Files

197 lines
9.4 KiB
TypeScript

// @vitest-environment node
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createSharedStore, MemoryAdapter } from "@hivegrid/shared-store";
const { clearCacheKey, getSharedStore, logError, logInfo, logWarn } = vi.hoisted(() => ({
clearCacheKey: vi.fn(),
getSharedStore: vi.fn(),
logError: vi.fn(),
logInfo: vi.fn(),
logWarn: vi.fn(),
}));
vi.mock("~/shared-store.server", () => ({ getSharedStore }));
vi.mock("~/utils/cache.server", () => ({ clearCacheKey }));
vi.mock("~/utils/logger.server", () => ({
createScopedLogger: () => ({ error: logError, info: logInfo, warn: logWarn }),
}));
import {
__resetPermissionCacheForTests,
cachePermissionNames,
createPermissionCache,
getCachedPermissionNames,
getPermissionCache,
invalidateUserPermissionCache,
invalidateUserPermissionCacheScopes,
subscribePermissionCache,
} from "./permission-cache.server";
const disposers: Array<() => Promise<void>> = [];
const originalCacheInvalidationEnabled = process.env.CACHE_INVALIDATION_ENABLED;
beforeEach(() => {
vi.clearAllMocks();
__resetPermissionCacheForTests();
delete process.env.CACHE_INVALIDATION_ENABLED;
getSharedStore.mockReturnValue(createSharedStore({ namespace: "permission-singleton-test", adapter: new MemoryAdapter() }));
});
afterEach(async () => {
await Promise.all(disposers.splice(0).map((dispose) => dispose()));
__resetPermissionCacheForTests();
if (originalCacheInvalidationEnabled === undefined) delete process.env.CACHE_INVALIDATION_ENABLED;
else process.env.CACHE_INVALIDATION_ENABLED = originalCacheInvalidationEnabled;
});
describe("permission authorization cache", () => {
it("revokes a cached grant on a second replica through shared-store pub/sub", async () => {
const adapter = new MemoryAdapter();
const replicaA = createPermissionCache(createSharedStore({ namespace: "permission-replica-test", adapter }));
const replicaB = createPermissionCache(createSharedStore({ namespace: "permission-replica-test", adapter }));
disposers.push(await replicaA.subscribe(), await replicaB.subscribe());
const key = "user_1:tenant_1";
await replicaA.set(key, ["settings.members.delete"]);
expect(await replicaB.get(key)).toEqual(["settings.members.delete"]);
expect(replicaB.l1.get(key)).toEqual(["settings.members.delete"]);
replicaA.deleteLocal(key);
await replicaA.l2.invalidate(key);
expect(replicaB.l1.get(key)).toBeUndefined();
expect(await replicaB.get(key)).toBeNull();
});
it("memoizes the process cache and stores defensive permission snapshots", async () => {
const first = getPermissionCache();
expect(getPermissionCache()).toBe(first);
expect(getSharedStore).toHaveBeenCalledTimes(1);
const names = ["settings.members.read"];
await expect(cachePermissionNames("user_1", "tenant_1", names)).resolves.toBe(true);
names.push("settings.members.delete");
const cached = await getCachedPermissionNames("user_1", "tenant_1");
expect(cached).toEqual(["settings.members.read"]);
cached?.push("mutated.by.caller");
await expect(getCachedPermissionNames("user_1", "tenant_1")).resolves.toEqual(["settings.members.read"]);
await expect(getCachedPermissionNames("missing", null)).resolves.toBeNull();
});
it("falls back to the database when cache reads or writes fail", async () => {
const cache = getPermissionCache();
vi.spyOn(cache, "get").mockRejectedValueOnce(new TypeError("read unavailable")).mockRejectedValueOnce("unknown read failure");
vi.spyOn(cache, "set").mockRejectedValueOnce(new RangeError("write unavailable")).mockRejectedValueOnce("unknown write failure");
await expect(getCachedPermissionNames("user_1", "tenant_1")).resolves.toBeNull();
await expect(getCachedPermissionNames("user_1", null)).resolves.toBeNull();
await expect(cachePermissionNames("user_1", "tenant_1", ["projects.read"])).resolves.toBe(false);
await expect(cachePermissionNames("user_1", null, ["admin.read"])).resolves.toBe(false);
expect(logWarn).toHaveBeenCalledTimes(4);
expect(logWarn.mock.calls.map(([context]) => context)).toEqual([
expect.objectContaining({ op: "permission-cache.read", err: { name: "TypeError" } }),
expect.objectContaining({ op: "permission-cache.read", err: { name: "Error" } }),
expect.objectContaining({ op: "permission-cache.write", err: { name: "RangeError" } }),
expect.objectContaining({ op: "permission-cache.write", err: { name: "Error" } }),
]);
});
it("invalidates one scope locally, in L2, and through the legacy cache", async () => {
const cache = getPermissionCache();
await cache.set("user_1:tenant_1", ["projects.read"]);
const invalidate = vi.spyOn(cache.l2, "invalidate");
await invalidateUserPermissionCache("user_1", "tenant_1");
expect(clearCacheKey).toHaveBeenCalledWith("userRoles:user_1:tenant_1");
expect(cache.l1.get("user_1:tenant_1")).toBeUndefined();
expect(invalidate).toHaveBeenCalledWith("user_1:tenant_1");
});
it("propagates single-scope invalidation failures", async () => {
const cache = getPermissionCache();
vi.spyOn(cache.l2, "invalidate").mockRejectedValueOnce(new TypeError("publish unavailable")).mockRejectedValueOnce("publish secret");
await expect(invalidateUserPermissionCache("user_1", null)).rejects.toThrow("publish unavailable");
await expect(invalidateUserPermissionCache("user_1", null)).rejects.toBe("publish secret");
expect(clearCacheKey).toHaveBeenCalledWith("userRoles:user_1:null");
expect(logError.mock.calls.map(([context]) => context)).toEqual(
expect.arrayContaining([
expect.objectContaining({ op: "permission-cache.invalidate", err: { name: "TypeError" } }),
expect.objectContaining({ op: "permission-cache.invalidate", err: { name: "Error" } }),
])
);
});
it("deduplicates batch scopes, deletes L2 snapshots, and broadcasts one wildcard", async () => {
const cache = getPermissionCache();
await cache.set("user_1:tenant_1", ["projects.read"]);
await cache.set("user_2:__admin__", ["admin.read"]);
const remove = vi.spyOn(cache.l2, "delete");
const invalidate = vi.spyOn(cache.l2, "invalidate");
await invalidateUserPermissionCacheScopes([
{ userId: "user_1", tenantId: "tenant_1" },
{ userId: "user_1", tenantId: "tenant_1" },
{ userId: "user_2", tenantId: null },
]);
expect(remove).toHaveBeenCalledTimes(2);
expect(remove).toHaveBeenCalledWith("user_1:tenant_1");
expect(remove).toHaveBeenCalledWith("user_2:__admin__");
expect(invalidate).toHaveBeenCalledWith("*");
expect(clearCacheKey.mock.calls).toEqual(expect.arrayContaining([["userRoles:user_1:tenant_1"], ["userRoles:user_2:null"]]));
expect(cache.l1.get("user_1:tenant_1")).toBeUndefined();
expect(cache.l1.get("user_2:__admin__")).toBeUndefined();
});
it("handles empty and single-scope batches without wildcard invalidation", async () => {
const cache = getPermissionCache();
const invalidate = vi.spyOn(cache.l2, "invalidate");
await invalidateUserPermissionCacheScopes([]);
expect(invalidate).not.toHaveBeenCalled();
await invalidateUserPermissionCacheScopes([{ userId: "user_1", tenantId: null }]);
expect(invalidate).toHaveBeenCalledWith("user_1:__admin__");
expect(invalidate).not.toHaveBeenCalledWith("*");
});
it("propagates batch invalidation failures without hiding stale-peer risk", async () => {
const cache = getPermissionCache();
const remove = vi.spyOn(cache.l2, "delete").mockRejectedValueOnce("delete unavailable");
const scopes = [
{ userId: "user_1", tenantId: "tenant_1" },
{ userId: "user_2", tenantId: "tenant_1" },
];
await expect(invalidateUserPermissionCacheScopes(scopes)).rejects.toBe("delete unavailable");
remove.mockRejectedValueOnce(new TypeError("delete failed"));
await expect(invalidateUserPermissionCacheScopes(scopes)).rejects.toThrow("delete failed");
expect(logError.mock.calls.map(([context]) => context)).toEqual(
expect.arrayContaining([
expect.objectContaining({ op: "permission-cache.invalidate-many", err: { name: "Error" } }),
expect.objectContaining({ op: "permission-cache.invalidate-many", err: { name: "TypeError" } }),
])
);
});
it("reuses the singleton subscriber and honours explicit pubsub disable values", async () => {
process.env.CACHE_INVALIDATION_ENABLED = "false";
createPermissionCache(createSharedStore({ namespace: "permission-pubsub-false", adapter: new MemoryAdapter() }));
process.env.CACHE_INVALIDATION_ENABLED = "0";
createPermissionCache(createSharedStore({ namespace: "permission-pubsub-zero", adapter: new MemoryAdapter() }));
process.env.CACHE_INVALIDATION_ENABLED = "TRUE";
createPermissionCache(createSharedStore({ namespace: "permission-pubsub-true", adapter: new MemoryAdapter() }));
process.env.CACHE_INVALIDATION_ENABLED = "";
createPermissionCache(createSharedStore({ namespace: "permission-pubsub-default", adapter: new MemoryAdapter() }));
const cache = getPermissionCache();
const subscribe = vi.spyOn(cache, "subscribe");
const first = await subscribePermissionCache();
disposers.push(first);
await expect(subscribePermissionCache()).resolves.toBe(first);
expect(subscribe).toHaveBeenCalledTimes(1);
expect(logInfo).toHaveBeenCalledWith({ namespace: "user-permissions" }, "Permission cache subscriber started.");
});
});