Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Prevent requests with `undefined` collection id (#78822)

Timofey Kachalovfedf6fbe0162
diff --git a/e2e/test-component/scenarios/embedding-sdk/sdk-question.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/sdk-question.cy.spec.tsx
index f210b88dcc0..f05bb446689 100644
--- a/e2e/test-component/scenarios/embedding-sdk/sdk-question.cy.spec.tsx
+++ b/e2e/test-component/scenarios/embedding-sdk/sdk-question.cy.spec.tsx
@@ -66,6 +66,30 @@ describe("scenarios > embedding-sdk > interactive-question", () => {
});
});
+ it("should not request a collection the current user does not have", () => {
+ // The question's Save affordance asks whether the user can write to the
+ // target collection. With no `targetCollection` that resolves to
+ // "personal" — which resolves to nothing for a user without a personal
+ // collection, and building a URL from that hits `/api/collection/undefined`.
+ cy.intercept("GET", "/api/user/current", (req) => {
+ req.continue((res) => {
+ delete res.body.personal_collection_id;
+ });
+ });
+ cy.intercept("GET", "/api/collection/undefined*").as(
+ "unresolvedCollection",
+ );
+
+ mountInteractiveQuestion();
+
+ getSdkRoot().within(() => {
+ cy.findByText("Product ID").should("be.visible");
+ cy.findByText("Max of Quantity").should("be.visible");
+ });
+
+ cy.get("@unresolvedCollection.all").should("have.length", 0);
+ });
+
it("should not show the expand button (metabase#68975)", () => {
mountInteractiveQuestion();
diff --git a/frontend/src/embedding-sdk-bundle/components/public/CollectionBrowser/CollectionBrowser.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/CollectionBrowser/CollectionBrowser.unit.spec.tsx
index dd2dea12354..330a40caf59 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/CollectionBrowser/CollectionBrowser.unit.spec.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/CollectionBrowser/CollectionBrowser.unit.spec.tsx
@@ -75,6 +75,41 @@ describe("CollectionBrowser", () => {
expect(screen.getByText("Last edited at")).toBeInTheDocument();
});
+ it("renders the empty table without requesting an undefined collection when the user has no personal collection", async () => {
+ // An API-key user (the data-app dev preview) never has a personal
+ // collection, so "personal" resolves to nothing. The browser must render
+ // its empty state, not request `/api/collection/undefined(/items)`.
+ useLocaleMock.mockReturnValue({ isLocaleLoading: false });
+ setupCollectionsEndpoints({
+ collections: TEST_COLLECTIONS,
+ rootCollection: ROOT_TEST_COLLECTION,
+ });
+
+ // API-key users (the data-app preview) come back with no
+ // `personal_collection_id`, though the type marks it required — simulate
+ // that shape.
+ const userWithoutPersonalCollection = {
+ ...createMockUser(),
+ personal_collection_id: undefined,
+ } as unknown as User;
+
+ renderWithSDKProviders(<CollectionBrowserInner collectionId="personal" />, {
+ componentProviderProps: { authConfig: createMockSdkConfig() },
+ storeInitialState: setupSdkState({
+ currentUser: userWithoutPersonalCollection,
+ }),
+ });
+
+ // The empty state renders, rather than nothing.
+ expect(
+ await screen.findByTestId("collection-empty-state"),
+ ).toBeInTheDocument();
+
+ expect(
+ fetchMock.callHistory.calls("glob:*/api/collection/undefined*"),
+ ).toHaveLength(0);
+ });
+
it("should allow to hide certain columns", async () => {
await setup({
props: {
diff --git a/frontend/src/embedding-sdk-bundle/components/public/CreateDashboardModal/CreateDashboardModal.tsx b/frontend/src/embedding-sdk-bundle/components/public/CreateDashboardModal/CreateDashboardModal.tsx
index 11905db8ed1..5e13c4a2447 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/CreateDashboardModal/CreateDashboardModal.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/CreateDashboardModal/CreateDashboardModal.tsx
@@ -8,7 +8,7 @@ import type {
MetabaseDashboard,
SdkCollectionId,
} from "embedding-sdk-bundle/types";
-import { useGetCollectionQuery } from "metabase/api";
+import { skipToken, useGetCollectionQuery } from "metabase/api";
import { CreateDashboardModal as CreateDashboardModalCore } from "metabase/common/CreateDashboard/CreateDashboardModal";
import { useLocale } from "metabase/common/hooks";
import { useSelector } from "metabase/redux";
@@ -69,9 +69,10 @@ const CreateDashboardModalInner = ({
: undefined,
);
- const { isLoading: isCollectionQueryLoading } = useGetCollectionQuery({
- id: collectionIdSlug,
- });
+ const { isLoading: isCollectionQueryLoading } = useGetCollectionQuery(
+ // To avoid `/api/collection/undefined` and 404.
+ collectionIdSlug === undefined ? skipToken : { id: collectionIdSlug },
+ );
useTrackSdkComponentMount("CreateDashboardModal", null, {});
diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-collection-data.ts b/frontend/src/embedding-sdk-bundle/hooks/private/use-collection-data.ts
index 4c9f330b8d5..aa9a735d96c 100644
--- a/frontend/src/embedding-sdk-bundle/hooks/private/use-collection-data.ts
+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-collection-data.ts
@@ -4,7 +4,7 @@ import { useSdkBreadcrumbs } from "embedding-sdk-bundle/hooks/private/use-sdk-br
import { useSdkSelector } from "embedding-sdk-bundle/store";
import { getCollectionIdSlugFromReference } from "embedding-sdk-bundle/store/collections";
import type { SdkCollectionId } from "embedding-sdk-bundle/types/collection";
-import { useGetCollectionQuery } from "metabase/api";
+import { skipToken, useGetCollectionQuery } from "metabase/api";
import type { CollectionId } from "metabase-types/api";
export const useCollectionData = (
@@ -16,8 +16,9 @@ export const useCollectionData = (
);
// Internal collection state.
- const [internalCollectionId, setInternalCollectionId] =
- useState<CollectionId>(baseCollectionId);
+ const [internalCollectionId, setInternalCollectionId] = useState<
+ CollectionId | undefined
+ >(baseCollectionId);
const { isBreadcrumbEnabled: isGlobalBreadcrumbEnabled, currentLocation } =
useSdkBreadcrumbs();
@@ -35,8 +36,10 @@ export const useCollectionData = (
error: collectionLoadingError,
isFetching: isFetchingCollection,
} = useGetCollectionQuery(
- { id: effectiveCollectionId },
- { skip: skipCollectionFetching },
+ // To avoid `/api/collection/undefined` and 404.
+ effectiveCollectionId === undefined || skipCollectionFetching
+ ? skipToken
+ : { id: effectiveCollectionId },
);
return {
diff --git a/frontend/src/embedding-sdk-bundle/store/collections.ts b/frontend/src/embedding-sdk-bundle/store/collections.ts
index 141447b8370..b3d3e5fe813 100644
--- a/frontend/src/embedding-sdk-bundle/store/collections.ts
+++ b/frontend/src/embedding-sdk-bundle/store/collections.ts
@@ -49,10 +49,12 @@ export const getCollectionIdValueFromReference = createSelector(
);
/**
- * This return an "id"/"slug" that can be used in `/api/collection/{:id}`
- * There are extra handlers for "root" and "trash" so unlike when
- * creating a dashboard, we have to pass "root" for the root collection
- * instead of null
+ * Returns an "id"/"slug" for `/api/collection/{:id}` — unlike when creating a
+ * dashboard, the root collection is `"root"` here rather than null.
+ *
+ * `undefined` when `"personal"` can't be resolved: `currentUser` hasn't loaded
+ * yet, or has no personal collection. Callers must handle that (e.g. with
+ * `skipToken`) — `/api/collection/undefined` is a 404.
*/
export const getCollectionIdSlugFromReference = createSelector(
[
@@ -64,27 +66,24 @@ export const getCollectionIdSlugFromReference = createSelector(
personalCollectionId,
tenantCollectionId,
collectionReference,
- ): CollectionId => {
- return (
- match(collectionReference)
- // Unjustified type cast. FIXME
- .with("personal", () => personalCollectionId as RegularCollectionId)
- .with("tenant", () => {
- if (!tenantCollectionId) {
- throw new Error(
- "You must be a tenant member to access the tenant collection.",
- );
- }
-
- return tenantCollectionId;
- })
- .with("root", () => "root" as const)
- .with(P.union(P.number, P.string), (id) => id)
- .otherwise(() => {
+ ): CollectionId | undefined => {
+ return match(collectionReference)
+ .with("personal", () => personalCollectionId)
+ .with("tenant", () => {
+ if (!tenantCollectionId) {
throw new Error(
- "Invalid collection id, expected `number | string | 'root' | 'personal' | 'tenant'`",
+ "You must be a tenant member to access the tenant collection.",
);
- })
- );
+ }
+
+ return tenantCollectionId;
+ })
+ .with("root", () => "root" as const)
+ .with(P.union(P.number, P.string), (id) => id)
+ .otherwise(() => {
+ throw new Error(
+ "Invalid collection id, expected `number | string | 'root' | 'personal' | 'tenant'`",
+ );
+ });
},
);
diff --git a/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.tsx b/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.tsx
index 98190a9c9ac..a202dcc71aa 100644
--- a/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.tsx
+++ b/frontend/src/metabase/collections/components/CollectionContent/CollectionItemsTable.tsx
@@ -7,7 +7,7 @@ import {
useState,
} from "react";
-import { useListCollectionItemsQuery } from "metabase/api";
+import { skipToken, useListCollectionItemsQuery } from "metabase/api";
import {
ALL_MODELS,
COLLECTION_PAGE_SIZE,
@@ -58,7 +58,7 @@ const getDefaultSortingOptions = (
};
export type CollectionItemsTableProps = {
- collectionId: CollectionId;
+ collectionId?: CollectionId;
} & Partial<{
bookmarks: Bookmark[];
clear: () => void;
@@ -163,16 +163,20 @@ export const CollectionItemsTable = ({
selectOnlyTheseItems={selectOnlyTheseItems}
toggleItem={toggleItem}
unpinnedItemsSorting={unpinnedItemsSorting}
- unpinnedQuery={{
- id: collectionId,
- models,
- limit: pageSize,
- offset: pageSize * page,
- ...(showAllItems
- ? { show_dashboard_questions: showDashboardQuestions }
- : { pinned_state: "is_not_pinned" }),
- ...unpinnedItemsSorting,
- }}
+ unpinnedQuery={
+ collectionId === undefined
+ ? skipToken
+ : {
+ id: collectionId,
+ models,
+ limit: pageSize,
+ offset: pageSize * page,
+ ...(showAllItems
+ ? { show_dashboard_questions: showDashboardQuestions }
+ : { pinned_state: "is_not_pinned" }),
+ ...unpinnedItemsSorting,
+ }
+ }
visibleColumns={visibleColumns}
onClick={onClick}
onNextPage={handleNextPage}
@@ -185,7 +189,7 @@ export const CollectionItemsTable = ({
type CollectionItemsTableContentProps = CollectionItemsTableProps & {
page: number;
unpinnedItemsSorting: SortingOptions<ListCollectionItemsSortColumn>;
- unpinnedQuery: ListCollectionItemsRequest;
+ unpinnedQuery: ListCollectionItemsRequest | typeof skipToken;
onNextPage: () => void;
onPreviousPage: () => void;
onUnpinnedItemsSortingChange: (