219 lines
8.7 KiB
TypeScript
219 lines
8.7 KiB
TypeScript
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
|
|
const mocks = vi.hoisted(() => ({
|
|
loadChatContext: vi.fn(),
|
|
requireChatPermission: vi.fn(),
|
|
getUserInfo: vi.fn(),
|
|
getValidatedServerSession: vi.fn(),
|
|
validateCSRFToken: vi.fn(),
|
|
issueChatGatewayToken: vi.fn(),
|
|
checkChatGatewayTokenRateLimit: vi.fn(),
|
|
loggerWarn: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("~/modules/chat/routes/chatAccess.server", () => ({
|
|
loadChatContext: mocks.loadChatContext,
|
|
requireChatPermission: mocks.requireChatPermission,
|
|
}));
|
|
vi.mock("~/utils/session.server", () => ({
|
|
getUserInfo: mocks.getUserInfo,
|
|
getValidatedServerSession: mocks.getValidatedServerSession,
|
|
validateCSRFToken: mocks.validateCSRFToken,
|
|
}));
|
|
vi.mock("@hivegrid/chat/gateway-auth.server", async (importOriginal) => ({
|
|
...(await importOriginal<typeof import("@hivegrid/chat/gateway-auth.server")>()),
|
|
issueChatGatewayToken: mocks.issueChatGatewayToken,
|
|
}));
|
|
vi.mock("~/modules/chat/services/chatGatewayRateLimit.server", () => ({
|
|
checkChatGatewayTokenRateLimit: mocks.checkChatGatewayTokenRateLimit,
|
|
}));
|
|
vi.mock("~/utils/logger.server", () => ({
|
|
createScopedLogger: () => ({ warn: mocks.loggerWarn }),
|
|
}));
|
|
|
|
import { action, loader } from "./chat.token";
|
|
|
|
const context = {
|
|
tenantId: "tenant_1",
|
|
userId: "user_1",
|
|
tenantUserId: "tenant_user_1",
|
|
permissions: ["chat.read_own_channels"],
|
|
hasModule: true,
|
|
} as const;
|
|
const NOW = new Date("2026-07-15T10:00:00.000Z");
|
|
|
|
function request() {
|
|
return new Request("https://app.example.test/hivegrid-demo/chat/token", {
|
|
method: "POST",
|
|
headers: { "x-csrf-token": "csrf-token" },
|
|
});
|
|
}
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
vi.useFakeTimers();
|
|
vi.setSystemTime(NOW);
|
|
vi.stubEnv("CHAT_GATEWAY_AUTH_SECRET", "chat-gateway-secret-at-least-32-bytes-long");
|
|
mocks.loadChatContext.mockResolvedValue(context);
|
|
mocks.requireChatPermission.mockImplementation((value) => value);
|
|
mocks.getUserInfo.mockResolvedValue({ userId: "user_1" });
|
|
mocks.getValidatedServerSession.mockResolvedValue({
|
|
id: "session_1",
|
|
userId: "user_1",
|
|
expiresAt: new Date("2026-07-15T11:00:00.000Z"),
|
|
user: { admin: null },
|
|
});
|
|
mocks.validateCSRFToken.mockResolvedValue(undefined);
|
|
mocks.issueChatGatewayToken.mockReturnValue("signed-chat-token");
|
|
mocks.checkChatGatewayTokenRateLimit.mockResolvedValue({ allowed: true, remaining: 19 });
|
|
});
|
|
|
|
afterEach(() => {
|
|
vi.useRealTimers();
|
|
});
|
|
|
|
describe("tenant chat token resource", () => {
|
|
it("keeps GET undiscoverable", () => {
|
|
expect(loader()).toMatchObject({ status: 404 });
|
|
});
|
|
|
|
it("mints an identity-only token after module, permission, CSRF, and live-session checks", async () => {
|
|
const incoming = request();
|
|
const response = await action({ request: incoming, params: { tenant: "hivegrid-demo" }, context: {} } as never);
|
|
|
|
expect(response.status).toBe(200);
|
|
expect(mocks.loadChatContext).toHaveBeenCalledWith({ request: incoming, params: { tenant: "hivegrid-demo" } });
|
|
expect(mocks.requireChatPermission).toHaveBeenCalledWith(context, "chat.read_own_channels");
|
|
expect(mocks.validateCSRFToken).toHaveBeenCalledWith(incoming, { headerOnly: true });
|
|
expect(mocks.getValidatedServerSession).toHaveBeenCalledWith(incoming, { userId: "user_1" });
|
|
expect(mocks.checkChatGatewayTokenRateLimit).toHaveBeenCalledWith({
|
|
tenantId: "tenant_1",
|
|
userId: "user_1",
|
|
sessionId: "session_1",
|
|
});
|
|
expect(mocks.issueChatGatewayToken).toHaveBeenCalledWith({
|
|
userId: "user_1",
|
|
tenantId: "tenant_1",
|
|
sessionId: "session_1",
|
|
secret: "chat-gateway-secret-at-least-32-bytes-long",
|
|
ttlSeconds: 900,
|
|
now: NOW,
|
|
});
|
|
expect(response.headers.get("cache-control")).toBe("no-store");
|
|
await expect(response.json()).resolves.toEqual({
|
|
ok: true,
|
|
data: { token: "signed-chat-token", expiresIn: 900, refreshAfter: 840 },
|
|
});
|
|
});
|
|
|
|
it("caps token lifetime to the remaining live session", async () => {
|
|
mocks.getValidatedServerSession.mockResolvedValueOnce({
|
|
id: "session_1",
|
|
userId: "user_1",
|
|
expiresAt: new Date("2026-07-15T10:01:30.000Z"),
|
|
user: { admin: null },
|
|
});
|
|
|
|
const response = await action({ request: request(), params: { tenant: "hivegrid-demo" }, context: {} } as never);
|
|
|
|
expect(mocks.issueChatGatewayToken).toHaveBeenCalledWith(expect.objectContaining({ ttlSeconds: 90, now: NOW }));
|
|
await expect(response.json()).resolves.toMatchObject({ data: { expiresIn: 90, refreshAfter: 72 } });
|
|
});
|
|
|
|
it("ignores the removed legacy User admin projection for regular tenant sessions", async () => {
|
|
mocks.getValidatedServerSession.mockResolvedValueOnce({
|
|
id: "session_admin",
|
|
userId: "user_1",
|
|
expiresAt: new Date("2026-07-15T10:10:00.000Z"),
|
|
user: { admin: { userId: "user_1" } },
|
|
});
|
|
|
|
const response = await action({ request: request(), params: { tenant: "hivegrid-demo" }, context: {} } as never);
|
|
|
|
expect(response.status).toBe(200);
|
|
expect(mocks.issueChatGatewayToken).toHaveBeenCalledWith(
|
|
expect.objectContaining({ userId: "user_1", tenantId: "tenant_1", sessionId: "session_admin" })
|
|
);
|
|
});
|
|
|
|
it("allows only POST for token minting", async () => {
|
|
const incoming = new Request("https://app.example.test/hivegrid-demo/chat/token", { method: "PATCH" });
|
|
|
|
const response = await action({ request: incoming, params: { tenant: "hivegrid-demo" }, context: {} } as never);
|
|
|
|
expect(response.status).toBe(405);
|
|
expect(response.headers.get("allow")).toBe("POST");
|
|
expect(mocks.loadChatContext).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("returns 404 before token issuance when module or permission access is denied", async () => {
|
|
mocks.requireChatPermission.mockImplementationOnce(() => {
|
|
throw new CatalogError(foundationErrors.notFound);
|
|
});
|
|
|
|
const response = await action({ request: request(), params: { tenant: "hivegrid-demo" }, context: {} } as never);
|
|
|
|
expect(response.status).toBe(404);
|
|
expect(mocks.validateCSRFToken).not.toHaveBeenCalled();
|
|
expect(mocks.issueChatGatewayToken).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects impersonation and a revoked server session", async () => {
|
|
mocks.getUserInfo.mockResolvedValueOnce({ userId: "user_1", impersonatingFromUserId: "operator_1" });
|
|
const impersonated = await action({ request: request(), params: { tenant: "hivegrid-demo" }, context: {} } as never);
|
|
|
|
mocks.getValidatedServerSession.mockResolvedValueOnce(null);
|
|
const revoked = await action({ request: request(), params: { tenant: "hivegrid-demo" }, context: {} } as never);
|
|
|
|
expect(impersonated.status).toBe(404);
|
|
expect(revoked.status).toBe(404);
|
|
expect(mocks.issueChatGatewayToken).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("fails clearly without a dedicated strong gateway secret", async () => {
|
|
vi.stubEnv("CHAT_GATEWAY_AUTH_SECRET", "too-short");
|
|
|
|
const response = await action({ request: request(), params: { tenant: "hivegrid-demo" }, context: {} } as never);
|
|
|
|
expect(response.status).toBe(503);
|
|
await expect(response.json()).resolves.toEqual({
|
|
ok: false,
|
|
error: "chat.errors.realtimeUnavailable",
|
|
code: "chat.realtime_unavailable",
|
|
});
|
|
expect(mocks.issueChatGatewayToken).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rate limits token minting with retry timing and no token disclosure", async () => {
|
|
mocks.checkChatGatewayTokenRateLimit.mockResolvedValueOnce({ allowed: false, retryAfterSeconds: 37 });
|
|
|
|
const response = await action({ request: request(), params: { tenant: "hivegrid-demo" }, context: {} } as never);
|
|
|
|
expect(response.status).toBe(429);
|
|
expect(response.headers.get("retry-after")).toBe("37");
|
|
expect(response.headers.get("cache-control")).toBe("no-store");
|
|
await expect(response.json()).resolves.toEqual({
|
|
ok: false,
|
|
error: "chat.errors.realtimeRateLimited",
|
|
code: "chat.realtime_rate_limited",
|
|
});
|
|
expect(mocks.issueChatGatewayToken).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("fails closed when the shared token limiter is unavailable", async () => {
|
|
mocks.checkChatGatewayTokenRateLimit.mockRejectedValueOnce(new Error("Redis unavailable"));
|
|
|
|
const response = await action({ request: request(), params: { tenant: "hivegrid-demo" }, context: {} } as never);
|
|
|
|
expect(response.status).toBe(503);
|
|
await expect(response.json()).resolves.toEqual({
|
|
ok: false,
|
|
error: "chat.errors.realtimeUnavailable",
|
|
code: "chat.realtime_unavailable",
|
|
});
|
|
expect(mocks.issueChatGatewayToken).not.toHaveBeenCalled();
|
|
expect(mocks.loggerWarn).toHaveBeenCalledWith({ tenantId: "tenant_1", userId: "user_1", errorName: "Error" }, "Chat gateway token rate limiter failed");
|
|
});
|
|
});
|