Files

238 lines
11 KiB
TypeScript

// @vitest-environment node
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import jwt from "jsonwebtoken";
// Mocks installed before the module under test is imported.
const getUserInfoMock = vi.fn();
const evaluateFlagForContextMock = vi.fn();
const getTenantUserTypeMock = vi.fn();
const knowledgeBaseArticleBelongsToTenantMock = vi.fn();
const getUserPermissionMock = vi.fn();
vi.mock("~/utils/session.server", () => ({
getUserInfo: getUserInfoMock,
}));
vi.mock("~/utils/services/.server/featureFlagEvaluator.server", () => ({
evaluateFlagForContext: evaluateFlagForContextMock,
}));
vi.mock("~/utils/db/tenants.db.server", () => ({
getTenantUserType: getTenantUserTypeMock,
}));
vi.mock("~/modules/knowledgeBase/db/kbArticles.db.server", () => ({
knowledgeBaseArticleBelongsToTenant: knowledgeBaseArticleBelongsToTenantMock,
}));
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
getUserPermission: getUserPermissionMock,
}));
const TEST_SECRET = "test-collab-secret-please-rotate-min-32";
async function importAction() {
const mod = await import("./api.collab.token");
return mod.action;
}
async function currentRlsContext() {
const mod = await import("@hivegrid/db/rls-context.server");
return mod.getRlsExecutionContext();
}
function buildRequest(body: unknown, method: "POST" | "GET" = "POST"): Request {
return new Request("http://localhost/api/collab/token", {
method,
headers: { "content-type": "application/json" },
body: body === undefined ? undefined : JSON.stringify(body),
});
}
describe("POST /api/collab/token", () => {
beforeEach(() => {
vi.resetModules();
getUserInfoMock.mockReset();
evaluateFlagForContextMock.mockReset();
getTenantUserTypeMock.mockReset();
knowledgeBaseArticleBelongsToTenantMock.mockReset();
getUserPermissionMock.mockReset();
// Resource-access defaults to allowed so existing flag/membership tests are unaffected.
knowledgeBaseArticleBelongsToTenantMock.mockResolvedValue(true);
getUserPermissionMock.mockResolvedValue({ permission: { id: "p-1" }, userPermission: "admin.kb.update" });
process.env.HOCUSPOCUS_AUTH_SECRET = TEST_SECRET;
});
afterEach(() => {
delete process.env.HOCUSPOCUS_AUTH_SECRET;
});
it("returns 503 when the server secret is not configured", async () => {
delete process.env.HOCUSPOCUS_AUTH_SECRET;
const action = await importAction();
const res = await action({ request: buildRequest({ tenantId: "t", resourceType: "kb-article", resourceId: "r" }) } as never);
expect(res.status).toBe(503);
});
it("returns 503 when the signing secret is too short", async () => {
process.env.HOCUSPOCUS_AUTH_SECRET = "too-short";
const action = await importAction();
const res = await action({ request: buildRequest({ tenantId: "t", resourceType: "kb-article", resourceId: "r" }) } as never);
expect(res.status).toBe(503);
});
it("returns 405 for non-POST methods", async () => {
const action = await importAction();
const res = await action({ request: buildRequest(undefined, "GET") } as never);
expect(res.status).toBe(405);
});
it("returns 401 when no userId on session", async () => {
getUserInfoMock.mockResolvedValue({ userId: null });
const action = await importAction();
const res = await action({ request: buildRequest({ tenantId: "t", resourceType: "kb-article", resourceId: "r" }) } as never);
expect(res.status).toBe(401);
});
it("returns 400 when body is missing fields", async () => {
getUserInfoMock.mockResolvedValue({ userId: "u_1" });
const action = await importAction();
const res = await action({ request: buildRequest({ tenantId: "t" }) } as never);
expect(res.status).toBe(400);
});
it("returns 400 when tenantId or resourceType would make an ambiguous document name", async () => {
getUserInfoMock.mockResolvedValue({ userId: "u_1" });
const action = await importAction();
const tenantRes = await action({ request: buildRequest({ tenantId: "tenant:abc", resourceType: "kb-article", resourceId: "art_1" }) } as never);
const resourceTypeRes = await action({ request: buildRequest({ tenantId: "tenant_abc", resourceType: "kb:article", resourceId: "art_1" }) } as never);
expect(tenantRes.status).toBe(400);
expect(resourceTypeRes.status).toBe(400);
expect(getTenantUserTypeMock).not.toHaveBeenCalled();
});
it("allows resourceId colons because hocuspocus parses the third document-name segment as the remainder", async () => {
getUserInfoMock.mockResolvedValue({ userId: "u_1" });
getTenantUserTypeMock.mockResolvedValue({ status: 2, type: 1 });
evaluateFlagForContextMock.mockResolvedValue({ enabled: true, reason: "matched" });
const action = await importAction();
const res = await action({ request: buildRequest({ tenantId: "tenant_abc", resourceType: "kb-article", resourceId: "folder:art_1" }) } as never);
expect(res.status).toBe(200);
const json = (await res.json()) as { documentName: string };
expect(json.documentName).toBe("tenant_abc:kb-article:folder:art_1");
});
it("returns 403 before feature-flag evaluation when the user is not an active member of the requested tenant", async () => {
getUserInfoMock.mockResolvedValue({ userId: "u_1" });
getTenantUserTypeMock.mockResolvedValue(null);
const action = await importAction();
const res = await action({ request: buildRequest({ tenantId: "other_tenant", resourceType: "kb-article", resourceId: "art_1" }) } as never);
expect(res.status).toBe(403);
expect(await res.json()).toEqual({ error: "forbidden", reason: "tenant-membership-required" });
expect(getTenantUserTypeMock).toHaveBeenCalledWith("u_1", "other_tenant");
expect(evaluateFlagForContextMock).not.toHaveBeenCalled();
expect(getUserPermissionMock).not.toHaveBeenCalled();
});
it("returns 403 before feature and resource checks when the user cannot update knowledge-base content", async () => {
getUserInfoMock.mockResolvedValue({ userId: "u_1" });
getTenantUserTypeMock.mockResolvedValue({ status: 2, type: 1 });
getUserPermissionMock.mockResolvedValue({ permission: { id: "p-1" }, userPermission: undefined });
const action = await importAction();
const res = await action({ request: buildRequest({ tenantId: "tenant_abc", resourceType: "kb-article", resourceId: "art_1" }) } as never);
expect(res.status).toBe(403);
expect(await res.json()).toEqual({ error: "forbidden", reason: "resource-write-permission-required" });
expect(getUserPermissionMock).toHaveBeenCalledWith({ userId: "u_1", permissionName: "admin.kb.update" });
expect(evaluateFlagForContextMock).not.toHaveBeenCalled();
expect(knowledgeBaseArticleBelongsToTenantMock).not.toHaveBeenCalled();
});
it("returns 403 when the feature-flag is disabled for the tenant", async () => {
getUserInfoMock.mockResolvedValue({ userId: "u_1" });
getTenantUserTypeMock.mockResolvedValue({ status: 2, type: 1 });
evaluateFlagForContextMock.mockResolvedValue({ enabled: false, reason: "disabled" });
const action = await importAction();
const res = await action({ request: buildRequest({ tenantId: "t", resourceType: "kb-article", resourceId: "art_1" }) } as never);
expect(res.status).toBe(403);
});
it("issues a signed JWT with the expected claims and 15min TTL when enabled", async () => {
getUserInfoMock.mockResolvedValue({ userId: "u_42" });
getTenantUserTypeMock.mockResolvedValue({ status: 2, type: 1 });
evaluateFlagForContextMock.mockResolvedValue({ enabled: true, reason: "matched" });
const action = await importAction();
const res = await action({ request: buildRequest({ tenantId: "tenant_abc", resourceType: "kb-article", resourceId: "art_xyz" }) } as never);
expect(res.status).toBe(200);
const json = (await res.json()) as { token: string; expiresIn: number; refreshAfter: number; documentName: string };
expect(json.expiresIn).toBe(900);
expect(json.refreshAfter).toBe(840);
expect(json.documentName).toBe("tenant_abc:kb-article:art_xyz");
expect(getTenantUserTypeMock).toHaveBeenCalledWith("u_42", "tenant_abc");
const decoded = jwt.verify(json.token, TEST_SECRET, { algorithms: ["HS256"] }) as {
userId: string;
tenantId: string;
resourceType: string;
resourceId: string;
exp: number;
iat: number;
iss: string;
aud: string;
sub: string;
jti: string;
};
expect(decoded.userId).toBe("u_42");
expect(decoded.tenantId).toBe("tenant_abc");
expect(decoded.resourceType).toBe("kb-article");
expect(decoded.resourceId).toBe("art_xyz");
expect(decoded.exp - decoded.iat).toBe(900);
expect(decoded.iss).toBe("hivegrid-web");
expect(decoded.aud).toBe("hivegrid-hocuspocus");
expect(decoded.sub).toBe("u_42");
expect(decoded.jti).toMatch(/^[0-9a-f-]{36}$/u);
});
it("binds feature, resource and token work to the verified tenant membership without leaking context", async () => {
getUserInfoMock.mockResolvedValue({ userId: "u_scoped" });
getTenantUserTypeMock.mockImplementation(async () => {
expect(await currentRlsContext()).toBeNull();
return { status: 2, type: 1 };
});
evaluateFlagForContextMock.mockImplementation(async () => {
expect(await currentRlsContext()).toMatchObject({ tenantId: "tenant_scoped", userId: "u_scoped" });
return { enabled: true, reason: "matched" };
});
knowledgeBaseArticleBelongsToTenantMock.mockImplementation(async () => {
expect(await currentRlsContext()).toMatchObject({ tenantId: "tenant_scoped", userId: "u_scoped" });
return true;
});
const action = await importAction();
const response = await action({
request: buildRequest({ tenantId: "tenant_scoped", resourceType: "kb-article", resourceId: "art_1" }),
} as never);
expect(response.status).toBe(200);
expect(await currentRlsContext()).toBeNull();
});
it("returns 403 for a kb-article that does not belong to the tenant", async () => {
getUserInfoMock.mockResolvedValue({ userId: "u_1" });
getTenantUserTypeMock.mockResolvedValue({ status: 2, type: 1 });
evaluateFlagForContextMock.mockResolvedValue({ enabled: true, reason: "matched" });
knowledgeBaseArticleBelongsToTenantMock.mockResolvedValue(false);
const action = await importAction();
const res = await action({ request: buildRequest({ tenantId: "tenant_abc", resourceType: "kb-article", resourceId: "art_foreign" }) } as never);
expect(res.status).toBe(403);
expect((await res.json()) as { token?: string }).not.toHaveProperty("token");
expect(await currentRlsContext()).toBeNull();
});
it("returns 403 for an unknown resource type (fail closed)", async () => {
getUserInfoMock.mockResolvedValue({ userId: "u_1" });
getTenantUserTypeMock.mockResolvedValue({ status: 2, type: 1 });
evaluateFlagForContextMock.mockResolvedValue({ enabled: true, reason: "matched" });
const action = await importAction();
const res = await action({ request: buildRequest({ tenantId: "tenant_abc", resourceType: "secret-blob", resourceId: "x" }) } as never);
expect(res.status).toBe(403);
});
});