Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
-64
@@ -1,64 +0,0 @@
|
||||
import { getDefaultTenantTypes } from "../../db/tenants/tenantTypes.db.server";
|
||||
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
|
||||
import { addTenantTypeToTenant, getTenant } from "../../db/tenants.db.server";
|
||||
|
||||
export namespace TenantTypesApi {
|
||||
export async function setTenantTypes({
|
||||
tenantId,
|
||||
subscriptionProduct,
|
||||
types,
|
||||
}: {
|
||||
tenantId: string;
|
||||
subscriptionProduct?: SubscriptionProductDto;
|
||||
types?: string[];
|
||||
}) {
|
||||
const tenant = await getTenant(tenantId);
|
||||
if (!tenant) {
|
||||
return;
|
||||
}
|
||||
if (types) {
|
||||
await Promise.all(
|
||||
types.map(async (typeId) => {
|
||||
await addTenantTypeToTenant(tenant.id, { typeId });
|
||||
})
|
||||
);
|
||||
return;
|
||||
}
|
||||
const defaultTenantTypes = await getDefaultTenantTypes();
|
||||
const allTenantTypes = [...defaultTenantTypes, ...(subscriptionProduct?.assignsTenantTypes ?? [])].filter(
|
||||
(v, i, a) => a.findIndex((t) => t.id === v.id) === i
|
||||
);
|
||||
await Promise.all(
|
||||
allTenantTypes.map(async (tenantType) => {
|
||||
if (!tenant.types.find((f) => f.id === tenantType.id)) {
|
||||
await addTenantTypeToTenant(tenant.id, {
|
||||
typeId: tenantType.id,
|
||||
});
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
// export async function filterEntities({
|
||||
// tenant,
|
||||
// entities,
|
||||
// entityGroups,
|
||||
// }: {
|
||||
// tenant: TenantSimple;
|
||||
// entities: EntityWithDetails[];
|
||||
// entityGroups?: EntityGroupWithDetails[];
|
||||
// }) {
|
||||
// const tenantTypes = await getAllTenantTypes();
|
||||
// if (tenantTypes.length > 0) {
|
||||
// const tenantEntities = await TenantEntitiesApi.getEntities({ inTypes: tenant.types, enabledOnly: true });
|
||||
// entities = tenantEntities.allEntities;
|
||||
// let newGroups: EntityGroupWithDetails[] = [];
|
||||
// entityGroups?.forEach((group) => {
|
||||
// group.entities = group.entities.filter((f) => entities.some((e) => e.id === f.id));
|
||||
// if (group.entities.length > 0) {
|
||||
// newGroups.push(group);
|
||||
// }
|
||||
// });
|
||||
// entityGroups = newGroups;
|
||||
// }
|
||||
// }
|
||||
}
|
||||
+210
@@ -0,0 +1,210 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { getRlsExecutionContext, runWithRlsContext, runWithRlsTransaction } from "@hivegrid/db/rls-context.server";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
createOwnedTenantWithShkDefaults: vi.fn(),
|
||||
getUser: vi.fn(),
|
||||
getUserInfo: vi.fn(),
|
||||
createIdempotentTenantEvent: vi.fn(),
|
||||
autosubscribeToTrialOrFreePlan: vi.fn(),
|
||||
postCommitWarn: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(async () => ({ t: (key: string) => key })),
|
||||
}));
|
||||
vi.mock("~/domain/tenant-bootstrap/tenantBootstrapService.server", () => ({
|
||||
createOwnedTenantWithShkDefaults: mocks.createOwnedTenantWithShkDefaults,
|
||||
}));
|
||||
vi.mock("~/utils/db/users.db.server", () => ({ getUser: mocks.getUser }));
|
||||
vi.mock("~/utils/session.server", () => ({ getUserInfo: mocks.getUserInfo }));
|
||||
vi.mock("~/modules/events/services/.server/EventsService", () => ({
|
||||
default: { createIdempotentTenantEvent: mocks.createIdempotentTenantEvent },
|
||||
}));
|
||||
vi.mock("~/utils/services/.server/pricingService", () => ({
|
||||
autosubscribeToTrialOrFreePlan: mocks.autosubscribeToTrialOrFreePlan,
|
||||
}));
|
||||
vi.mock("~/utils/logger.server", () => ({
|
||||
createScopedLogger: vi.fn(() => ({ warn: mocks.postCommitWarn })),
|
||||
}));
|
||||
vi.mock("~/utils/app/CanonicalUrlUtils", () => ({
|
||||
appPath: ({ tenantSlug, path }: { tenantSlug: string; path: string }) => `/app/${tenantSlug}/${path}`,
|
||||
}));
|
||||
|
||||
import { TenantsApi } from "./TenantsApi";
|
||||
|
||||
const CREATION_REQUEST_KEY = "d7077797-054b-497a-b1ce-8e4f36257a96";
|
||||
const ACCOUNT_EVENT_IDEMPOTENCY_KEY = `tenant-bootstrap:tenant_1:${CREATION_REQUEST_KEY}:account-created`;
|
||||
|
||||
describe("TenantsApi.create RLS provisioning", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.getUserInfo.mockResolvedValue({ userId: "user_1" });
|
||||
const user = {
|
||||
id: "user_1",
|
||||
email: "owner@example.test",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
locale: "de",
|
||||
createdAt: new Date("2026-07-15T08:00:00.000Z"),
|
||||
defaultTenantId: null,
|
||||
};
|
||||
mocks.getUser.mockResolvedValue(user);
|
||||
mocks.createOwnedTenantWithShkDefaults.mockImplementation(async () => {
|
||||
expect(getRlsExecutionContext()).toMatchObject({ userId: "user_1" });
|
||||
return {
|
||||
tenant: { id: "tenant_1", name: "Acme", slug: "acme" },
|
||||
user: { ...user, defaultTenantId: "tenant_1" },
|
||||
replayed: false,
|
||||
};
|
||||
});
|
||||
mocks.autosubscribeToTrialOrFreePlan.mockImplementation(async () => {
|
||||
expect(getRlsExecutionContext()).toMatchObject({ userId: "user_1", tenantId: "tenant_1" });
|
||||
expect(getRlsExecutionContext()?.transaction).toBeUndefined();
|
||||
});
|
||||
mocks.createIdempotentTenantEvent.mockImplementation(async () => {
|
||||
expect(getRlsExecutionContext()).toMatchObject({ userId: "user_1", tenantId: "tenant_1" });
|
||||
expect(getRlsExecutionContext()?.transaction).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
it("runs replay-safe post-commit work outside any bootstrap or marker transaction", async () => {
|
||||
const request = new Request("https://admin.example.test/accounts", { method: "POST" });
|
||||
|
||||
const result = await runWithRlsContext({ userId: "user_1" }, () =>
|
||||
TenantsApi.create({ request, name: "Acme", slug: "acme", creationRequestKey: CREATION_REQUEST_KEY })
|
||||
);
|
||||
|
||||
expect(mocks.createOwnedTenantWithShkDefaults).toHaveBeenCalledWith({
|
||||
user: expect.objectContaining({ id: "user_1", email: "owner@example.test" }),
|
||||
name: "Acme",
|
||||
slug: "acme",
|
||||
creationRequestKey: CREATION_REQUEST_KEY,
|
||||
t: expect.any(Function),
|
||||
});
|
||||
expect(mocks.autosubscribeToTrialOrFreePlan).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_1",
|
||||
throwOnFailure: true,
|
||||
idempotencyKey: CREATION_REQUEST_KEY,
|
||||
})
|
||||
);
|
||||
expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
event: "account.created",
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_1",
|
||||
idempotencyKey: ACCOUNT_EVENT_IDEMPOTENCY_KEY,
|
||||
})
|
||||
);
|
||||
expect(mocks.autosubscribeToTrialOrFreePlan.mock.invocationCallOrder[0]).toBeGreaterThan(
|
||||
mocks.createOwnedTenantWithShkDefaults.mock.invocationCallOrder[0]
|
||||
);
|
||||
expect(mocks.createIdempotentTenantEvent.mock.invocationCallOrder[0]).toBeGreaterThan(
|
||||
mocks.createOwnedTenantWithShkDefaults.mock.invocationCallOrder[0]
|
||||
);
|
||||
expect(result).toMatchObject({ redirectTo: "/app/acme/dashboard", tenant: { id: "tenant_1" }, user: { id: "user_1" } });
|
||||
expect(getRlsExecutionContext()).toBeNull();
|
||||
});
|
||||
|
||||
it("does not run post-commit work when the atomic owner bootstrap fails", async () => {
|
||||
mocks.createOwnedTenantWithShkDefaults.mockRejectedValueOnce(new Error("bootstrap failed"));
|
||||
const request = new Request("https://admin.example.test/accounts", { method: "POST" });
|
||||
|
||||
await expect(
|
||||
runWithRlsContext({ userId: "user_1" }, () =>
|
||||
TenantsApi.create({ request, name: "Acme", slug: "acme", creationRequestKey: CREATION_REQUEST_KEY })
|
||||
)
|
||||
).rejects.toThrow("bootstrap failed");
|
||||
|
||||
expect(mocks.autosubscribeToTrialOrFreePlan).not.toHaveBeenCalled();
|
||||
expect(mocks.createIdempotentTenantEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("isolates post-commit work from a previously-bound tenant", async () => {
|
||||
const request = new Request("https://old.example.test/new-account", { method: "POST" });
|
||||
|
||||
await runWithRlsContext({ userId: "user_1", tenantId: "tenant_old" }, async () => {
|
||||
await TenantsApi.create({ request, name: "Acme", slug: "acme", creationRequestKey: CREATION_REQUEST_KEY });
|
||||
expect(getRlsExecutionContext()).toMatchObject({ userId: "user_1", tenantId: "tenant_old" });
|
||||
});
|
||||
|
||||
expect(mocks.autosubscribeToTrialOrFreePlan).toHaveBeenCalledOnce();
|
||||
expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("drops an inherited transaction before dispatching post-commit work", async () => {
|
||||
const request = new Request("https://app.example.test/new-account", { method: "POST" });
|
||||
const oldTransaction = {};
|
||||
|
||||
await runWithRlsContext({ userId: "user_1" }, () =>
|
||||
runWithRlsTransaction(oldTransaction, () =>
|
||||
TenantsApi.create({ request, name: "Acme", slug: "acme", creationRequestKey: CREATION_REQUEST_KEY })
|
||||
)
|
||||
);
|
||||
|
||||
expect(mocks.autosubscribeToTrialOrFreePlan).toHaveBeenCalledOnce();
|
||||
expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("replays both intrinsically idempotent steps with their original stable keys after response loss", async () => {
|
||||
const request = new Request("https://app.example.test/new-account", { method: "POST" });
|
||||
|
||||
await runWithRlsContext({ userId: "user_1" }, () =>
|
||||
TenantsApi.create({ request, name: "Acme", slug: "acme", creationRequestKey: CREATION_REQUEST_KEY })
|
||||
);
|
||||
const user = await mocks.getUser();
|
||||
mocks.createOwnedTenantWithShkDefaults.mockResolvedValueOnce({
|
||||
tenant: { id: "tenant_1", name: "Acme", slug: "acme" },
|
||||
user: { ...user, defaultTenantId: "tenant_1" },
|
||||
replayed: true,
|
||||
});
|
||||
|
||||
const replay = await runWithRlsContext({ userId: "user_1" }, () =>
|
||||
TenantsApi.create({ request, name: "Acme", slug: "acme", creationRequestKey: CREATION_REQUEST_KEY })
|
||||
);
|
||||
|
||||
expect(replay.replayed).toBe(true);
|
||||
expect(mocks.autosubscribeToTrialOrFreePlan).toHaveBeenCalledTimes(2);
|
||||
expect(mocks.autosubscribeToTrialOrFreePlan.mock.calls.map(([args]) => args.idempotencyKey)).toEqual([
|
||||
CREATION_REQUEST_KEY,
|
||||
CREATION_REQUEST_KEY,
|
||||
]);
|
||||
expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledTimes(2);
|
||||
expect(mocks.createIdempotentTenantEvent.mock.calls.map(([args]) => args.idempotencyKey)).toEqual([
|
||||
ACCOUNT_EVENT_IDEMPOTENCY_KEY,
|
||||
ACCOUNT_EVENT_IDEMPOTENCY_KEY,
|
||||
]);
|
||||
});
|
||||
|
||||
it("propagates a replayable post-commit failure and completes it on an exact retry", async () => {
|
||||
const request = new Request("https://app.example.test/new-account", { method: "POST" });
|
||||
mocks.autosubscribeToTrialOrFreePlan.mockRejectedValueOnce(new Error("billing unavailable"));
|
||||
|
||||
await expect(
|
||||
runWithRlsContext({ userId: "user_1" }, () =>
|
||||
TenantsApi.create({ request, name: "Acme", slug: "acme", creationRequestKey: CREATION_REQUEST_KEY })
|
||||
)
|
||||
).rejects.toThrow("billing unavailable");
|
||||
expect(mocks.createIdempotentTenantEvent).not.toHaveBeenCalled();
|
||||
expect(mocks.postCommitWarn).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ op: "workspace.postcommit.trial-autosubscribe", tenantId: "tenant_1" }),
|
||||
expect.stringContaining("Workspace creation committed")
|
||||
);
|
||||
|
||||
const user = await mocks.getUser();
|
||||
mocks.createOwnedTenantWithShkDefaults.mockResolvedValueOnce({
|
||||
tenant: { id: "tenant_1", name: "Acme", slug: "acme" },
|
||||
user: { ...user, defaultTenantId: "tenant_1" },
|
||||
replayed: true,
|
||||
});
|
||||
await runWithRlsContext({ userId: "user_1" }, () =>
|
||||
TenantsApi.create({ request, name: "Acme", slug: "acme", creationRequestKey: CREATION_REQUEST_KEY })
|
||||
);
|
||||
|
||||
expect(mocks.autosubscribeToTrialOrFreePlan).toHaveBeenCalledTimes(2);
|
||||
expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
+95
-24
@@ -1,48 +1,119 @@
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { createTenant } from "../../db/tenants.db.server";
|
||||
import { getUser, updateUserDefaultTenantId } from "../../db/users.db.server";
|
||||
import { createOwnedTenantWithShkDefaults } from "~/domain/tenant-bootstrap/tenantBootstrapService.server";
|
||||
import { getUser } from "../../db/users.db.server";
|
||||
import { getUserInfo } from "../../session.server";
|
||||
import { TenantTypesApi } from "./TenantTypesApi";
|
||||
import EventsService from "../../../modules/events/services/.server/EventsService";
|
||||
import { AccountCreatedDto } from "~/modules/events/dtos/AccountCreatedDto";
|
||||
import { autosubscribeToTrialOrFreePlan } from "../../services/.server/pricingService";
|
||||
import { appPath } from "../../app/CanonicalUrlUtils";
|
||||
import { getRlsExecutionContext, runWithIsolatedUserRlsContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
|
||||
const tenantsApiLogger = createScopedLogger("tenants-api");
|
||||
|
||||
type WorkspacePostCommitOperation = "account-created-event" | "trial-autosubscribe";
|
||||
|
||||
function runWithPostCommitTenantRlsContext<T>(tenantId: string, userId: string, callback: () => T): T {
|
||||
const current = getRlsExecutionContext();
|
||||
if (current?.userId === userId && (current.transaction !== undefined || (current.tenantId !== undefined && current.tenantId !== tenantId))) {
|
||||
return runWithIsolatedUserRlsContext(userId, () => runWithRlsContext({ tenantId, userId }, callback));
|
||||
}
|
||||
return runWithRlsContext({ tenantId, userId }, callback);
|
||||
}
|
||||
|
||||
async function runWorkspacePostCommitStep({
|
||||
operation,
|
||||
tenantId,
|
||||
userId,
|
||||
callback,
|
||||
}: {
|
||||
operation: WorkspacePostCommitOperation;
|
||||
tenantId: string;
|
||||
userId: string;
|
||||
callback: () => Promise<unknown>;
|
||||
}): Promise<void> {
|
||||
try {
|
||||
await callback();
|
||||
} catch (error) {
|
||||
tenantsApiLogger.warn(
|
||||
{
|
||||
op: `workspace.postcommit.${operation}`,
|
||||
tenantId,
|
||||
userId,
|
||||
err: { name: error instanceof Error ? error.name : "Error" },
|
||||
},
|
||||
"Workspace creation committed, but a replayable post-commit step failed."
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export namespace TenantsApi {
|
||||
export async function create({ request, name, slug }: { request: Request; name: string; slug?: string }) {
|
||||
export async function create({ request, name, slug, creationRequestKey }: { request: Request; name: string; slug?: string; creationRequestKey: string }) {
|
||||
const { t } = await getTranslations(request);
|
||||
let userInfo = await getUserInfo(request);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const user = await getUser(userInfo.userId);
|
||||
if (!user) {
|
||||
throw new Error("User not found");
|
||||
throw new CatalogError(foundationErrors.notFound, { resource: "workspace-owner" });
|
||||
}
|
||||
if (!name) {
|
||||
throw new Error("Name is required");
|
||||
throw new CatalogError(foundationErrors.notFound, { resource: "workspace-creation-input" });
|
||||
}
|
||||
|
||||
const tenant = await createTenant({ name, slug });
|
||||
const {
|
||||
tenant,
|
||||
user: bootstrappedUser,
|
||||
replayed,
|
||||
} = await runWithRlsContext({ userId: user.id }, () =>
|
||||
createOwnedTenantWithShkDefaults({
|
||||
user,
|
||||
name,
|
||||
slug,
|
||||
creationRequestKey,
|
||||
t,
|
||||
})
|
||||
);
|
||||
|
||||
await updateUserDefaultTenantId({ defaultTenantId: tenant.id }, user.id);
|
||||
|
||||
await autosubscribeToTrialOrFreePlan({ request, t, tenantId: tenant.id, userId: user.id });
|
||||
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "account.created",
|
||||
tenantId: tenant.id,
|
||||
userId: user.id,
|
||||
data: {
|
||||
tenant: { id: tenant.id, name: tenant.name, slug: tenant.slug },
|
||||
user: { id: user.id, email: user.email },
|
||||
} satisfies AccountCreatedDto,
|
||||
await runWithPostCommitTenantRlsContext(tenant.id, bootstrappedUser.id, async () => {
|
||||
await runWorkspacePostCommitStep({
|
||||
operation: "trial-autosubscribe",
|
||||
tenantId: tenant.id,
|
||||
userId: bootstrappedUser.id,
|
||||
callback: () =>
|
||||
autosubscribeToTrialOrFreePlan({
|
||||
request,
|
||||
t,
|
||||
tenantId: tenant.id,
|
||||
userId: bootstrappedUser.id,
|
||||
throwOnFailure: true,
|
||||
idempotencyKey: creationRequestKey,
|
||||
}),
|
||||
});
|
||||
await runWorkspacePostCommitStep({
|
||||
operation: "account-created-event",
|
||||
tenantId: tenant.id,
|
||||
userId: bootstrappedUser.id,
|
||||
callback: () =>
|
||||
EventsService.createIdempotentTenantEvent({
|
||||
request,
|
||||
event: "account.created",
|
||||
tenantId: tenant.id,
|
||||
userId: bootstrappedUser.id,
|
||||
idempotencyKey: `tenant-bootstrap:${tenant.id}:${creationRequestKey}:account-created`,
|
||||
data: {
|
||||
tenant: { id: tenant.id, name: tenant.name, slug: tenant.slug },
|
||||
user: { id: bootstrappedUser.id, email: bootstrappedUser.email },
|
||||
} satisfies AccountCreatedDto,
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
await TenantTypesApi.setTenantTypes({ tenantId: tenant.id });
|
||||
|
||||
return {
|
||||
redirectTo: appPath({ tenantSlug: tenant.slug, path: "dashboard", mode: "host-aware" }),
|
||||
tenant,
|
||||
user,
|
||||
user: bootstrappedUser,
|
||||
replayed,
|
||||
};
|
||||
}
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
import type { LegacyApiKeySimple } from "@hivegrid/db/api-keys.server";
|
||||
import { createTwoTierCache, type CacheSerializer, type SharedStore, type TwoTierCache } from "@hivegrid/shared-store";
|
||||
|
||||
import { getSharedStore } from "~/shared-store.server";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
|
||||
const log = createScopedLogger("api-key-auth-cache");
|
||||
|
||||
// Pub/sub is the primary revocation path. The short TTL bounds exposure when a
|
||||
// replica misses an invalidation while disconnected from Redis.
|
||||
export const API_KEY_AUTH_CACHE_TTL_SECONDS = 30;
|
||||
|
||||
type SerializedApiKeySnapshot = Omit<LegacyApiKeySimple, "expires"> & { expires: string | null };
|
||||
|
||||
const apiKeySerializer: CacheSerializer<LegacyApiKeySimple> = {
|
||||
serialize(value) {
|
||||
const serialized: SerializedApiKeySnapshot = {
|
||||
...value,
|
||||
expires: value.expires?.toISOString() ?? null,
|
||||
};
|
||||
return JSON.stringify(serialized);
|
||||
},
|
||||
deserialize(raw) {
|
||||
const value = JSON.parse(raw) as SerializedApiKeySnapshot;
|
||||
return {
|
||||
...value,
|
||||
expires: value.expires ? new Date(value.expires) : null,
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
function pubsubEnabledFromEnv(): boolean {
|
||||
const raw = process.env.CACHE_INVALIDATION_ENABLED;
|
||||
if (raw === undefined || raw === null || raw === "") return true;
|
||||
return raw.toLowerCase() !== "false" && raw !== "0";
|
||||
}
|
||||
|
||||
export function createApiKeyAuthCache(store: SharedStore, options: { now?: () => number } = {}): TwoTierCache<LegacyApiKeySimple> {
|
||||
return createTwoTierCache<LegacyApiKeySimple>({
|
||||
store,
|
||||
namespace: "api-key-auth",
|
||||
ttlSeconds: API_KEY_AUTH_CACHE_TTL_SECONDS,
|
||||
l1MaxEntries: 10_000,
|
||||
l1Now: options.now,
|
||||
serializer: apiKeySerializer,
|
||||
pubsubEnabled: pubsubEnabledFromEnv(),
|
||||
logger: {
|
||||
warn: (obj, msg) => log.warn(obj, msg),
|
||||
info: (obj, msg) => log.info(obj, msg),
|
||||
error: (obj, msg) => log.error(obj, msg),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
let cacheSingleton: TwoTierCache<LegacyApiKeySimple> | null = null;
|
||||
let subscribeDisposer: (() => Promise<void>) | null = null;
|
||||
|
||||
export function getApiKeyAuthCache(): TwoTierCache<LegacyApiKeySimple> {
|
||||
cacheSingleton ??= createApiKeyAuthCache(getSharedStore());
|
||||
return cacheSingleton;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cache an already-verified authorization snapshot. The raw credential is
|
||||
* neither part of LegacyApiKeySimple nor passed to this module; callers use a
|
||||
* SHA-256 lookup key so Redis never receives plaintext API keys.
|
||||
*/
|
||||
export async function loadCachedApiKeySnapshot(
|
||||
lookupCacheKey: string,
|
||||
getFreshValue: () => Promise<LegacyApiKeySimple | null>
|
||||
): Promise<LegacyApiKeySimple | null> {
|
||||
const cache = getApiKeyAuthCache();
|
||||
try {
|
||||
const cached = await cache.get(lookupCacheKey);
|
||||
if (cached !== null) return cached;
|
||||
} catch (error) {
|
||||
log.warn(
|
||||
{ op: "api-key-auth-cache.read", err: { name: error instanceof Error ? error.name : "Error" } },
|
||||
"API-key cache read failed; falling back to the database."
|
||||
);
|
||||
}
|
||||
|
||||
const fresh = await getFreshValue();
|
||||
if (fresh !== null) {
|
||||
try {
|
||||
await cache.set(lookupCacheKey, fresh);
|
||||
} catch (error) {
|
||||
log.warn(
|
||||
{ op: "api-key-auth-cache.write", err: { name: error instanceof Error ? error.name : "Error" } },
|
||||
"API-key cache write failed; continuing with the database result."
|
||||
);
|
||||
}
|
||||
}
|
||||
return fresh;
|
||||
}
|
||||
|
||||
/** Fail closed after key rotation, revocation, or deletion. */
|
||||
export async function invalidateApiKeySnapshot(lookupCacheKey: string): Promise<void> {
|
||||
const cache = getApiKeyAuthCache();
|
||||
cache.deleteLocal(lookupCacheKey);
|
||||
await cache.l2.invalidate(lookupCacheKey);
|
||||
}
|
||||
|
||||
export async function subscribeApiKeyAuthCache(): Promise<() => Promise<void>> {
|
||||
if (subscribeDisposer) return subscribeDisposer;
|
||||
subscribeDisposer = await getApiKeyAuthCache().subscribe();
|
||||
log.info({ namespace: "api-key-auth" }, "API-key authorization cache subscriber started.");
|
||||
return subscribeDisposer;
|
||||
}
|
||||
|
||||
/** Test seam. */
|
||||
export function __resetApiKeyAuthCacheForTests(): void {
|
||||
cacheSingleton = null;
|
||||
subscribeDisposer = null;
|
||||
}
|
||||
Reference in new issue
Block a user