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
+1
-6
@@ -1,10 +1,8 @@
|
||||
import { useSubmit, useSearchParams, useNavigation, useParams } from "react-router";
|
||||
import { useSubmit, useParams } from "react-router";
|
||||
import { useState } from "react";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import RefreshIcon from "~/components/ui/icons/RefreshIcon";
|
||||
import InputFilters from "~/components/ui/input/InputFilters";
|
||||
import InputSearchWithURL from "~/components/ui/input/InputSearchWithURL";
|
||||
import ShowPayloadModalButton from "~/components/ui/json/ShowPayloadModalButton";
|
||||
@@ -32,13 +30,10 @@ export default function ApiKeyLogsDetails({ data }: Props) {
|
||||
const formatters = useLocaleFormatters();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const submit = useSubmit();
|
||||
const navigation = useNavigation();
|
||||
const params = useParams();
|
||||
|
||||
const canDelete = !params.tenant;
|
||||
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
|
||||
const [selectedRows, setSelectedRows] = useState<ApiKeyLogDto[]>([]);
|
||||
function onDelete(ids: string[]) {
|
||||
if (!canDelete) {
|
||||
|
||||
-28
@@ -1,28 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { readRepoFile } from "~/utils/testing/repoPaths";
|
||||
|
||||
describe("ApiKeyLogsSummary i18n", () => {
|
||||
it("keeps visible summary controls behind semantic API log keys", () => {
|
||||
const source = [
|
||||
"apps/web/app/modules/api/components/ApiKeyLogsSummary.tsx",
|
||||
"apps/web/app/modules/api/components/ApiCallSpeedBadge.tsx",
|
||||
"apps/web/app/modules/metrics/components/SpeedBadge.tsx",
|
||||
]
|
||||
.map((file) => readRepoFile(file))
|
||||
.join("\n");
|
||||
|
||||
expect(source).toContain("models.apiKeyLog.groupBy.placeholder");
|
||||
expect(source).toContain("models.apiKeyLog.calls");
|
||||
expect(source).toContain("models.apiKeyLog.avgDuration");
|
||||
expect(source).toContain("metrics.speed.lightningFast");
|
||||
expect(source).toContain("metrics.speed.verySlow");
|
||||
expect(source).not.toContain("ui.autogenerated");
|
||||
expect(source).not.toContain("lightning_fast");
|
||||
expect(source).not.toContain("response_schema");
|
||||
expect(source).not.toContain("body_example");
|
||||
expect(source).not.toContain('"Group by"');
|
||||
expect(source).not.toContain('"Select group by"');
|
||||
expect(source).not.toContain('"Please select at least one group by"');
|
||||
expect(source).not.toContain('"Speed"');
|
||||
});
|
||||
});
|
||||
-192
@@ -1,192 +0,0 @@
|
||||
import { Link, useParams, useSearchParams } from "react-router";
|
||||
import { useEffect, useState } from "react";
|
||||
import ApiKeyLogUtils from "../utils/ApiKeyLogUtils";
|
||||
import { RowHeaderDisplayDto } from "~/application/dtos/data/RowHeaderDisplayDto";
|
||||
import { ApiCallSummaryDto } from "../dtos/ApiCallSummaryDto";
|
||||
import ApiKeyLogsConstants from "../utils/ApiKeyLogsConstants";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import { FilterableValueLink } from "~/components/ui/links/FilterableValueLink";
|
||||
import WarningBanner from "~/components/ui/banners/WarningBanner";
|
||||
import InputCombobox from "~/components/ui/input/InputCombobox";
|
||||
import InputFilters from "~/components/ui/input/InputFilters";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import ApiUtils from "~/utils/app/ApiUtils";
|
||||
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import ApiCallSpeedBadge from "./ApiCallSpeedBadge";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
interface Props {
|
||||
data: {
|
||||
items: ApiCallSummaryDto[];
|
||||
allTenants: { id: string; name: string }[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
};
|
||||
}
|
||||
export default function ApiKeyLogsSummary({ data }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const params = useParams();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const [groupBy, setGroupBy] = useState<string[]>(ApiKeyLogUtils.getGroupByValues(searchParams));
|
||||
|
||||
const [headers, setHeaders] = useState<RowHeaderDisplayDto<ApiCallSummaryDto>[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (ApiKeyLogUtils.getGroupByValues(searchParams).sort().join(",") !== groupBy.sort().join(",")) {
|
||||
searchParams.delete("groupBy");
|
||||
groupBy.forEach((by) => {
|
||||
searchParams.append("groupBy", by);
|
||||
});
|
||||
setSearchParams(searchParams);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [groupBy]);
|
||||
|
||||
useEffect(() => {
|
||||
const headers: RowHeaderDisplayDto<ApiCallSummaryDto>[] = [];
|
||||
let currentGroupBy = groupBy;
|
||||
if (currentGroupBy.length === 0) {
|
||||
currentGroupBy = ApiKeyLogsConstants.DEFAULT_GROUP_BY;
|
||||
}
|
||||
const getTenant = (item: ApiCallSummaryDto) => {
|
||||
return data.allTenants.find((x) => x.id === item.tenantId);
|
||||
};
|
||||
const getCountLink = (item: ApiCallSummaryDto) => {
|
||||
const searchParams = new URLSearchParams();
|
||||
// searchParams.set("pageSize", "100");
|
||||
currentGroupBy.forEach((groupBy) => {
|
||||
if (groupBy === "method") {
|
||||
searchParams.append("method", item.method);
|
||||
} else if (groupBy === "endpoint") {
|
||||
searchParams.append("endpoint", item.endpoint);
|
||||
} else if (groupBy === "params") {
|
||||
searchParams.append("params", item.params);
|
||||
} else if (groupBy === "status") {
|
||||
searchParams.append("status", item.status?.toString() ?? "{null}");
|
||||
}
|
||||
});
|
||||
return UrlUtils.getModulePath(params, `api/logs?${searchParams.toString()}`);
|
||||
};
|
||||
if (groupBy.includes("method")) {
|
||||
headers.push({
|
||||
name: "method",
|
||||
title: t("models.apiKeyLog.method"),
|
||||
value: (item) => (
|
||||
<FilterableValueLink name="method" value={item.method}>
|
||||
<SimpleBadge title={item.method} color={ApiUtils.getMethodColor(item.method)} underline />
|
||||
</FilterableValueLink>
|
||||
),
|
||||
});
|
||||
}
|
||||
if (groupBy.includes("endpoint")) {
|
||||
headers.push({
|
||||
name: "endpoint",
|
||||
title: t("models.apiKeyLog.endpoint"),
|
||||
value: (item) => <FilterableValueLink name="endpoint" value={item.endpoint} />,
|
||||
});
|
||||
}
|
||||
if (groupBy.includes("params")) {
|
||||
headers.push({
|
||||
name: "params",
|
||||
title: t("models.apiKeyLog.params"),
|
||||
value: (item) => <FilterableValueLink name="params" value={item.params} />,
|
||||
});
|
||||
}
|
||||
if (groupBy.includes("status")) {
|
||||
headers.push({
|
||||
name: "status",
|
||||
title: t("models.apiKeyLog.status"),
|
||||
value: (item) => (
|
||||
<FilterableValueLink name="status" value={item.status?.toString() ?? "{null}"}>
|
||||
<SimpleBadge title={item.status?.toString() ?? t("shared.unknown")} color={item.status?.toString().startsWith("4") ? Colors.RED : Colors.GREEN} />
|
||||
</FilterableValueLink>
|
||||
),
|
||||
});
|
||||
}
|
||||
if (groupBy.includes("tenantId")) {
|
||||
headers.push({
|
||||
name: "tenantId",
|
||||
title: t("models.apiKeyLog.tenant"),
|
||||
value: (item) => <FilterableValueLink name="tenantId" value={getTenant(item)?.name ?? ""} />,
|
||||
});
|
||||
}
|
||||
headers.push({
|
||||
name: "apiCalls",
|
||||
title: t("models.apiKeyLog.apiCalls"),
|
||||
align: "right",
|
||||
value: (item) => (
|
||||
<div className="flex justify-end text-right">
|
||||
<Link to={getCountLink(item)} className="hover:underline">
|
||||
{t("models.apiKeyLog.calls", { count: Number(item._count._all), formattedCount: formatters.number(Number(item._count._all)) })}
|
||||
</Link>
|
||||
</div>
|
||||
),
|
||||
});
|
||||
|
||||
headers.push({
|
||||
name: "duration",
|
||||
title: t("models.apiKeyLog.avgDuration"),
|
||||
value: (item) =>
|
||||
item._avg.duration === null ? (
|
||||
<span className="text-muted-foreground text-xs italic">{t("shared.notAvailable")}</span>
|
||||
) : (
|
||||
<div>{formatters.number(Number(item._avg.duration), { style: "unit", unit: "millisecond", unitDisplay: "short", maximumFractionDigits: 3 })}</div>
|
||||
),
|
||||
});
|
||||
headers.push({
|
||||
name: "speed",
|
||||
title: t("models.apiKeyLog.speed"),
|
||||
value: (item) =>
|
||||
item._avg.duration === null ? (
|
||||
<span className="text-muted-foreground text-xs italic">{t("shared.notAvailable")}</span>
|
||||
) : (
|
||||
<ApiCallSpeedBadge duration={Number(item._avg.duration)} />
|
||||
),
|
||||
});
|
||||
headers.push({
|
||||
name: "actions",
|
||||
title: "",
|
||||
value: (item) => (
|
||||
<Link to={getCountLink(item)} className="hover:underline">
|
||||
{t("shared.details")} <span className="ml-1">→</span>
|
||||
</Link>
|
||||
),
|
||||
});
|
||||
|
||||
setHeaders(headers);
|
||||
}, [data, groupBy, params, t]);
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="flex w-full items-center space-x-2">
|
||||
<InputCombobox
|
||||
name="groupBy"
|
||||
prefix={t("models.apiKeyLog.groupBy.prefix")}
|
||||
className="bg-background h-8"
|
||||
selectPlaceholder={t("models.apiKeyLog.groupBy.placeholder")}
|
||||
options={[
|
||||
{ value: "method", name: t("models.apiKeyLog.method") },
|
||||
{ value: "endpoint", name: t("models.apiKeyLog.endpoint") },
|
||||
{ value: "params", name: t("models.apiKeyLog.params") },
|
||||
{ value: "status", name: t("models.apiKeyLog.status") },
|
||||
{ value: "tenantId", name: t("models.apiKeyLog.tenant") },
|
||||
]}
|
||||
value={groupBy}
|
||||
onChange={(value) => {
|
||||
setGroupBy(value as string[]);
|
||||
}}
|
||||
/>
|
||||
<div className="grow">{/* <InputSearchWithURL /> */}</div>
|
||||
<InputFilters size="sm" filters={data.filterableProperties} />
|
||||
</div>
|
||||
{groupBy.length === 0 ? (
|
||||
<WarningBanner title={t("models.apiKeyLog.groupBy.title")} text={t("models.apiKeyLog.groupBy.required")} />
|
||||
) : (
|
||||
<TableSimple items={data.items} headers={headers} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
findScopes: vi.fn(),
|
||||
deleteForTenant: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/db/accounts.server", () => ({
|
||||
adminGetAllLegacyTenantSummaries: vi.fn(async () => []),
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/db/api-keys.server", () => ({
|
||||
countLegacyApiKeyLogs: vi.fn(),
|
||||
deleteTenantLegacyApiKeyLogsByIds: mocks.deleteForTenant,
|
||||
findLegacyApiKeyLogTenantScopesByIds: mocks.findScopes,
|
||||
getLegacyApiKeyLogAdminDetails: vi.fn(),
|
||||
groupLegacyApiKeyLogs: vi.fn(),
|
||||
tenantLegacyApiKeyLogScope: (tenantId: string) => ({ tenantId }),
|
||||
}));
|
||||
|
||||
import ApiKeyLogService from "./ApiKeyLogService";
|
||||
|
||||
describe("ApiKeyLogService admin RLS deletion", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.deleteForTenant.mockImplementation(async ({ tenantId }: { tenantId: string }) => {
|
||||
expect(getRlsExecutionContext()).toMatchObject({ userId: "operator_1", tenantId });
|
||||
return { count: 1 };
|
||||
});
|
||||
});
|
||||
|
||||
it("deletes each selected log only inside its owning tenant context", async () => {
|
||||
mocks.findScopes.mockResolvedValue([
|
||||
{ id: "log_a", tenantId: "tenant_a" },
|
||||
{ id: "log_b", tenantId: "tenant_b" },
|
||||
]);
|
||||
|
||||
const result = await runWithRlsContext({ userId: "operator_1" }, () => ApiKeyLogService.adminDeleteMany(["log_a", "log_b"]));
|
||||
|
||||
expect(result).toEqual({ deletedCount: 2, rejectedTenantlessIds: [] });
|
||||
expect(mocks.deleteForTenant).toHaveBeenCalledTimes(2);
|
||||
expect(mocks.deleteForTenant).toHaveBeenCalledWith({ ids: ["log_a"], tenantId: "tenant_a" });
|
||||
expect(mocks.deleteForTenant).toHaveBeenCalledWith({ ids: ["log_b"], tenantId: "tenant_b" });
|
||||
});
|
||||
|
||||
it("rejects the whole batch when it contains a tenantless platform log", async () => {
|
||||
mocks.findScopes.mockResolvedValue([
|
||||
{ id: "log_a", tenantId: "tenant_a" },
|
||||
{ id: "log_platform", tenantId: null },
|
||||
]);
|
||||
|
||||
const result = await runWithRlsContext({ userId: "operator_1" }, () => ApiKeyLogService.adminDeleteMany(["log_a", "log_platform"]));
|
||||
|
||||
expect(result).toEqual({ deletedCount: 0, rejectedTenantlessIds: ["log_platform"] });
|
||||
expect(mocks.deleteForTenant).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("fails closed outside an unscoped authenticated operator request", async () => {
|
||||
await expect(ApiKeyLogService.adminDeleteMany(["log_a"])).rejects.toThrow("unscoped authenticated operator context");
|
||||
await expect(runWithRlsContext({ userId: "operator_1", tenantId: "tenant_a" }, () => ApiKeyLogService.adminDeleteMany(["log_a"]))).rejects.toThrow(
|
||||
"unscoped authenticated operator context"
|
||||
);
|
||||
expect(mocks.findScopes).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+49
-5
@@ -1,14 +1,15 @@
|
||||
import { adminGetAllLegacyTenantSummaries } from "@hivegrid/db/accounts.server";
|
||||
import {
|
||||
adminDeleteLegacyApiKeyLogsByIds,
|
||||
countLegacyApiKeyLogs,
|
||||
deleteTenantLegacyApiKeyLogsByIds,
|
||||
findLegacyApiKeyLogTenantScopesByIds,
|
||||
getLegacyApiKeyLogAdminDetails,
|
||||
groupLegacyApiKeyLogs,
|
||||
tenantLegacyApiKeyLogScope,
|
||||
type LegacyApiKeyLogOrderByInput,
|
||||
type LegacyApiKeyLogWhereInput,
|
||||
} from "@hivegrid/db/api-keys.server";
|
||||
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
import { Prisma } from "@hivegrid/db/prisma-browser";
|
||||
import { Params } from "react-router";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
@@ -63,7 +64,7 @@ async function getDetails({ request, params }: { request: Request; params: Param
|
||||
const totalItems = await countLegacyApiKeyLogs(whereFilters);
|
||||
|
||||
return {
|
||||
items: items as ApiKeyLogDto[],
|
||||
items: items.map(toApiKeyLogDto),
|
||||
filterableProperties,
|
||||
pagination: {
|
||||
page: pagination.page,
|
||||
@@ -170,12 +171,55 @@ async function getFilters({ request, params }: { request: Request; params: Param
|
||||
return { filterableProperties, whereFilters, allTenants };
|
||||
}
|
||||
|
||||
async function adminDeleteMany(ids: string[]) {
|
||||
return await adminDeleteLegacyApiKeyLogsByIds(ids);
|
||||
async function adminDeleteMany(ids: string[]): Promise<{ deletedCount: number; rejectedTenantlessIds: string[] }> {
|
||||
const context = getRlsExecutionContext();
|
||||
if (!context?.userId || context.tenantId) {
|
||||
throw new Error("Admin API log deletion requires an unscoped authenticated operator context");
|
||||
}
|
||||
|
||||
const normalizedIds = [...new Set(ids.map((id) => id.trim()).filter(Boolean))];
|
||||
if (normalizedIds.length === 0) return { deletedCount: 0, rejectedTenantlessIds: [] };
|
||||
if (normalizedIds.length > 500) {
|
||||
throw new Error("At most 500 API log entries can be deleted at once");
|
||||
}
|
||||
|
||||
const scopes = await findLegacyApiKeyLogTenantScopesByIds(normalizedIds);
|
||||
const rejectedTenantlessIds = scopes.filter((scope) => !scope.tenantId).map((scope) => scope.id);
|
||||
if (rejectedTenantlessIds.length > 0) {
|
||||
return { deletedCount: 0, rejectedTenantlessIds };
|
||||
}
|
||||
|
||||
const byTenant = new Map<string, string[]>();
|
||||
for (const scope of scopes) {
|
||||
if (!scope.tenantId) continue;
|
||||
const tenantIds = byTenant.get(scope.tenantId) ?? [];
|
||||
tenantIds.push(scope.id);
|
||||
byTenant.set(scope.tenantId, tenantIds);
|
||||
}
|
||||
await Promise.all(
|
||||
[...byTenant].map(([tenantId, tenantIds]) => runWithRlsContext({ tenantId }, () => deleteTenantLegacyApiKeyLogsByIds({ ids: tenantIds, tenantId })))
|
||||
);
|
||||
return { deletedCount: scopes.length, rejectedTenantlessIds: [] };
|
||||
}
|
||||
|
||||
async function deleteManyForTenant(ids: string[], tenantId: string | null) {
|
||||
return await deleteTenantLegacyApiKeyLogsByIds({ ids, tenantId });
|
||||
return tenantId
|
||||
? runWithRlsContext({ tenantId }, () => deleteTenantLegacyApiKeyLogsByIds({ ids, tenantId }))
|
||||
: deleteTenantLegacyApiKeyLogsByIds({ ids, tenantId });
|
||||
}
|
||||
|
||||
function toApiKeyLogDto(item: Awaited<ReturnType<typeof getLegacyApiKeyLogAdminDetails>>[number]): ApiKeyLogDto {
|
||||
if (item.apiKey || !item.apiKeyId || !item.alias || !item.tenantId) return item as ApiKeyLogDto;
|
||||
return {
|
||||
...item,
|
||||
apiKey: {
|
||||
alias: item.alias,
|
||||
tenant: {
|
||||
id: item.tenantId,
|
||||
name: item.tenant?.name ?? item.tenantName ?? item.tenantId,
|
||||
},
|
||||
},
|
||||
} as ApiKeyLogDto;
|
||||
}
|
||||
|
||||
export default {
|
||||
|
||||
Reference in new issue
Block a user