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
+57
-49
@@ -1,4 +1,5 @@
|
||||
import { Tenant } from "@hivegrid/db/prisma-browser";
|
||||
import type { Tenant } from "@hivegrid/db/prisma-browser";
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { useNavigate } from "react-router";
|
||||
import ApiKeyForm from "~/components/core/apiKeys/ApiKeyForm";
|
||||
@@ -7,7 +8,7 @@ import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import { RedactedApiKeyWithDetails, adminGetApiKeyById, deleteApiKey, getApiKeys, updateApiKey } from "~/utils/db/apiKeys.db.server";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { adminGetAllTenants } from "~/utils/db/tenants.db.server";
|
||||
import { adminGetAllTenantsIdsAndNames } from "~/utils/db/tenants.db.server";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import EventsService from "~/modules/events/services/.server/EventsService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
@@ -18,7 +19,7 @@ import { ApiKeyUpdatedDto } from "~/modules/events/dtos/ApiKeyUpdatedDto";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
type LoaderData = {
|
||||
tenants: Tenant[];
|
||||
tenants: Pick<Tenant, "id" | "name">[];
|
||||
item: RedactedApiKeyWithDetails;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
@@ -27,7 +28,7 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
if (!item) {
|
||||
return redirect(adminPath("api", { mode: "host-aware" }));
|
||||
}
|
||||
const tenants = await adminGetAllTenants();
|
||||
const tenants = await adminGetAllTenantsIdsAndNames();
|
||||
const data: LoaderData = {
|
||||
item,
|
||||
tenants,
|
||||
@@ -60,58 +61,65 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
expirationDate = new Date(expires);
|
||||
}
|
||||
const tenantId = form.get("tenant-id")?.toString() ?? "";
|
||||
const alias = form.get("alias")?.toString() ?? "";
|
||||
const existingAlias = await getApiKeys(tenantId);
|
||||
if (existingAlias.filter((f) => f.id !== existing.id && f.alias === alias).length > 0) {
|
||||
return badRequest({ error: t("models.apiKey.errors.aliasExists", { alias }) });
|
||||
if (tenantId !== existing.tenantId) {
|
||||
return badRequest({ error: t("models.apiKey.errors.tenantChangeNotAllowed") });
|
||||
}
|
||||
const alias = form.get("alias")?.toString() ?? "";
|
||||
const active = Boolean(form.get("active"));
|
||||
await updateApiKey(params.id ?? "", {
|
||||
tenantId,
|
||||
alias,
|
||||
expires: expirationDate,
|
||||
active,
|
||||
await runWithRlsContext({ tenantId }, async () => {
|
||||
const existingAlias = await getApiKeys(tenantId);
|
||||
if (existingAlias.some((item) => item.id !== existing.id && item.alias === alias)) {
|
||||
throw badRequest({ error: t("models.apiKey.errors.aliasExists", { alias }) });
|
||||
}
|
||||
await updateApiKey(params.id ?? "", {
|
||||
tenantId,
|
||||
alias,
|
||||
expires: expirationDate,
|
||||
active,
|
||||
});
|
||||
await createAdminLog(request, "admin.apiKeys.updated", JSON.stringify({ tenantId, alias, expirationDate, active }));
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "api_key.updated",
|
||||
tenantId,
|
||||
userId: currentUser?.id ?? null,
|
||||
data: {
|
||||
id: existing.id,
|
||||
new: {
|
||||
alias: alias,
|
||||
expires: expirationDate,
|
||||
active: active,
|
||||
},
|
||||
old: {
|
||||
alias: existing.alias,
|
||||
expires: existing.expires,
|
||||
active: existing.active,
|
||||
},
|
||||
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
|
||||
} satisfies ApiKeyUpdatedDto,
|
||||
});
|
||||
});
|
||||
await createAdminLog(request, "admin.apiKeys.updated", JSON.stringify({ tenantId, alias, expirationDate, active }));
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "api_key.updated",
|
||||
tenantId,
|
||||
userId: currentUser?.id ?? null,
|
||||
data: {
|
||||
id: existing.id,
|
||||
new: {
|
||||
alias: alias,
|
||||
expires: expirationDate,
|
||||
active: active,
|
||||
},
|
||||
old: {
|
||||
return redirect(`${adminPath("api/keys", { mode: "host-aware" })}?toast=${encodeURIComponent("models.apiKey.toast.saved")}`);
|
||||
} else if (action === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.delete");
|
||||
await runWithRlsContext({ tenantId: existing.tenantId }, async () => {
|
||||
await deleteApiKey(params.id ?? "", existing.tenantId);
|
||||
await createAdminLog(request, "admin.apiKeys.deleted", "");
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "api_key.deleted",
|
||||
tenantId: existing.tenantId,
|
||||
userId: currentUser?.id ?? null,
|
||||
data: {
|
||||
id: existing.id,
|
||||
alias: existing.alias,
|
||||
expires: existing.expires,
|
||||
active: existing.active,
|
||||
},
|
||||
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
|
||||
} satisfies ApiKeyUpdatedDto,
|
||||
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
|
||||
} satisfies ApiKeyDeletedDto,
|
||||
});
|
||||
});
|
||||
return redirect(adminPath(`api/keys`, { mode: "host-aware" }));
|
||||
} else if (action === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.delete");
|
||||
await deleteApiKey(params.id ?? "", existing.tenantId);
|
||||
await createAdminLog(request, "admin.apiKeys.deleted", "");
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "api_key.deleted",
|
||||
tenantId: existing.tenantId,
|
||||
userId: currentUser?.id ?? null,
|
||||
data: {
|
||||
id: existing.id,
|
||||
alias: existing.alias,
|
||||
expires: existing.expires,
|
||||
active: existing.active,
|
||||
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
|
||||
} satisfies ApiKeyDeletedDto,
|
||||
});
|
||||
return redirect(adminPath(`api/keys`, { mode: "host-aware" }));
|
||||
return redirect(`${adminPath("api/keys", { mode: "host-aware" })}?toast=${encodeURIComponent("models.apiKey.toast.deleted")}`);
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
// @vitest-environment node
|
||||
import type { ActionFunctionArgs } from "react-router";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: vi.fn() }));
|
||||
vi.mock("~/utils/session.server", () => ({ getUserInfo: vi.fn(), validateCSRFToken: vi.fn() }));
|
||||
vi.mock("~/utils/db/tenants.db.server", () => ({ adminGetAllTenantsIdsAndNames: vi.fn() }));
|
||||
vi.mock("~/utils/db/users.db.server", () => ({ getUser: vi.fn() }));
|
||||
vi.mock("~/utils/db/apiKeys.db.server", () => ({
|
||||
adminGetApiKeyById: vi.fn(),
|
||||
createApiKey: vi.fn(),
|
||||
deleteApiKey: vi.fn(),
|
||||
getApiKeyByAlias: vi.fn(),
|
||||
getApiKeys: vi.fn(),
|
||||
updateApiKey: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/db/logs.db.server", () => ({ createAdminLog: vi.fn() }));
|
||||
vi.mock("~/modules/events/services/.server/EventsService", () => ({ default: { create: vi.fn() } }));
|
||||
vi.mock("~/utils/app/CanonicalUrlUtils", () => ({ adminPath: (path = "") => `/admin/${path}` }));
|
||||
vi.mock("~/components/core/apiKeys/ApiKeyCreatedModal", () => ({ default: () => null }));
|
||||
vi.mock("~/components/core/apiKeys/ApiKeyForm", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/modals/OpenModal", () => ({ default: ({ children }: { children: React.ReactNode }) => children }));
|
||||
vi.mock("~/utils/data/useAdminData", () => ({ useAdminData: () => ({}) }));
|
||||
vi.mock("~/utils/helpers/PermissionsHelper", () => ({ getUserHasPermission: () => true }));
|
||||
|
||||
import EventsService from "~/modules/events/services/.server/EventsService";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { adminGetApiKeyById, createApiKey, deleteApiKey, getApiKeyByAlias, getApiKeys, updateApiKey } from "~/utils/db/apiKeys.db.server";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { adminGetAllTenantsIdsAndNames } from "~/utils/db/tenants.db.server";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { action as createAction } from "./new";
|
||||
import { action as editAction } from "./$id";
|
||||
|
||||
const operator = { id: "operator_1", email: "operator@example.test" };
|
||||
const tenants = [
|
||||
{ id: "tenant_a", name: "Tenant A", slug: "tenant-a" },
|
||||
{ id: "tenant_b", name: "Tenant B", slug: "tenant-b" },
|
||||
];
|
||||
const existing = { id: "key_a", tenantId: "tenant_a", alias: "Primary", expires: null, active: true };
|
||||
|
||||
function requestFor(path: string, values: Record<string, string>) {
|
||||
return new Request(`https://admin.example.test${path}`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams(values),
|
||||
});
|
||||
}
|
||||
|
||||
function callCreate(values: Record<string, string>) {
|
||||
return runWithRlsContext({ userId: operator.id }, () =>
|
||||
createAction({
|
||||
request: requestFor("/api/keys/new", values),
|
||||
params: {},
|
||||
context: {},
|
||||
unstable_pattern: "admin/api/keys/new",
|
||||
} as ActionFunctionArgs)
|
||||
) as Promise<Response>;
|
||||
}
|
||||
|
||||
function callEdit(values: Record<string, string>) {
|
||||
return runWithRlsContext({ userId: operator.id }, () =>
|
||||
editAction({
|
||||
request: requestFor("/api/keys/key_a", values),
|
||||
params: { id: "key_a" },
|
||||
context: {},
|
||||
unstable_pattern: "admin/api/keys/$id",
|
||||
} as ActionFunctionArgs)
|
||||
) as Promise<Response>;
|
||||
}
|
||||
|
||||
describe("admin API key route RLS contexts", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(getTranslations).mockResolvedValue({ t: (key: string) => `translated:${key}` } as never);
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getUserInfo).mockResolvedValue({ userId: operator.id } as never);
|
||||
vi.mocked(validateCSRFToken).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getUser).mockResolvedValue(operator as never);
|
||||
vi.mocked(adminGetAllTenantsIdsAndNames).mockResolvedValue(tenants);
|
||||
vi.mocked(adminGetApiKeyById).mockResolvedValue(existing as never);
|
||||
vi.mocked(getApiKeyByAlias).mockResolvedValue(null as never);
|
||||
vi.mocked(getApiKeys).mockResolvedValue([existing] as never);
|
||||
vi.mocked(createApiKey).mockResolvedValue({ ...existing, id: "key_b", tenantId: "tenant_b" } as never);
|
||||
vi.mocked(updateApiKey).mockResolvedValue(existing as never);
|
||||
vi.mocked(deleteApiKey).mockResolvedValue(existing as never);
|
||||
vi.mocked(EventsService.create).mockResolvedValue(undefined as never);
|
||||
vi.mocked(createAdminLog).mockResolvedValue({} as never);
|
||||
});
|
||||
|
||||
it("creates a key and its event only inside the selected tenant context", async () => {
|
||||
vi.mocked(getApiKeyByAlias).mockImplementation(async () => {
|
||||
expect(getRlsExecutionContext()).toMatchObject({ userId: operator.id, tenantId: "tenant_b" });
|
||||
return null;
|
||||
});
|
||||
vi.mocked(createApiKey).mockImplementation(async () => {
|
||||
expect(getRlsExecutionContext()).toMatchObject({ userId: operator.id, tenantId: "tenant_b" });
|
||||
return { ...existing, id: "key_b", tenantId: "tenant_b" } as never;
|
||||
});
|
||||
vi.mocked(EventsService.create).mockImplementation(async () => {
|
||||
expect(getRlsExecutionContext()).toMatchObject({ userId: operator.id, tenantId: "tenant_b" });
|
||||
});
|
||||
|
||||
const response = await callCreate({ action: "create", "tenant-id": "tenant_b", alias: "Primary", active: "on" });
|
||||
|
||||
expect(response.status).toBe(302);
|
||||
expect(response.headers.get("Location")).toContain(`toast=${encodeURIComponent("models.apiKey.toast.created")}`);
|
||||
expect(createApiKey).toHaveBeenCalledWith(expect.objectContaining({ tenantId: "tenant_b", createdByUserId: operator.id }));
|
||||
});
|
||||
|
||||
it("rejects a forged tenant before probing aliases or creating a key", async () => {
|
||||
const response = await callCreate({ action: "create", "tenant-id": "tenant_forged", alias: "Primary" });
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(getApiKeyByAlias).not.toHaveBeenCalled();
|
||||
expect(createApiKey).not.toHaveBeenCalled();
|
||||
expect(EventsService.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects moving an existing key to another tenant", async () => {
|
||||
const response = await callEdit({ action: "edit", "tenant-id": "tenant_b", alias: "Moved", active: "on" });
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
await expect(response.json()).resolves.toEqual({ error: "translated:models.apiKey.errors.tenantChangeNotAllowed" });
|
||||
expect(getApiKeys).not.toHaveBeenCalled();
|
||||
expect(updateApiKey).not.toHaveBeenCalled();
|
||||
expect(EventsService.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("updates and deletes only inside the key's owning tenant context", async () => {
|
||||
vi.mocked(updateApiKey).mockImplementation(async () => {
|
||||
expect(getRlsExecutionContext()).toMatchObject({ userId: operator.id, tenantId: "tenant_a" });
|
||||
return existing as never;
|
||||
});
|
||||
vi.mocked(deleteApiKey).mockImplementation(async () => {
|
||||
expect(getRlsExecutionContext()).toMatchObject({ userId: operator.id, tenantId: "tenant_a" });
|
||||
return existing as never;
|
||||
});
|
||||
|
||||
const editResponse = await callEdit({ action: "edit", "tenant-id": "tenant_a", alias: "Updated", active: "on" });
|
||||
const deleteResponse = await callEdit({ action: "delete" });
|
||||
|
||||
expect(editResponse.status).toBe(302);
|
||||
expect(deleteResponse.status).toBe(302);
|
||||
expect(editResponse.headers.get("Location")).toContain(`toast=${encodeURIComponent("models.apiKey.toast.saved")}`);
|
||||
expect(deleteResponse.headers.get("Location")).toContain(`toast=${encodeURIComponent("models.apiKey.toast.deleted")}`);
|
||||
expect(updateApiKey).toHaveBeenCalledWith("key_a", expect.objectContaining({ tenantId: "tenant_a", alias: "Updated" }));
|
||||
expect(deleteApiKey).toHaveBeenCalledWith("key_a", "tenant_a");
|
||||
});
|
||||
});
|
||||
+35
-28
@@ -1,4 +1,5 @@
|
||||
import { Tenant } from "@hivegrid/db/prisma-browser";
|
||||
import type { Tenant } from "@hivegrid/db/prisma-browser";
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { useActionData, useNavigate } from "react-router";
|
||||
import ApiKeyCreatedModal from "~/components/core/apiKeys/ApiKeyCreatedModal";
|
||||
@@ -7,7 +8,7 @@ import OpenModal from "~/components/ui/modals/OpenModal";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { createApiKey, getApiKeyByAlias } from "~/utils/db/apiKeys.db.server";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { adminGetAllTenants } from "~/utils/db/tenants.db.server";
|
||||
import { adminGetAllTenantsIdsAndNames } from "~/utils/db/tenants.db.server";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import EventsService from "~/modules/events/services/.server/EventsService";
|
||||
@@ -16,11 +17,11 @@ import { ApiKeyCreatedDto } from "~/modules/events/dtos/ApiKeyCreatedDto";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
type LoaderData = {
|
||||
tenants: Tenant[];
|
||||
tenants: Pick<Tenant, "id" | "name">[];
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.create");
|
||||
const tenants = await adminGetAllTenants();
|
||||
const tenants = await adminGetAllTenantsIdsAndNames();
|
||||
const data: LoaderData = {
|
||||
tenants,
|
||||
};
|
||||
@@ -35,7 +36,7 @@ type ActionData = {
|
||||
};
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
export const action: ActionFunction = async ({ request, params: _params }) => {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.create");
|
||||
const { t } = await getTranslations(request);
|
||||
const userInfo = await getUserInfo(request);
|
||||
@@ -52,34 +53,40 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
}
|
||||
const tenantId = form.get("tenant-id")?.toString() ?? "";
|
||||
const alias = form.get("alias")?.toString() ?? "";
|
||||
const existingAlias = await getApiKeyByAlias(tenantId, alias);
|
||||
if (existingAlias) {
|
||||
return badRequest({ error: t("models.apiKey.errors.aliasExists", { alias }) });
|
||||
const tenantExists = (await adminGetAllTenantsIdsAndNames()).some((tenant) => tenant.id === tenantId);
|
||||
if (!tenantExists) {
|
||||
return badRequest({ error: t("shared.notFound") });
|
||||
}
|
||||
const active = Boolean(form.get("active"));
|
||||
const apiKey = await createApiKey({
|
||||
tenantId,
|
||||
createdByUserId: userInfo.userId,
|
||||
alias,
|
||||
expires: expirationDate,
|
||||
active,
|
||||
});
|
||||
await createAdminLog(request, "admin.apiKeys.created", JSON.stringify({ id: apiKey.id, tenantId, alias, expirationDate, active }));
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "api_key.created",
|
||||
tenantId,
|
||||
userId: currentUser?.id ?? "",
|
||||
data: {
|
||||
id: apiKey.id,
|
||||
alias: apiKey.alias,
|
||||
await runWithRlsContext({ tenantId }, async () => {
|
||||
const existingAlias = await getApiKeyByAlias(tenantId, alias);
|
||||
if (existingAlias) {
|
||||
throw badRequest({ error: t("models.apiKey.errors.aliasExists", { alias }) });
|
||||
}
|
||||
const apiKey = await createApiKey({
|
||||
tenantId,
|
||||
createdByUserId: userInfo.userId,
|
||||
alias,
|
||||
expires: expirationDate,
|
||||
active: active,
|
||||
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
|
||||
} satisfies ApiKeyCreatedDto,
|
||||
active,
|
||||
});
|
||||
await createAdminLog(request, "admin.apiKeys.created", JSON.stringify({ id: apiKey.id, tenantId, alias, expirationDate, active }));
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "api_key.created",
|
||||
tenantId,
|
||||
userId: currentUser?.id ?? "",
|
||||
data: {
|
||||
id: apiKey.id,
|
||||
alias: apiKey.alias,
|
||||
expires: expirationDate,
|
||||
active: active,
|
||||
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
|
||||
} satisfies ApiKeyCreatedDto,
|
||||
});
|
||||
});
|
||||
// return success({ apiKey });
|
||||
return redirect(adminPath("api/keys", { mode: "host-aware" }));
|
||||
return redirect(`${adminPath("api/keys", { mode: "host-aware" })}?toast=${encodeURIComponent("models.apiKey.toast.created")}`);
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user