The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Resolve tenant/personal collection sentinels in the question save path (#78104)
Sébastien6b1809dca19c
diff --git a/enterprise/frontend/src/metabase-enterprise/collections/use-get-default-collection-id/use-get-default-collection-id.ts b/enterprise/frontend/src/metabase-enterprise/collections/use-get-default-collection-id/use-get-default-collection-id.tsindex d2a2d9d8419..9080e94a412 100644--- a/enterprise/frontend/src/metabase-enterprise/collections/use-get-default-collection-id/use-get-default-collection-id.ts+++ b/enterprise/frontend/src/metabase-enterprise/collections/use-get-default-collection-id/use-get-default-collection-id.ts@@ -10,24 +10,30 @@ import type { CollectionId } from "metabase-types/api";*/export const useGetDefaultCollectionId = (sourceCollectionId?: CollectionId | null,+ { disabled = false }: { disabled?: boolean } = {},): CollectionId | null => {const { data: auditInfo } = useGetAuditInfoQuery(- sourceCollectionId ? undefined : skipToken,+ !disabled && sourceCollectionId ? undefined : skipToken,);const { data: collectionInfo } = useGetCollectionQuery(- sourceCollectionId ? { id: sourceCollectionId } : skipToken,+ !disabled && sourceCollectionId ? { id: sourceCollectionId } : skipToken,);const { data: customReportsCollectionInfo } = useGetCollectionQuery(- auditInfo?.custom_reports ? { id: auditInfo?.custom_reports } : skipToken,+ !disabled && auditInfo?.custom_reports+ ? { id: auditInfo?.custom_reports }+ : skipToken,);const isIAcollection = isInstanceAnalyticsCollection(collectionInfo);- const initialCollectionId = useOSSGetDefaultCollectionId(sourceCollectionId);+ const initialCollectionId = useOSSGetDefaultCollectionId(sourceCollectionId, {+ disabled,+ });if (+ !disabled &&isIAcollection &&auditInfo?.custom_reports &&customReportsCollectionInfo?.can_writediff --git a/frontend/src/metabase/common/collections/hooks.ts b/frontend/src/metabase/common/collections/hooks.tsindex ec9278e1687..2666b7c3262 100644--- a/frontend/src/metabase/common/collections/hooks.ts+++ b/frontend/src/metabase/common/collections/hooks.ts@@ -15,6 +15,13 @@ export type UseInitialCollectionIdProps = {collectionId?: Collection["id"] | null;location?: Location;params?: { collectionId?: Collection["id"]; slug?: string };+ /**+ * When `true`, skips every lookup and returns `null`. Callers that already+ * know the target collection (e.g. the SDK's `targetCollection` prop) use+ * this to avoid an unused `GET /api/collection/root` — a request tenant users+ * get a 403 for (EMB-2107).+ */+ disabled?: boolean;};const collectionIdParam = (id: Collection["id"] | undefined | null) =>@@ -25,12 +32,13 @@ export function useInitialCollectionId({collectionId,location,params,+ disabled = false,}: UseInitialCollectionIdProps = {}): CollectionId | null {const { data: fromCollectionId } = useGetCollectionQuery(- collectionIdParam(collectionId),+ disabled ? skipToken : collectionIdParam(collectionId),);const { data: fromNavParam } = useGetCollectionQuery(- collectionIdParam(params?.collectionId),+ disabled ? skipToken : collectionIdParam(params?.collectionId),);const idFromSlug =@@ -38,7 +46,7 @@ export function useInitialCollectionId({? Urls.extractCollectionId(params.slug): undefined;const { data: fromSlug } = useGetCollectionQuery(- collectionIdParam(idFromSlug),+ disabled ? skipToken : collectionIdParam(idFromSlug),);// Unjustified type cast. FIXME@@ -46,16 +54,20 @@ export function useInitialCollectionId({| Collection["id"]| undefined;const { data: fromQuery } = useGetCollectionQuery(- collectionIdParam(idFromQuery),+ disabled ? skipToken : collectionIdParam(idFromQuery),);const personalCollectionId = useSelector(getUserPersonalCollectionId);const isAuthenticated = useSelector(getUser) != null;const { data: rootCollection } = useGetCollectionQuery(- isAuthenticated ? { id: ROOT_COLLECTION.id } : skipToken,+ !disabled && isAuthenticated ? { id: ROOT_COLLECTION.id } : skipToken,);return useMemo(() => {+ if (disabled) {+ return null;+ }+const candidates = [fromCollectionId,fromNavParam,@@ -74,6 +86,7 @@ export function useInitialCollectionId({}return canonicalCollectionId(personalCollectionId);}, [+ disabled,fromCollectionId,fromNavParam,fromSlug,@@ -83,21 +96,32 @@ export function useInitialCollectionId({]);}+export type GetDefaultCollectionIdOptions = {+ /** When `true`, skips the lookup and returns `null`. Defaults to `false`. */+ disabled?: boolean;+};+export const useOSSGetDefaultCollectionId = (sourceCollectionId?: CollectionId | null,+ { disabled = false }: GetDefaultCollectionIdOptions = {},): CollectionId | null => {return useInitialCollectionId({collectionId: sourceCollectionId ?? undefined,+ disabled,});};export const useGetDefaultCollectionId = (sourceCollectionId?: CollectionId | null,+ options: GetDefaultCollectionIdOptions = {},): CollectionId | null => {if (PLUGIN_COLLECTIONS.useGetDefaultCollectionId) {// eslint-disable-next-line react-hooks/rules-of-hooks -- this won't change at runtime, so it's safe- return PLUGIN_COLLECTIONS.useGetDefaultCollectionId(sourceCollectionId);+ return PLUGIN_COLLECTIONS.useGetDefaultCollectionId(+ sourceCollectionId,+ options,+ );}// eslint-disable-next-line react-hooks/rules-of-hooks -- this won't change at runtime, so it's safe- return useOSSGetDefaultCollectionId(sourceCollectionId);+ return useOSSGetDefaultCollectionId(sourceCollectionId, options);};diff --git a/frontend/src/metabase/common/collections/hooks.unit.spec.tsx b/frontend/src/metabase/common/collections/hooks.unit.spec.tsxindex eebcc5c0e01..9daa980cb3c 100644--- a/frontend/src/metabase/common/collections/hooks.unit.spec.tsx+++ b/frontend/src/metabase/common/collections/hooks.unit.spec.tsx@@ -1,3 +1,5 @@+import fetchMock from "fetch-mock";+import { setupCollectionByIdEndpoint } from "__support__/server-mocks";import { createMockEntitiesState } from "__support__/store";import { renderWithProviders, screen } from "__support__/ui";@@ -9,10 +11,14 @@ import { useGetDefaultCollectionId } from "./hooks";const TestComponent = ({collectionId,+ disabled,}: {collectionId: CollectionId | null;+ disabled?: boolean;}) => {- const defaultCollectionId = useGetDefaultCollectionId(collectionId);+ const defaultCollectionId = useGetDefaultCollectionId(collectionId, {+ disabled,+ });return <div>id: {JSON.stringify(defaultCollectionId)}</div>;};@@ -44,10 +50,12 @@ const setup = ({collectionId,collections,hasRootAccess = true,+ disabled,}: {collectionId: CollectionId | null;collections: Collection[];hasRootAccess?: boolean;+ disabled?: boolean;}) => {const allCollections = [createMockCollection({@@ -64,9 +72,12 @@ const setup = ({});const state = createMockState({ currentUser: user, entities: entitiesState });- renderWithProviders(<TestComponent collectionId={collectionId} />, {- storeInitialState: state,- });+ renderWithProviders(+ <TestComponent collectionId={collectionId} disabled={disabled} />,+ {+ storeInitialState: state,+ },+ );};describe("enterprise > useGetDefaultCollectionId", () => {@@ -132,5 +143,19 @@ describe("enterprise > useGetDefaultCollectionId", () => {expect(await screen.findByText("id: 301")).toBeInTheDocument();});++ it("should return null and skip the lookup when disabled (EMB-2107)", async () => {+ setup({+ collectionId: null,+ hasRootAccess: true,+ collections: defaultCollections,+ disabled: true,+ });++ expect(await screen.findByText("id: null")).toBeInTheDocument();+ expect(+ fetchMock.callHistory.calls("path:/api/collection/root"),+ ).toHaveLength(0);+ });});});diff --git a/frontend/src/metabase/common/components/SaveQuestionForm/context.tsx b/frontend/src/metabase/common/components/SaveQuestionForm/context.tsxindex 967ab7420d3..ea302eaa685 100644--- a/frontend/src/metabase/common/components/SaveQuestionForm/context.tsx+++ b/frontend/src/metabase/common/components/SaveQuestionForm/context.tsx@@ -27,7 +27,11 @@ import type { CollectionId, DashboardId } from "metabase-types/api";import { SAVE_QUESTION_SCHEMA } from "./schema";import type { FormValues, SaveQuestionProps } from "./types";-import { getInitialValues, submitQuestion } from "./util";+import {+ getInitialValues,+ resolveCollectionReference,+ submitQuestion,+} from "./util";type SaveQuestionContextType = {question: Question;@@ -75,17 +79,28 @@ export const SaveQuestionProvider = ({}: PropsWithChildren<SaveQuestionProps>) => {const [originalQuestion] = useState(latestOriginalQuestion); // originalQuestion from props changes during saving+ const currentUser = useSelector(getUser);++ // Resolve the `"personal"` / `"tenant"` sentinels to the current user's real+ // collection id. Without this, `"tenant"` collapses to the root collection,+ // which tenant users cannot write to (EMB-2107).+ const targetCollection = resolveCollectionReference(+ userTargetCollection,+ currentUser,+ );+ const resolvedInitialCollectionId = resolveCollectionReference(+ userInitialCollectionId,+ currentUser,+ );++ // When a target collection is set the picker is hidden and the save is forced+ // into it, so the default-collection lookup is unused — skipping it also+ // avoids a `GET /api/collection/root` that tenant users get a 403 for.const defaultCollectionId = useGetDefaultCollectionId(originalQuestion?.collectionId(),+ { disabled: userTargetCollection != null },);- const currentUser = useSelector(getUser);-- const targetCollection =- userTargetCollection === "personal" && currentUser- ? currentUser.personal_collection_id- : userTargetCollection;-const { data: recentItems } = useListRecentsQuery({context: ["selections"],});@@ -135,7 +150,7 @@ export const SaveQuestionProvider = ({// over the recent-items logic. Used by the SDK so the picker opens on the// collection the user is browsing.const initialCollectionId =- userInitialCollectionId ??+ resolvedInitialCollectionId ??(!isAnalytics? lastSelectedDashboard?.parent_collection.id: defaultCollectionId) ??diff --git a/frontend/src/metabase/common/components/SaveQuestionForm/context.unit.spec.tsx b/frontend/src/metabase/common/components/SaveQuestionForm/context.unit.spec.tsxindex ff4c06930b1..c107fa738fc 100644--- a/frontend/src/metabase/common/components/SaveQuestionForm/context.unit.spec.tsx+++ b/frontend/src/metabase/common/components/SaveQuestionForm/context.unit.spec.tsx@@ -11,7 +11,7 @@ import { mockSettings } from "__support__/settings";import { render, renderWithProviders, screen, waitFor } from "__support__/ui";import { createMockState } from "metabase/redux/store/mocks";import Question from "metabase-lib/v1/Question";-import type { Card } from "metabase-types/api";+import type { Card, CollectionId, User } from "metabase-types/api";import {createMockCard,createMockCollection,@@ -27,7 +27,8 @@ import {} from "./context";const TestComponent = () => {- const { values, saveToDashboard } = useSaveQuestionContext();+ const { values, saveToDashboard, targetCollection } =+ useSaveQuestionContext();return (<div>{values.collection_id && (@@ -39,6 +40,9 @@ const TestComponent = () => {{saveToDashboard && (<div data-testid="saveToDashboard">{saveToDashboard}</div>)}+ {targetCollection != null && (+ <div data-testid="targetCollection">{targetCollection}</div>+ )}</div>);};@@ -47,6 +51,8 @@ interface setupProps {question?: Question;originalQuestion?: Question | null;initialCollectionId?: number | string | null;+ targetCollection?: CollectionId;+ currentUser?: User;}const setup = ({@@ -59,6 +65,8 @@ const setup = ({),originalQuestion = null,initialCollectionId,+ targetCollection,+ currentUser = createMockUser({ personal_collection_id: 1337 }),}: setupProps = {}) => {const onCreate = jest.fn();const onSave = jest.fn();@@ -84,14 +92,13 @@ const setup = ({onCreate={onCreate}onSave={onSave}initialCollectionId={initialCollectionId}+ targetCollection={targetCollection}><TestComponent /></SaveQuestionProvider>,{storeInitialState: createMockState({- currentUser: createMockUser({- personal_collection_id: 1337,- }),+ currentUser,settings,}),},@@ -175,6 +182,50 @@ describe("SaveQuestionContext", () => {expect(screen.queryByTestId("dashboardId")).not.toBeInTheDocument();});+ it('should resolve targetCollection="tenant" to the user\'s tenant collection (EMB-2107)', async () => {+ setupRecentViewsAndSelectionsEndpoints([], ["selections"]);++ setup({+ targetCollection: "tenant",+ currentUser: createMockUser({+ personal_collection_id: 1337,+ tenant_collection_id: 99,+ }),+ });++ expect(await screen.findByTestId("targetCollection")).toHaveTextContent(+ "99",+ );+ });++ it('should resolve targetCollection="personal" to the user\'s personal collection (EMB-2107)', async () => {+ setupRecentViewsAndSelectionsEndpoints([], ["selections"]);++ setup({ targetCollection: "personal" });++ expect(await screen.findByTestId("targetCollection")).toHaveTextContent(+ "1337",+ );+ });++ it('should resolve initialCollectionId="tenant" to the user\'s tenant collection (EMB-2107)', async () => {+ setupRecentViewsAndSelectionsEndpoints([], ["selections"]);++ setup({+ initialCollectionId: "tenant",+ currentUser: createMockUser({+ personal_collection_id: 1337,+ tenant_collection_id: 99,+ }),+ });++ await waitFor(async () =>+ expect(await screen.findByTestId("collectionId")).toHaveTextContent(+ "99",+ ),+ );+ });+it("should require saving to a specific dashboard if the question has a dashboard id already", async () => {setupRecentViewsAndSelectionsEndpoints([createMockRecentCollectionItem({ model: "dashboard", id: 10 })],diff --git a/frontend/src/metabase/common/components/SaveQuestionForm/util.ts b/frontend/src/metabase/common/components/SaveQuestionForm/util.tsindex 16ce538c5f6..f2b1665f092 100644--- a/frontend/src/metabase/common/components/SaveQuestionForm/util.ts+++ b/frontend/src/metabase/common/components/SaveQuestionForm/util.ts@@ -8,7 +8,7 @@ import {import { trackMetricCreated } from "metabase/common/data-studio/analytics";import { isNullOrUndefined } from "metabase/utils/types";import type Question from "metabase-lib/v1/Question";-import type { CardType } from "metabase-types/api";+import type { CardType, CollectionId, User } from "metabase-types/api";import type {CreateQuestionOptions,@@ -17,6 +17,46 @@ import type {UpdateQuestionOptions,} from "./types";+/**+ * Resolves the `"personal"` and `"tenant"` collection sentinels — accepted by+ * the SDK's `targetCollection` / `initialCollection` props — to the current+ * user's real collection id.+ *+ * `"tenant"` throws when the user is not a tenant member, so a mis-targeted save+ * fails loudly instead of silently landing in the root collection (EMB-2107).+ * This mirrors the resolvers already wired into the dashboard and+ * collection-browser paths (`embedding-sdk-bundle/store/collections.ts`).+ *+ * Real ids, `"root"`, and every other value pass through unchanged, as does any+ * value while the current user is still loading.+ */+export const resolveCollectionReference = <+ T extends CollectionId | null | undefined,+>(+ collectionId: T,+ currentUser: User | null | undefined,+): T | CollectionId => {+ if (!currentUser) {+ return collectionId;+ }++ if (collectionId === "personal") {+ return currentUser.personal_collection_id;+ }++ if (collectionId === "tenant") {+ if (!currentUser.tenant_collection_id) {+ throw new Error(+ "You must be a tenant member to access the tenant collection.",+ );+ }++ return currentUser.tenant_collection_id;+ }++ return collectionId;+};+const updateQuestion = async (options: UpdateQuestionOptions) => {const { originalQuestion, newQuestion, onSave } = options;diff --git a/frontend/src/metabase/common/components/SaveQuestionForm/util.unit.spec.ts b/frontend/src/metabase/common/components/SaveQuestionForm/util.unit.spec.tsindex bde89f9339c..70c793ff215 100644--- a/frontend/src/metabase/common/components/SaveQuestionForm/util.unit.spec.ts+++ b/frontend/src/metabase/common/components/SaveQuestionForm/util.unit.spec.ts@@ -1,5 +1,5 @@import Question from "metabase-lib/v1/Question";-import { createMockCard } from "metabase-types/api/mocks";+import { createMockCard, createMockUser } from "metabase-types/api/mocks";import type { CreateQuestionOptions } from "./types";import {@@ -7,6 +7,7 @@ import {getInitialValues,getPlaceholder,getTitle,+ resolveCollectionReference,} from "./util";const mockCard = createMockCard({@@ -137,6 +138,45 @@ describe("SaveQuestionForm utils", () => {});});+ describe("resolveCollectionReference", () => {+ const tenantUser = createMockUser({+ personal_collection_id: 10,+ tenant_collection_id: 20,+ });+ const nonTenantUser = createMockUser({+ personal_collection_id: 10,+ tenant_collection_id: null,+ });++ it('resolves "personal" to the user\'s personal collection id', () => {+ expect(resolveCollectionReference("personal", tenantUser)).toBe(10);+ });++ it('resolves "tenant" to the user\'s tenant collection id', () => {+ expect(resolveCollectionReference("tenant", tenantUser)).toBe(20);+ });++ it('throws for "tenant" when the user is not a tenant member', () => {+ expect(() => resolveCollectionReference("tenant", nonTenantUser)).toThrow(+ "You must be a tenant member to access the tenant collection.",+ );+ });++ it.each([5, "root", null, undefined] as const)(+ "passes %p through unchanged",+ (value) => {+ expect(resolveCollectionReference(value, tenantUser)).toBe(value);+ },+ );++ it("passes sentinels through unchanged while the user is not loaded", () => {+ expect(resolveCollectionReference("tenant", null)).toBe("tenant");+ expect(resolveCollectionReference("personal", undefined)).toBe(+ "personal",+ );+ });+ });+describe("getInitialValues", () => {it("should return correct initial values for a new question", () => {const result = getInitialValues(null, mockQuestion, 1, null);diff --git a/frontend/src/metabase/plugins/oss/collections.ts b/frontend/src/metabase/plugins/oss/collections.tsindex eed891381b9..70ca20e6833 100644--- a/frontend/src/metabase/plugins/oss/collections.ts+++ b/frontend/src/metabase/plugins/oss/collections.ts@@ -22,6 +22,7 @@ export type ItemWithCollection = { collection: CollectionEssentials };type GetCollectionIdType = (sourceCollectionId?: CollectionId | null,+ options?: { disabled?: boolean },) => CollectionId | null;export type CollectionAuthorityLevelDisplayProps = {