diff --git a/.gitea/workflows/stage-author-bootstrap.yml b/.gitea/workflows/stage-author-bootstrap.yml new file mode 100644 index 00000000..6e911249 --- /dev/null +++ b/.gitea/workflows/stage-author-bootstrap.yml @@ -0,0 +1,42 @@ +name: Stage author bootstrap (dedicated repair) +on: + push: + branches: + - ops/author-bootstrap-stage-rehearse + - ops/author-bootstrap-stage-apply +jobs: + bootstrap: + runs-on: canina + steps: + - name: Exact SHA build then isolated rehearsal and authorized repair + env: + GITHUB_SHA: ${{ github.sha }} + GITHUB_REF: ${{ github.ref }} + GITHUB_ACTIONS: 'true' + STAGE_AUTHOR_BOOTSTRAP_REVIEWED_SHA: ${{ secrets.STAGE_AUTHOR_BOOTSTRAP_REVIEWED_SHA }} + # Path only, NOT a token value. Parent supplies an existing private file + # visible to the runner; absent file blocks repair AFTER image build. + AUTHOR_BOOTSTRAP_TOKEN_FILE: ${{ secrets.STAGE_AUTHOR_BOOTSTRAP_TOKEN_FILE }} + run: | + set -eu + set +x + umask 077 + case "$GITHUB_REF" in + refs/heads/ops/author-bootstrap-stage-rehearse|refs/heads/ops/author-bootstrap-stage-apply) ;; + *) exit 2 ;; + esac + test "$STAGE_AUTHOR_BOOTSTRAP_REVIEWED_SHA" = "$GITHUB_SHA" + export no_proxy="git.parsaaghayi.ir,localhost,127.0.0.1,87.248.133.138" + echo "87.248.133.138 git.parsaaghayi.ir" >> /etc/hosts + unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY + root=$(mktemp -d) + chmod 700 "$root" + git init "$root/source" + git -C "$root/source" fetch --depth=1 https://git.parsaaghayi.ir/parsa/canina.git "$GITHUB_SHA" + git -C "$root/source" checkout --detach FETCH_HEAD + test "$(git -C "$root/source" rev-parse HEAD)" = "$GITHUB_SHA" + export AUTHOR_BOOTSTRAP_EVIDENCE="$root/evidence" + printf 'Private Stage evidence directory (retained on failure): %s\n' "$root/evidence" + python3 "$root/source/scripts/stage-author-bootstrap/ci.py" + # Retain private dumps locally; never upload archive or credential files. + printf 'Private Stage evidence directory: %s\n' "$root/evidence" diff --git a/backend/prisma/migrations/20261028160000_public_author_identity/migration.sql b/backend/prisma/migrations/20261028160000_public_author_identity/migration.sql new file mode 100644 index 00000000..e482c16f --- /dev/null +++ b/backend/prisma/migrations/20261028160000_public_author_identity/migration.sql @@ -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) +); diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 43765881..afafc69b 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -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() diff --git a/backend/src/admin/admin-stage-author-restoration.controller.spec.ts b/backend/src/admin/admin-stage-author-restoration.controller.spec.ts index 9fb8dcff..a1209ca0 100644 --- a/backend/src/admin/admin-stage-author-restoration.controller.spec.ts +++ b/backend/src/admin/admin-stage-author-restoration.controller.spec.ts @@ -34,8 +34,18 @@ describe("AdminController - Stage Author Restoration endpoint", () => { controller = module.get(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); diff --git a/backend/src/admin/admin.controller.ts b/backend/src/admin/admin.controller.ts index 12e3e0ae..03b35814 100644 --- a/backend/src/admin/admin.controller.ts +++ b/backend/src/admin/admin.controller.ts @@ -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"); } diff --git a/backend/src/admin/stage-author-restoration.service.spec.ts b/backend/src/admin/stage-author-restoration.service.spec.ts index 38a7f71a..65232578 100644 --- a/backend/src/admin/stage-author-restoration.service.spec.ts +++ b/backend/src/admin/stage-author-restoration.service.spec.ts @@ -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(); }); }); }); diff --git a/backend/src/admin/stage-author-restoration.service.ts b/backend/src/admin/stage-author-restoration.service.ts index eda884c0..1316b497 100644 --- a/backend/src/admin/stage-author-restoration.service.ts +++ b/backend/src/admin/stage-author-restoration.service.ts @@ -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>` + 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 }); } } diff --git a/backend/src/auth/auth.controller.ts b/backend/src/auth/auth.controller.ts index 13da0605..c47e72ef 100644 --- a/backend/src/auth/auth.controller.ts +++ b/backend/src/auth/auth.controller.ts @@ -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, ) { diff --git a/backend/src/auth/auth.service.ts b/backend/src/auth/auth.service.ts index 5aff004c..cf3d874c 100644 --- a/backend/src/auth/auth.service.ts +++ b/backend/src/auth/auth.service.ts @@ -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, diff --git a/backend/src/auth/jwt-auth.guard.ts b/backend/src/auth/jwt-auth.guard.ts index 9738ace3..b32fc34e 100644 --- a/backend/src/auth/jwt-auth.guard.ts +++ b/backend/src/auth/jwt-auth.guard.ts @@ -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; } } diff --git a/backend/src/auth/jwt.strategy.ts b/backend/src/auth/jwt.strategy.ts index c27e89a8..039c8957 100644 --- a/backend/src/auth/jwt.strategy.ts +++ b/backend/src/auth/jwt.strategy.ts @@ -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] || ''; diff --git a/backend/src/auth/public-author.spec.ts b/backend/src/auth/public-author.spec.ts new file mode 100644 index 00000000..2c97bf3d --- /dev/null +++ b/backend/src/auth/public-author.spec.ts @@ -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"\)/); + }); +}); diff --git a/backend/src/auth/stage-test-principal.ts b/backend/src/auth/stage-test-principal.ts index 850f7010..75d9b240 100644 --- a/backend/src/auth/stage-test-principal.ts +++ b/backend/src/auth/stage-test-principal.ts @@ -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'); } diff --git a/backend/src/auth/stage-test-session-security.spec.ts b/backend/src/auth/stage-test-session-security.spec.ts index c67f0036..68b551b5 100644 --- a/backend/src/auth/stage-test-session-security.spec.ts +++ b/backend/src/auth/stage-test-session-security.spec.ts @@ -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'); diff --git a/backend/src/common/guards/human-admin.guard.ts b/backend/src/common/guards/human-admin.guard.ts index c060446b..e280b4d5 100644 --- a/backend/src/common/guards/human-admin.guard.ts +++ b/backend/src/common/guards/human-admin.guard.ts @@ -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; } diff --git a/backend/src/common/guards/roles.guard.ts b/backend/src/common/guards/roles.guard.ts index a716c3ed..4ab41261 100644 --- a/backend/src/common/guards/roles.guard.ts +++ b/backend/src/common/guards/roles.guard.ts @@ -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(); + 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(); - const user = request.user; if (!user || !user.role) { throw new ForbiddenException("شما دسترسی لازم برای این بخش را ندارید"); } diff --git a/backend/src/maintenance/main.ts b/backend/src/maintenance/main.ts new file mode 100644 index 00000000..e21f26f3 --- /dev/null +++ b/backend/src/maintenance/main.ts @@ -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; + }); +} diff --git a/backend/src/maintenance/maintenance-prisma.service.ts b/backend/src/maintenance/maintenance-prisma.service.ts new file mode 100644 index 00000000..1d4810e5 --- /dev/null +++ b/backend/src/maintenance/maintenance-prisma.service.ts @@ -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 { + await this.$connect(); + } +} diff --git a/backend/src/maintenance/maintenance.controller.ts b/backend/src/maintenance/maintenance.controller.ts new file mode 100644 index 00000000..610cdff4 --- /dev/null +++ b/backend/src/maintenance/maintenance.controller.ts @@ -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(); + } +} diff --git a/backend/src/maintenance/maintenance.module.ts b/backend/src/maintenance/maintenance.module.ts new file mode 100644 index 00000000..2de12478 --- /dev/null +++ b/backend/src/maintenance/maintenance.module.ts @@ -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 {} diff --git a/backend/src/maintenance/maintenance.spec.ts b/backend/src/maintenance/maintenance.spec.ts new file mode 100644 index 00000000..c73c8612 --- /dev/null +++ b/backend/src/maintenance/maintenance.spec.ts @@ -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 = {}, 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(); + }); +}); diff --git a/backend/src/reviews/reviews.service.ts b/backend/src/reviews/reviews.service.ts index f110fdf3..214a4164 100644 --- a/backend/src/reviews/reviews.service.ts +++ b/backend/src/reviews/reviews.service.ts @@ -46,7 +46,7 @@ export class ReviewsService { "کاربر کنینا"; } if (!resolvedPhone) { - resolvedPhone = user.mobile; + resolvedPhone = user.mobile ?? undefined; } } } diff --git a/backend/src/tickets/tickets.service.ts b/backend/src/tickets/tickets.service.ts index 5c75e538..3fd67dc3 100644 --- a/backend/src/tickets/tickets.service.ts +++ b/backend/src/tickets/tickets.service.ts @@ -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: { diff --git a/scripts/stage-author-bootstrap/README.md b/scripts/stage-author-bootstrap/README.md new file mode 100644 index 00000000..d8484e40 --- /dev/null +++ b/scripts/stage-author-bootstrap/README.md @@ -0,0 +1,40 @@ +# Stage-only public author bootstrap + +Implemented locally, **not executed against Stage**. No production mode, commit, push or recovery-gate override. + +## Official operation path + +1. Review/commit the integrated backend auth, public-author restoration service, Prisma client/schema, versioned SQL and these scripts/workflow together. This shared worktree is not yet a releasable SHA. +2. Independently approve that exact SHA in repository secret `STAGE_AUTHOR_BOOTSTRAP_REVIEWED_SHA` through existing authorized repository administration. No new API token is needed by these scripts. Gitea 1.22 uses exact push refs, not workflow_dispatch. +3. Push the **same reviewed commit**, only when authorized, to `ops/author-bootstrap-stage-rehearse` first, then `ops/author-bootstrap-stage-apply`. The new `.gitea/workflows/stage-author-bootstrap.yml` does not call deploy.sh: the existing normal Stage recovery gate cannot pass before this repair. +4. CI fetches the immutable event SHA and invokes `ci.py`. The driver builds only `backend/Dockerfile` with revision label and records its immutable image ID **before any credential-file prerequisites**. No migrate, seed, app recreation or live DDL occurs during build. Build failure blocks the operation. +5. Existing Stage runtime env is read privately from `canino_backend_stage` into mode0600 runner files, with exact DB URL identity validation. Nothing is printed. Clone config overrides database/Redis with isolated loopback instances while retaining the existing Stage JWT verification configuration. No JWT is minted and no auth guard is bypassed. Do not upload any env files or dumps. +6. Parent browser assistance must provide a currently valid **human admin** bearer privately in a mode0600 regular file visible to the CI runner. Set repository secret `STAGE_AUTHOR_BOOTSTRAP_TOKEN_FILE` to its **path**, not token value. No implicit host path, credential, token or runner mount is invented here. Missing prerequisite blocks repair *after* the image build. `/opt/data/cache/scratch/author-bootstrap-parent-assistance.json` describes the outstanding browser handoff; that agent-local path is not automatically runner-visible. +7. Rehearsal must pass before apply: fixed Stage identity and orphan baseline; retained original full dump; expected original FK restore failure; new clone pre-data/data; two transactional schema applies; authenticated API once; all post-data; new repaired dump restored fully into another clean clone. Original invalid archive is never overwritten or relabeled clean. +8. Apply repeats the entire rehearsal, rechecks Stage identity/lock, applies one live schema transaction in dedicated exact-SHA CI, then starts a **separate temporary maintenance API** with `STAGE_AUTHOR_RESTORATION_MODE=maintenance`. It shares the fixed Stage backend network namespace for existing DB DNS and real Redis blacklist validation, but HTTP is forced to loopback `127.0.0.1:39071`, never published, avoiding existing port3000. It runs immutable image `node` directly, without startup migration/seed. The only business writes are the authenticated restoration API. POST is never automatically retried after ambiguity. +9. Rerun the **unchanged** full Stage recovery gate and normal release acceptance afterward. This receipt is not live recovery/deployment acceptance. If live DDL succeeds but API fails, inspect retained evidence before deciding any recovery; do not blindly rerun the orphan-baseline tool. Prisma ledger remains untouched; SQL is a separately applied Stage bootstrap artifact, not migrate-deploy/resolve. + +Clone authentication uses both restored Stage user/session rows and a read-only Stage Redis RDB snapshot in a disposable no-network Redis. An empty blacklist would silently accept revoked tokens and is deliberately not substituted. The clone backend has `STAGE_AUTHOR_RESTORATION_MODE=rehearsal`. Snapshot staleness is bounded by the operation; live authentication independently uses real Stage Redis. + +## Practical prerequisites/blockers + +- Source is currently uncommitted; a reviewed exact SHA and authorized official ref push remain parent responsibilities. +- Approved browser bearer and secure CI-runner-visible file handoff are outstanding. Do not expose token values in chat/logs or create replacement tokens. +- Host read-only inspection confirmed Stage backend port3000, Redis `redis_stage:6379`, and no explicit `JWT_ACCESS_SECRET`/`JWT_SECRET` env. Existing auth code's configured fallback is reused unchanged; no replacement secret is synthesized. This existing fallback should be reviewed separately, never rotated during repair without coordinating sessions. +- Runner must have Docker/Python/git, sufficient disk for three DB clones, one Redis clone and two full archives, and the existing host deployment lock inode. All operations have bounded individual deadlines. No pre-existing lock helper is reclaimed. +- PostgreSQL image ID is pinned in operation.py and must match the exact Stage DB image or execution fails closed. +- Private env/archive evidence is retained in a mode0700 runner directory, printed before execution. Delete credential copies using an explicitly approved retention/cleanup action afterward; never generic prune/delete other workers' containers or images. Owned disposable containers/anonymous volumes are removed by captured ID in reverse order. Immutable backend image is retained for the subsequent official operation, not discarded as a test image. + +## Tests + +``` +python3 -m unittest discover -s scripts/stage-author-bootstrap -v +python3 -m unittest discover -s scripts/stage-schema -v +python3 scripts/stage-author-bootstrap/operation.py --help +``` + +Tests exercise the actual CI Python entrypoint with command doubles (build/rehearse/apply, missing token after build, wrong SHA/ref before transport, build failure), maintenance isolation and original/post-data restore failure ordering. They are offline tests, **not CI execution or real database rehearsal**. + +For controlled local clone-only diagnostic use, `operation.py rehearse --sha ... --sql-sha256 ... --backend-image sha256:... --clone-env-file ... --clone-token-file ... --evidence ...` accepts explicit private files. Live `apply-schema` additionally requires `--live-env-file`, independently reviewed SHA and the exact dedicated CI event/ref; do not spoof CI variables on SSH. Backend image revision label must match source SHA. SQL digest and committed tool/workflow contents are verified in CI. + +CHECK scope is row-local; application auth must deny public-author principals centrally. Authors must be the five genuine configured UUIDs, `isPublicAuthor=true`, role `User_PetOwner`, no mobile/email/password/session/expiry and zero balances. No invented identity, phone number or privileged role is permitted. diff --git a/scripts/stage-author-bootstrap/ci.py b/scripts/stage-author-bootstrap/ci.py new file mode 100644 index 00000000..803c38c6 --- /dev/null +++ b/scripts/stage-author-bootstrap/ci.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +"""Dedicated exact-ref CI driver. No deploy, migration CLI, token mint or SSH apply.""" +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import re +import subprocess +import sys + +HERE = Path(__file__).resolve().parent +spec = importlib.util.spec_from_file_location('bootstrap', HERE / 'operation.py') +assert spec is not None and spec.loader is not None +op = importlib.util.module_from_spec(spec) +spec.loader.exec_module(op) + + +def run(env=os.environ, call=subprocess.run): + sha = env.get('GITHUB_SHA', '') + refs = {'refs/heads/ops/author-bootstrap-stage-rehearse': 'rehearse', + 'refs/heads/ops/author-bootstrap-stage-apply': 'apply-schema'} + if (env.get('GITHUB_ACTIONS') != 'true' or not re.fullmatch('[a-f0-9]{40}', sha) + or env.get('STAGE_AUTHOR_BOOTSTRAP_REVIEWED_SHA') != sha + or env.get('GITHUB_REF') not in refs): + raise ValueError('Dedicated reviewed exact-SHA CI required') + def command(args, **kwargs): + return call(args, check=True, timeout=kwargs.pop('timeout', 180), **kwargs) + head = command(['git', '-C', str(op.ROOT), 'rev-parse', 'HEAD'], capture_output=True, text=True).stdout.strip() + if head != sha: raise ValueError('Source SHA mismatch') + evidence = Path(env['AUTHOR_BOOTSTRAP_EVIDENCE']) + evidence.mkdir(mode=0o700, parents=True, exist_ok=False) + os.chmod(evidence, 0o700) + # Build BEFORE credential prerequisites: missing browser-assisted token does + # not prevent the official immutable build needed for this repair. + iid = evidence / 'backend.iid' + command(['docker', 'build', '--label', 'org.opencontainers.image.revision=' + sha, + '--build-arg', 'NPM_REGISTRY=https://registry.parsaaghayi.ir/repository/npm/', + '--iidfile', str(iid), str(op.ROOT / 'backend')], timeout=1800) + image = iid.read_text().strip() + if not re.fullmatch('sha256:[a-f0-9]{64}', image): raise ValueError('Invalid build image ID') + # Reuse existing Stage runtime config privately; never invent JWT secrets. + # CLI writes no configuration to stdout/logs. Runner-local env-file is sent + # by Docker CLI even when its daemon is on another filesystem. + raw = command(['docker', 'inspect', op.BACKEND], capture_output=True).stdout + info = json.loads(raw)[0] + if info.get('Name') != '/' + op.BACKEND or not info.get('State', {}).get('Running'): + raise ValueError('Existing Stage runtime unavailable') + values = dict(x.split('=', 1) for x in info['Config']['Env']) + from urllib.parse import urlparse + url = urlparse(values.get('DATABASE_URL', '')) + if url.hostname != op.STAGE or url.path != '/caninodb_stage' or url.query or url.fragment: + raise ValueError('Existing Stage runtime DB identity mismatch') + if any('\n' in v or '\r' in v for v in values.values()): raise ValueError('Multiline env refused') + live_env = evidence / 'stage.env' + op.private_write(live_env, '\n'.join(k + '=' + v for k, v in values.items()).encode()) + clone_env = evidence / 'clone.env' + values.update(REDIS_HOST='127.0.0.1', REDIS_PORT='16379', REDIS_PASSWORD='') + op.private_write(clone_env, '\n'.join(k + '=' + v for k, v in values.items()).encode()) + env = dict(env, AUTHOR_BOOTSTRAP_CLONE_ENV_FILE=str(clone_env), AUTHOR_BOOTSTRAP_LIVE_ENV_FILE=str(live_env)) + args = [sys.executable, str(HERE / 'operation.py'), refs[env['GITHUB_REF']], '--sha', sha, + '--sql-sha256', hashlib.sha256((op.ROOT / op.SQL_PATH).read_bytes()).hexdigest(), + '--backend-image', image, '--evidence', str(evidence / 'operation')] + for flag, key in [('--clone-env-file', 'AUTHOR_BOOTSTRAP_CLONE_ENV_FILE'), + ('--clone-token-file', 'AUTHOR_BOOTSTRAP_TOKEN_FILE')]: + path = env.get(key) + if not path: raise ValueError('Image built; parent-assisted private prerequisite missing: ' + key) + op.private_file(Path(path)) + args += [flag, path] + if refs[env['GITHUB_REF']] == 'apply-schema': + path = env.get('AUTHOR_BOOTSTRAP_LIVE_ENV_FILE') + if not path: raise ValueError('Existing private Stage env required') + op.private_file(Path(path)) + args += ['--live-env-file', path] + command(args, timeout=1800) + return image + + +if __name__ == '__main__': + run() diff --git a/scripts/stage-author-bootstrap/operation.py b/scripts/stage-author-bootstrap/operation.py new file mode 100644 index 00000000..87730846 --- /dev/null +++ b/scripts/stage-author-bootstrap/operation.py @@ -0,0 +1,285 @@ +#!/usr/bin/env python3 +"""Explicit Stage-only attribution bootstrap. Never invokes or bypasses recovery gate.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import stat + +# Dedicated lifecycle-safe app: no full AppModule startup or listener monkeypatch. +LOOPBACK_JS = "require('./dist/maintenance/main.js').startMaintenance().catch(()=>{console.error('Maintenance startup failed');process.exit(1)});" +BACKEND = 'canino_backend_stage' + + +def private_file(path): + if path.is_symlink() or not stat.S_ISREG(path.stat().st_mode) or path.stat().st_mode & 0o077: + raise ValueError('Private regular credential files required') + + +def check_image(d, image, sha): + info = json.loads(d.run(['image', 'inspect', image]))[0] + if info.get('Id') != image or info.get('Config', {}).get('Labels', {}).get('org.opencontainers.image.revision') != sha: + raise ValueError('Backend image revision does not match exact reviewed SHA') + + +def api(d, backend, token): + # No retry: a lost response can follow a committed transaction. + result = json.loads(d.run(['exec', '-i', backend, 'node', '-e', API_JS], token, timeout=40)) + if {a.get('id') for a in result.get('authors', [])} != AUTHOR_IDS: + raise ValueError('API returned unexpected author identities') + return result + + +def api_ready(d, backend): + for _ in range(30): + try: + if d.run(['inspect', '-f', '{{.State.Running}}', backend]).strip() != b'true': + raise ValueError('Maintenance process exited') + d.run(['exec', backend, 'node', '-e', "fetch('http://127.0.0.1:39071/api/admin/users/stage-author-restoration',{method:'POST',signal:AbortSignal.timeout(2000)}).then(r=>{if(r.status!==401)process.exit(1)}).catch(()=>process.exit(1))"], timeout=5) + return + except subprocess.CalledProcessError: + time.sleep(1) + raise ValueError('Maintenance API readiness failed') + + +def maintenance(d, image, env_file, token, owned): + # Shares only the fixed Stage backend network namespace, with NO published + # port and loopback-only HTTP. Stage DNS/Redis keep the real blacklist validator. + info = json.loads(d.run(['inspect', BACKEND]))[0] + if info.get('Name') != '/' + BACKEND or not info.get('State', {}).get('Running'): + raise ValueError('Stage backend namespace unavailable') + cid = d.run(['run', '-d', '--pull=never', '--network=container:' + info['Id'], + '--env-file', str(env_file), '-e', 'APP_ENV=stage', '-e', 'PORT=39071', + '-e', 'STAGE_AUTHOR_RESTORATION_ENABLED=true', + '-e', 'STAGE_AUTHOR_RESTORATION_MODE=maintenance', image, + 'node', '-e', LOOPBACK_JS]).decode().strip() + owned.append(cid) + api_ready(d, cid) + return api(d, cid, token) + + +import subprocess +import time +import uuid + +ROOT = Path(__file__).resolve().parents[2] +SQL_PATH = 'backend/prisma/migrations/20261028160000_public_author_identity/migration.sql' +POSTGRES_IMAGE = 'sha256:de3a4eab8fdfa507ea92aac488b916b08089e515db49b055fe71dfa271ba3a28' +STAGE = 'canino_db_stage' +AUTHOR_IDS = {'14490d36-52fc-40be-8637-b7b04b8302f8', '4e0d830c-0125-4f08-8cb7-c5ae0a38cee7', + '63d38117-f864-4af6-afa0-ae5b05255f57', '7b1e51d1-8c32-4a3c-804f-948d706aef36', + 'f57e0f98-efee-4fa1-90ef-67bf84cafad4'} +ORPHANS_SQL = """SELECT json_build_object('count',count(*),'ids',array_agg(DISTINCT b.author_id::text)) +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;""" + +def check_orphans(raw): + value = json.loads(raw) + if value.get('count') != 52 or set(value.get('ids') or []) != AUTHOR_IDS: + raise ValueError('Reviewed 52-blog/five-genuine-author orphan baseline changed') + +def check_identity(info): + if (info.get('Name') != '/' + STAGE or info.get('Image') != POSTGRES_IMAGE + or not re.fullmatch('[0-9a-f]{64}', info.get('Id', '')) + or not info.get('State', {}).get('Running') + or 'POSTGRES_DB=caninodb_stage' not in info.get('Config', {}).get('Env', []) + or not any(m.get('Destination') == '/var/lib/postgresql/data' and m.get('RW') + and m.get('Type') in ('bind', 'volume') for m in info.get('Mounts', []))): + raise ValueError('Exact Stage database container identity required') + return info['Id'] + +class Docker: + def run(self, args, data=None, timeout=180): + return subprocess.run(['docker'] + args, input=data, + stdin=subprocess.DEVNULL if data is None else None, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + timeout=timeout, check=True).stdout + def sql(self, cid, query, live=False): + command = ['sh', '-c', 'exec psql -X -qAt -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB"'] if live else [ + 'psql', '-h', '127.0.0.1', '-U', 'postgres', '-d', 'rehearsal', '-X', '-qAt', '-v', 'ON_ERROR_STOP=1'] + return self.run(['exec', '-i', cid] + command, query.encode()).decode().strip() + +def transaction(sql): + return "BEGIN; SET LOCAL lock_timeout='5s'; SET LOCAL statement_timeout='60s'; SELECT pg_advisory_xact_lock(72707369); SET LOCAL search_path=public;\n" + sql + '\nCOMMIT;' + +def restore(d, cid, backup, section=None): + args = ['exec', '-i', cid, 'pg_restore', '-h', '127.0.0.1', '-U', 'postgres', '-d', 'rehearsal', '--no-owner', '--no-acl', '--exit-on-error'] + if section: args += ['--section=' + section] + d.run(args, backup, timeout=300) + +def private_write(path, data): + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(fd, 'wb') as f: + f.write(data) + f.flush() + os.fsync(f.fileno()) + +def readiness(d, cid): + for _ in range(60): + try: + d.run(['exec', cid, 'pg_isready', '-h', '127.0.0.1', '-U', 'postgres', '-d', 'rehearsal'], timeout=5) + return + except subprocess.CalledProcessError: time.sleep(1) + raise ValueError('Final TCP server readiness failed') + +# Returns only validated contract metadata. Token never enters argv, env or logs. +API_JS = r'''const fs=require('fs'); const token=fs.readFileSync(0,'utf8').trim(); +(async()=>{let r=await fetch('http://127.0.0.1:39071/api/admin/users/stage-author-restoration',{ +method:'POST',headers:{Authorization:'Bearer '+token},signal:AbortSignal.timeout(30000)}); +if(!r.ok)throw Error('API status '+r.status);let x=await r.json(); +if(x.success!==true||x.totalConfigured!==5||x.restoredCount+x.existingCount!==5)throw Error('API contract'); +process.stdout.write(JSON.stringify(x));})().catch(()=>{process.exit(1)});''' + +def rehearse(d, backup, sql, backend_image, env_file, token, owned, evidence): + def clone(): + cid = d.run(['run', '-d', '--pull=never', '--network=none', '--name', 'author-bootstrap-' + uuid.uuid4().hex[:16], + '-e', 'POSTGRES_HOST_AUTH_METHOD=trust', '-e', 'POSTGRES_DB=rehearsal', POSTGRES_IMAGE]).decode().strip() + owned.append(cid) + readiness(d, cid) + return cid + # Preserve proof of the known invalid original: no constraints disabled, no claim of clean recovery. + original = clone() + try: + restore(d, original, backup) + except subprocess.CalledProcessError as e: + error = e.stderr or b'' + private_write(evidence / 'original-full-restore.stderr', error) + if b'blogs_author_id_fkey' not in error or b'foreign key constraint' not in error: + raise ValueError('Original restore failed for an unreviewed reason') from e + else: + raise ValueError('Expected original orphan-FK restore failure absent; review baseline before bootstrap') + cid = clone() + restore(d, cid, backup, 'pre-data') + restore(d, cid, backup, 'data') + check_orphans(d.sql(cid, ORPHANS_SQL)) + d.sql(cid, transaction(sql)) + d.sql(cid, transaction(sql)) + # Carry the real token blacklist into the isolated namespace, not an empty + # Redis that would silently accept revoked sessions. SYNC reads keys only. + redis_info = json.loads(d.run(['inspect', 'canino_redis_stage']))[0] + if redis_info.get('Name') != '/canino_redis_stage' or not redis_info.get('State', {}).get('Running'): + raise ValueError('Stage session validator unavailable') + rdb = d.run(['exec', 'canino_redis_stage', 'sh', '-c', + 'export REDISCLI_AUTH="$REDIS_PASSWORD"; exec redis-cli --rdb /dev/stdout'], timeout=120) + if not rdb.startswith(b'REDIS'): raise ValueError('Invalid Stage blacklist snapshot') + redis = d.run(['create', '--pull=never', '--network=container:' + cid, + redis_info['Image'], 'redis-server', '--bind', '127.0.0.1', + '--port', '16379', '--save', '', '--appendonly', 'no']).decode().strip() + owned.append(redis) + import io + import tarfile + archive = io.BytesIO() + with tarfile.open(fileobj=archive, mode='w') as tar: + entry = tarfile.TarInfo('dump.rdb'); entry.size = len(rdb); entry.mode = 0o600 + entry.uid = 0; entry.gid = 0 + tar.addfile(entry, io.BytesIO(rdb)) + d.run(['cp', '-', redis + ':/data/'], archive.getvalue()) + d.run(['start', redis]) + for _ in range(30): + try: + if d.run(['exec', redis, 'redis-cli', '-p', '16379', 'PING']).strip() == b'PONG': break + except subprocess.CalledProcessError: pass + time.sleep(1) + else: raise ValueError('Clone session validator readiness failed') + backend = d.run(['run', '-d', '--pull=never', '--network=container:' + cid, + '--env-file', str(env_file), '-e', 'DATABASE_URL=postgresql://postgres@127.0.0.1:5432/rehearsal', + '-e', 'APP_ENV=stage', '-e', 'PORT=39071', '-e', 'STAGE_AUTHOR_RESTORATION_ENABLED=true', + '-e', 'STAGE_AUTHOR_RESTORATION_MODE=rehearsal', + backend_image, 'node', '-e', LOOPBACK_JS]).decode().strip() + owned.append(backend) + api_ready(d, backend) + result = api(d, backend, token) + restore(d, cid, backup, 'post-data') # Mandatory ALL post-data, exit on first failure. + # A repaired clone is not the original archive: prove full recovery of a NEW archive separately. + repaired = d.run(['exec', cid, 'pg_dump', '-h', '127.0.0.1', '-U', 'postgres', '-d', 'rehearsal', '--no-owner', '--no-acl', '-Fc']) + if not repaired: raise ValueError('Empty repaired clone archive') + private_write(evidence / 'repaired-clone.dump', repaired) + final = clone() + restore(d, final, repaired) + return result, hashlib.sha256(repaired).hexdigest() + +def execute(d, mode, sql, backend_image, env_file, token, evidence, live_env_file=None): + owned = [] + try: + runner = d.run(['inspect', '-f', '{{.Config.Image}}', 'gitea_runner']).decode().strip() + lock = d.run(['create', '--name', 'canina-stage-deploy-lock', '--pull=never', '--network=none', + '--cap-drop=ALL', '--security-opt=no-new-privileges', '--mount', + 'type=bind,src=/opt/services/canina,dst=/host-canina,readonly', '--entrypoint', '/bin/sh', runner, '-c', + 'exec 91)) + else: + self.assertEqual(ci.run(env,call),'sha256:'+'b'*64) + operation = calls[-1] + self.assertEqual(operation[2], 'apply-schema' if ref.endswith('apply') else 'rehearse') + self.assertLess(next(i for i,a in enumerate(calls) if a[:2]==['docker','build']),len(calls)-1) + self.assertIn('--live-env-file', operation) if ref.endswith('apply') else self.assertNotIn('--live-env-file', operation) + clone = (root/'evidence/clone.env').read_text() + self.assertIn('REDIS_HOST=127.0.0.1',clone) + self.assertIn('JWT_SECRET=existing-test-secret',clone) + self.assertEqual((root/'evidence/clone.env').stat().st_mode & 0o777,0o600) + return calls + + def test_real_ci_driver_rehearse(self): self.exercise('refs/heads/ops/author-bootstrap-stage-rehearse') + def test_real_ci_driver_apply(self): self.exercise('refs/heads/ops/author-bootstrap-stage-apply') + def test_missing_token_still_builds(self): + calls = self.exercise('refs/heads/ops/author-bootstrap-stage-rehearse',missing=True) + self.assertTrue(any(a[:2]==['docker','build'] for a in calls)) + def test_failed_build_never_operates(self): self.exercise('refs/heads/ops/author-bootstrap-stage-apply',build_fail=True) + def test_wrong_ref_sha_no_transport(self): + for ref, reviewed in [('refs/heads/develop','a'*40),('refs/heads/ops/author-bootstrap-stage-apply','b'*40)]: + with self.assertRaises(ValueError): + ci.run({'GITHUB_ACTIONS':'true','GITHUB_SHA':'a'*40,'GITHUB_REF':ref, + 'STAGE_AUTHOR_BOOTSTRAP_REVIEWED_SHA':reviewed}, lambda *a,**kw:self.fail('transport before binding')) + def test_workflow_exact_refs_and_real_driver(self): + text = (HERE.parents[1]/'.gitea/workflows/stage-author-bootstrap.yml').read_text() + self.assertIn('- ops/author-bootstrap-stage-rehearse',text) + self.assertIn('- ops/author-bootstrap-stage-apply',text) + self.assertIn('scripts/stage-author-bootstrap/ci.py',text) + self.assertNotIn('scripts/deploy.sh',text) + self.assertNotIn('workflow_dispatch',text) + + +class MaintenanceTests(unittest.TestCase): + def test_no_published_port_real_validator_and_single_post(self): + op=ci.op + calls=[] + class D: + def run(self,args,data=None,timeout=180): + calls.append((args,data)) + if args[0]=='inspect': return json.dumps([{'Id':'a'*64,'Name':'/canino_backend_stage','State':{'Running':True}}]).encode() + if args[0]=='run': return b'b'*64 + return b'' + owned=[] + with patch.object(op,'api_ready'), patch.object(op,'api',return_value={'success':True}) as api: + op.maintenance(D(),'sha256:'+'c'*64,Path('/private/stage.env'),b'opaque',owned) + api.assert_called_once() + command=calls[1][0] + self.assertIn('--network=container:'+'a'*64,command) + self.assertIn('STAGE_AUTHOR_RESTORATION_MODE=maintenance',command) + self.assertIn('PORT=39071',command) + self.assertNotIn('-p',command) + self.assertIn(op.LOOPBACK_JS,command) + self.assertEqual(owned,['b'*64]) + +if __name__ == '__main__': unittest.main() diff --git a/scripts/stage-author-bootstrap/test_execute.py b/scripts/stage-author-bootstrap/test_execute.py new file mode 100644 index 00000000..394b4397 --- /dev/null +++ b/scripts/stage-author-bootstrap/test_execute.py @@ -0,0 +1,74 @@ +import importlib.util +import json +from pathlib import Path +import subprocess +import tempfile +import unittest +from unittest.mock import patch + +HERE=Path(__file__).resolve().parent +spec=importlib.util.spec_from_file_location('op',HERE/'operation.py') +assert spec is not None and spec.loader is not None +op=importlib.util.module_from_spec(spec) +spec.loader.exec_module(op) + + +class ExecuteTests(unittest.TestCase): + def test_recovery_failure_blocks_live_and_cleans_reverse(self): + self.exercise('recovery') + def test_empty_backup_blocks_rehearsal(self): + self.exercise('empty') + def test_contended_lock_never_removed(self): + self.exercise('lock') + def test_rehearse_never_writes_live(self): + self.exercise(None,mode='rehearse') + def test_apply_ddl_then_authenticated_api(self): + self.exercise(None) + def exercise(self,fail,mode='apply-schema'): + calls=[] + identity={'Id':'a'*64,'Name':'/'+op.STAGE,'Image':op.POSTGRES_IMAGE, + 'State':{'Running':True},'Config':{'Env':['POSTGRES_DB=caninodb_stage']}, + 'Mounts':[{'Destination':'/var/lib/postgresql/data','RW':True,'Type':'volume'}]} + class D: + def run(self,args,data=None,timeout=180): + calls.append(args) + if args[0]=='create': + if fail=='lock': raise subprocess.CalledProcessError(1,args) + return b'b'*64 + if args[0]=='logs': return b'LOCKED' + if args[:2]==['inspect',op.STAGE]: return json.dumps([identity]).encode() + if args[0]=='inspect': return b'true' + if 'pg_dump' in ' '.join(args): return b'' if fail=='empty' else b'original' + return b'' + def sql(self,cid,query,live=False): + if query==op.ORPHANS_SQL: return json.dumps({'count':52,'ids':list(op.AUTHOR_IDS)}) + if 'READ ONLY' in query: return 'caninodb_stage' + calls.append(['live-ddl']) + def rehearsal(d,backup,sql,image,env,token,owned,evidence): + owned.append('c'*64) + calls.append(['recovery']) + if fail=='recovery': raise ValueError('restore failed') + return {'success':True},'hash' + def maintenance(*args): + calls.append(['live-api']) + return {'success':True} + with tempfile.TemporaryDirectory(dir='/opt/data/cache/scratch') as tmp, patch.object(op,'rehearse',side_effect=rehearsal),patch.object(op,'maintenance',side_effect=maintenance): + if fail: + with self.assertRaises((ValueError,subprocess.CalledProcessError)): + op.execute(D(),mode,'SQL','image',Path(tmp)/'env',b'token',Path(tmp),Path(tmp)/'live-env') + self.assertFalse((Path(tmp)/'receipt.json').exists()) + self.assertNotIn(['live-ddl'],calls) + self.assertNotIn(['live-api'],calls) + else: + result=op.execute(D(),mode,'SQL','image',Path(tmp)/'env',b'token',Path(tmp),Path(tmp)/'live-env') + self.assertEqual(result['live_business_writes'],mode=='apply-schema') + if mode=='apply-schema': + self.assertLess(calls.index(['recovery']),calls.index(['live-ddl'])) + self.assertLess(calls.index(['live-ddl']),calls.index(['live-api'])) + else: + self.assertNotIn(['live-ddl'],calls) + self.assertNotIn(['live-api'],calls) + removed=[a[-1] for a in calls if a[0]=='rm'] + self.assertEqual(removed, [] if fail=='lock' else ['b'*64] if fail=='empty' else ['c'*64,'b'*64]) + +if __name__=='__main__': unittest.main() diff --git a/scripts/stage-author-bootstrap/test_operation.py b/scripts/stage-author-bootstrap/test_operation.py new file mode 100644 index 00000000..3ca55420 --- /dev/null +++ b/scripts/stage-author-bootstrap/test_operation.py @@ -0,0 +1,72 @@ +import importlib.util +from pathlib import Path +import unittest + +HERE = Path(__file__).resolve().parent + +class BootstrapTests(unittest.TestCase): + def test_stage_identity_fails_closed(self): + self.assertTrue((HERE / 'operation.py').exists(), 'Stage bootstrap operation is missing') + spec = importlib.util.spec_from_file_location('bootstrap', HERE / 'operation.py') + op = importlib.util.module_from_spec(spec) + spec.loader.exec_module(op) + identity = {'Id': 'a'*64, 'Name': '/canino_db_stage', 'Image': op.POSTGRES_IMAGE, + 'State': {'Running': True}, 'Config': {'Env': ['POSTGRES_DB=caninodb_stage']}, + 'Mounts': [{'Destination':'/var/lib/postgresql/data','RW':True,'Type':'volume'}]} + self.assertEqual(op.check_identity(identity), 'a'*64) + for key, value in [('Name','/canino_db_prod'), ('Image','other'), ('Id','short')]: + with self.subTest(key=key): + with self.assertRaises(ValueError): op.check_identity({**identity,key:value}) + +class RecoveryTests(unittest.TestCase): + def test_clone_order_and_postdata_failure_no_recovery_claim(self): + spec = importlib.util.spec_from_file_location('bootstrap', HERE / 'operation.py') + op = importlib.util.module_from_spec(spec) + spec.loader.exec_module(op) + from unittest.mock import patch + import subprocess + import tempfile + calls = [] + class Transport: + def run(self, args, data=None, timeout=180): + if args[:2] == ['inspect', 'canino_redis_stage']: + return b'[{"Name":"/canino_redis_stage","State":{"Running":true},"Image":"redis"}]' + if args[:2] == ['inspect', '-f']: return b'true' + if args[0] == 'create': return ('b'*64).encode() + if '--rdb /dev/stdout' in ' '.join(args): return b'REDISsnapshot' + if 'PING' in args: return b'PONG' + if args[0] == 'run': return ('a'*64).encode() + if 'pg_restore' in args: + section = next((x for x in args if x.startswith('--section=')), 'full') + calls.append(section) + if section in ('full','--section=post-data'): + raise subprocess.CalledProcessError(1, args, stderr=b'ERROR: insert or update on table "blogs" violates foreign key constraint "blogs_author_id_fkey"') + if 'node' in args and '-i' in args: + calls.append('api') + return __import__('json').dumps({'success':True,'totalConfigured':5,'restoredCount':5,'existingCount':0,'authors':[{'id':x} for x in op.AUTHOR_IDS]}).encode() + return b'' + def sql(self, cid, query): + if query == op.ORPHANS_SQL: + return __import__('json').dumps({'count':52,'ids':list(op.AUTHOR_IDS)}) + calls.append('ddl') + return '' + with tempfile.TemporaryDirectory(dir='/opt/data/cache/scratch') as tmp: + with patch.object(op, 'readiness'): + with self.assertRaises(subprocess.CalledProcessError): + op.rehearse(Transport(), b'archive', 'DDL', 'image', Path(tmp)/'env', b'token', [], Path(tmp)) + self.assertEqual(calls, ['full','--section=pre-data','--section=data','ddl','ddl','api','--section=post-data']) + self.assertFalse((Path(tmp)/'repaired-clone.dump').exists()) + +class MigrationTests(unittest.TestCase): + def test_strong_check_contract(self): + migration = HERE.parents[1] / 'backend/prisma/migrations/20261028160000_public_author_identity/migration.sql' + self.assertTrue(migration.exists(), 'Versioned migration missing') + sql = migration.read_text() + for fragment in ('DROP NOT NULL', 'is_public_author', 'mobile IS NOT NULL', 'mobile IS NULL', + 'email IS NULL', 'password IS NULL', "role = 'User_PetOwner'", 'stage_test_session IS NULL', + 'stage_test_generation IS NULL', 'auth_expires_at IS NULL', 'wallet_balance = 0'): + self.assertIn(fragment, sql) + self.assertNotIn('NOT VALID', sql) + self.assertNotRegex(sql.upper(), r'INSERT|UPDATE|DELETE|DISABLE TRIGGER') + +if __name__ == '__main__': unittest.main() diff --git a/specs/stage-author-restoration/bootstrap-repair.md b/specs/stage-author-restoration/bootstrap-repair.md new file mode 100644 index 00000000..caad407e --- /dev/null +++ b/specs/stage-author-restoration/bootstrap-repair.md @@ -0,0 +1,24 @@ +# Stage-only attribution bootstrap repair + +## Scope and authorization +Stage additive DDL and five genuine attribution identities only. Production, main, prices, stock, paid actions and approval modules remain prohibited. Existing 52 Blog author references remain unchanged. No contacts, credentials or privileges are copied from Production. + +## Design +`users.mobile` becomes physically nullable, but a validated CHECK continues requiring non-null mobile for every ordinary user. `is_public_author` defaults false. Public authors require no mobile/email/password, no auth/session markers, no balances and the baseline User_PetOwner value; the marker denies all authentication and permission guards independently of role. Unique non-null mobile semantics remain unchanged. + +The repair API requires genuine human-admin JWT verification, exact Stage database identity, explicit maintenance mode and actual loopback socket peer. A Serializable transaction preflights all five identities and the exact orphan distribution 16/2/3/14/17; partial/conflicting states fail before inserts. Replay requires all exact safe rows and zero orphans. + +The dedicated maintenance module imports no full app, seed or worker modules. Its Prisma provider only connects, never runs schema-creation hooks. Existing JWT, Redis revocation, role and human-admin guards are reused; API keys are denied. + +## Recovery gates +Retain original full dump and its expected FK restore failure. Disposable rehearsal restores pre-data and data, applies/replays reviewed DDL, performs the authenticated five-author API operation, restores ALL post-data, then dumps/restores the repaired clone fully. This does not certify the original invalid archive as clean. Live Stage DDL follows only successful rehearsal; live business rows are inserted exclusively by authenticated backend API. The unchanged normal full-data recovery gate remains mandatory afterward. + +## Verification obtained +- Actual PostgreSQL 16.2 migration integration: 18 checks passed, including real-user null-mobile rejection, prohibited author fields, duplicate real mobile, safe author rows, wrong database denial and idempotent DDL replay. +- Backend TypeScript build passed. +- Focused maintenance/auth/restoration suites: 83 tests passed; broader auth run: 61 passed. +- Bootstrap transport/workflow tests: 15 passed. Existing schema-operation tests: 17 passed. +- Full backend suite: 98 passed suites; two failures remain in unchanged wiki pagination expectation and PostgreSQL fixture construction with absent URL. Do not claim a clean full suite. + +## Outstanding execution prerequisites +Obtain parent-assisted genuine Stage human-admin bearer via private mode0600 file visible to the runner. Configure existing repository secret administration with exact reviewed SHA and private file path; never bearer contents in source/chat/logs. Execute dedicated rehearsal then apply workflow for that exact SHA. Verify actual clone full recovery, live API readback, unchanged normal recovery gate and normal exact-SHA Stage CI/image/live behavior. No live schema or data writes have been executed by this implementation work.