1
0
Fork 0
polaris-task-force/tests/int/notification-inbox-scope.int.spec.ts
Z8MB1E cc8a911502 test(vitest): parallel forks with per-worker database clones
Stage 2 of the int-suite speedup: pool=forks with fileParallelism and a
default cap of 8 (VITEST_MAX_FORKS), each fork cloning the template into
ptf_*_test_w<ID> via tests/vitest-worker-setup.ts; environment defaults
to node with jsdom opt-in docblocks on the six DOM-consuming specs; a
tiny reporter writes a failure marker so post-run cleanup keeps clones
after red runs (KEEP_TEST_DBS=1 forces keeping); pg pools cap at
TEST_PG_POOL_MAX=3 per boot in workers mode. Legacy serial mode stays
reachable by setting TEST_DATABASE_URI.

Notes from the gate G2 runs (Vitest 4.0.16): globalTeardown config was
removed in Vitest 4 entirely - cleanup now returns from globalSetup. The
pool scheduler only reuses worker processes when isolate:false, so this
per-file-fork stage lands short of the wall-time target and is expected
to be superseded by the gated isolate:false stage. Gate G2 warm serial
equivalent stays green via TEST_DATABASE_URI bisect mode.
2026-10-21 10:41:57 -04:00

217 lines
7.1 KiB
TypeScript

// jose (via payload's jwtSign) fails under jsdom: its module-level TextEncoder and
// the global Uint8Array come from different realms, so signing throws a TypeError.
import { getFieldsToSign, getPayload, jwtSign, Payload } from "payload";
import config from "@/payload.config";
import { randomUUID } from "node:crypto";
import { NextRequest } from "next/server";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { Role, User } from "@/payload-types";
import type { Permission } from "@/permissions";
import { GET } from "@/app/api/notifications/inbox/route";
import { invalidatePermissionCache } from "@/utils/access-control/loadUserPermissions";
let payload: Payload;
const RUN = `ntfinbox-${Date.now().toString(36)}`;
const TIMEOUT = 30_000;
/** Build a GET against the inbox route, optionally authenticated + scoped. */
function request(token?: string, scope?: "all" | "mine"): NextRequest {
const headers = new Headers();
if (token) headers.set("cookie", `payload-token=${token}`);
const url = new URL("http://localhost/api/notifications/inbox");
url.searchParams.set("limit", "12");
url.searchParams.set("sort", "-createdAt");
if (scope) url.searchParams.set("scope", scope);
return new NextRequest(url, { headers });
}
/**
* Mint a payload-token JWT for a user, mirroring the impersonation route:
* persist a session on the user doc, then sign with that session's sid.
*/
async function mintToken(userId: number): Promise<string> {
const collection = payload.collections.users.config;
const user = await payload.findByID({
collection: "users",
id: userId,
depth: 0,
overrideAccess: true,
});
const sid = randomUUID();
const now = new Date();
const expiresAt = new Date(now.getTime() + collection.auth.tokenExpiration * 1000);
const sessions = (user.sessions ?? []).filter(
(session) => new Date(session.expiresAt).getTime() > now.getTime(),
);
sessions.push({ id: sid, createdAt: now.toISOString(), expiresAt: expiresAt.toISOString() });
await payload.update({
collection: "users",
id: userId,
data: { sessions },
overrideAccess: true,
});
const { token } = await jwtSign({
fieldsToSign: getFieldsToSign({
collectionConfig: collection,
email: user.email ?? "",
sid,
user,
}),
secret: payload.secret,
tokenExpiration: collection.auth.tokenExpiration,
});
return token;
}
interface InboxBody {
notifications?: Array<{ id: number; isMine?: boolean; ownerName?: string }>;
canViewOthers?: boolean;
scope?: "all" | "mine";
}
describe("notifications inbox scope toggle", () => {
const roleIds: number[] = [];
const userIds: number[] = [];
const notifIds: number[] = [];
let adminToken: string;
let plainToken: string;
let adminNotifId: number;
let plainNotifId: number;
const makeRole = async (label: string, permissions: Permission[]): Promise<Role> => {
const role = (await payload.create({
collection: "roles",
data: { name: `${RUN}-${label}`, slug: `${RUN}-${label}`, permissions },
overrideAccess: true,
depth: 0,
})) as unknown as Role;
roleIds.push(role.id);
return role;
};
const makeUser = async (label: string, roleId: number): Promise<User> => {
const user = (await payload.create({
collection: "users",
data: {
username: `${RUN}-${label}`,
discordUsername: `${RUN}-${label}`,
displayName: label.toUpperCase(),
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roleDocs: [roleId],
},
overrideAccess: true,
depth: 0,
})) as unknown as User;
userIds.push(user.id);
return user;
};
const createNotification = async (userId: number): Promise<number> => {
const doc = await payload.create({
collection: "user-notifications",
data: {
user: userId,
type: "test:inbox-scope",
title: `${RUN} ${userId}`,
message: "test",
read: false,
},
overrideAccess: true,
depth: 0,
});
notifIds.push(doc.id as number);
return doc.id as number;
};
beforeAll(async () => {
const payloadConfig = await config;
payload = await getPayload({ config: payloadConfig });
invalidatePermissionCache();
// The read-all tier is exactly `system:admin-access` (mirrors the collection
// access rule); a plain role (no permissions) only ever sees its own rows.
const adminRole = await makeRole("admin", ["system:admin-access"]);
const plainRole = await makeRole("plain", []);
const admin = await makeUser("admin", adminRole.id);
const plain = await makeUser("plain", plainRole.id);
adminNotifId = await createNotification(admin.id);
plainNotifId = await createNotification(plain.id);
adminToken = await mintToken(admin.id);
plainToken = await mintToken(plain.id);
invalidatePermissionCache();
}, TIMEOUT);
afterAll(async () => {
if (!payload) return;
for (const id of notifIds) {
await payload.delete({ collection: "user-notifications", id, overrideAccess: true }).catch(
() => {},
);
}
for (const id of userIds) {
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => {});
}
for (const id of roleIds) {
await payload.delete({ collection: "roles", id, overrideAccess: true }).catch(() => {});
}
});
it("rejects unauthenticated callers", async () => {
const res = await GET(request());
expect(res.status).toBe(401);
}, TIMEOUT);
it("admin scope=all sees both users' notifications and is told it can view others", async () => {
const res = await GET(request(adminToken, "all"));
expect(res.status).toBe(200);
const body = (await res.json()) as InboxBody;
expect(body.canViewOthers).toBe(true);
expect(body.scope).toBe("all");
const ids = (body.notifications ?? []).map((n) => n.id);
expect(ids).toContain(adminNotifId);
expect(ids).toContain(plainNotifId);
const foreign = (body.notifications ?? []).find((n) => n.id === plainNotifId);
expect(foreign?.isMine).toBe(false);
}, TIMEOUT);
it("admin scope=mine narrows to just their own notifications", async () => {
const res = await GET(request(adminToken, "mine"));
expect(res.status).toBe(200);
const body = (await res.json()) as InboxBody;
expect(body.canViewOthers).toBe(true);
expect(body.scope).toBe("mine");
const ids = (body.notifications ?? []).map((n) => n.id);
expect(ids).toContain(adminNotifId);
expect(ids).not.toContain(plainNotifId);
}, TIMEOUT);
it("plain user cannot view others and stays scoped to their own regardless of scope", async () => {
const res = await GET(request(plainToken, "all"));
expect(res.status).toBe(200);
const body = (await res.json()) as InboxBody;
expect(body.canViewOthers).toBe(false);
// Requested "all" but the server forces "mine" for a non-oversight caller.
expect(body.scope).toBe("mine");
const ids = (body.notifications ?? []).map((n) => n.id);
expect(ids).toContain(plainNotifId);
expect(ids).not.toContain(adminNotifId);
}, TIMEOUT);
});