You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by el...@apache.org on 2026/08/31 21:54:51 UTC
(superset) branch eschutho/sc-119327/group-by-dashboard-filter-allowlist created (now 2651ceaf379)
This is an automated email from the ASF dual-hosted git repository.
eschutho pushed a change to branch eschutho/sc-119327/group-by-dashboard-filter-allowlist
in repository https://gitbox.apache.org/repos/asf/superset.git
at 2651ceaf379 feat(dashboard): add column allowlist to Group By native filter [sc-119327]
This branch includes the following new commits:
new 2651ceaf379 feat(dashboard): add column allowlist to Group By native filter [sc-119327]
The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
(superset) 01/01: feat(dashboard): add column allowlist to Group By native filter [sc-119327]
Posted by el...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
eschutho pushed a commit to branch eschutho/sc-119327/group-by-dashboard-filter-allowlist
in repository https://gitbox.apache.org/repos/asf/superset.git
commit 2651ceaf379598eed49de644523d448115ba00a6
Author: Elizabeth Thompson <es...@gmail.com>
AuthorDate: Mon Aug 31 21:54:35 2026 +0000
feat(dashboard): add column allowlist to Group By native filter [sc-119327]
Let dashboard builders curate which columns viewers may group by in a
Dynamic Group By native filter (chart_customization_dynamic_groupby).
- Add a multi-select "Groupable columns" control to the filter's config
panel (reusing ColumnSelect in mode="multiple"), stored in the
customization's controlValues.columnsAllowlist.
- Respect the allowlist in the viewer (GroupByFilterCard): only allowed
columns are offered. An unset or empty allowlist means no restriction,
so existing filters behave exactly as before (backwards compatible).
- The allowlist rides along in controlValues, so it survives save/reload
and dashboard export/import with no backend changes.
- Clear the allowlist when the builder changes the dataset to avoid
stale, dataset-specific column entries.
- Add unit/RTL tests for the filtering helper, the viewer rendering, the
config-form control, and controlValues persistence.
Co-Authored-By: Claude Opus 4.8 <no...@anthropic.com>
---
.../FilterControls/GroupByFilterCard.test.tsx | 105 ++++++++++++++++-
.../FilterBar/FilterControls/GroupByFilterCard.tsx | 29 ++++-
.../FiltersConfigForm/FiltersConfigForm.tsx | 59 ++++++++++
.../GroupByColumnAllowlist.test.tsx | 124 +++++++++++++++++++++
.../transformers/customizationTransformer.test.ts | 25 +++++
5 files changed, 338 insertions(+), 4 deletions(-)
diff --git a/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/FilterControls/GroupByFilterCard.test.tsx b/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/FilterControls/GroupByFilterCard.test.tsx
index 3a155f7fece..762d04f3583 100644
--- a/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/FilterControls/GroupByFilterCard.test.tsx
+++ b/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/FilterControls/GroupByFilterCard.test.tsx
@@ -21,16 +21,23 @@ import {
type ChartCustomization,
} from '@superset-ui/core';
import { LabeledValue } from '@superset-ui/core/components';
-import { render, screen } from 'spec/helpers/testing-library';
+import { render, screen, userEvent } from 'spec/helpers/testing-library';
+import { cachedSupersetGet } from 'src/utils/cachedSupersetGet';
import GroupByFilterCard, {
+ applyColumnAllowlist,
createLabelSortComparator,
} from './GroupByFilterCard';
jest.mock('src/utils/cachedSupersetGet', () => ({
- // Never resolves, pinning the card in its column-loading state.
+ // Never resolves by default, pinning the card in its column-loading state.
+ // Individual tests override this with `mockImplementationOnce`.
cachedSupersetGet: jest.fn(() => new Promise(() => {})),
}));
+const mockedCachedSupersetGet = cachedSupersetGet as jest.MockedFunction<
+ typeof cachedSupersetGet
+>;
+
const apple: LabeledValue = { value: 'a', label: 'Apple' };
const banana: LabeledValue = { value: 'b', label: 'Banana' };
@@ -52,6 +59,33 @@ test('preserves source order when sortAscending is unset', () => {
expect(compare(banana, apple)).toBe(0);
});
+const columnOptions = [
+ { label: 'Country', value: 'country' },
+ { label: 'State', value: 'state' },
+ { label: 'City', value: 'city' },
+];
+
+test('returns all options when the allowlist is unset (backwards compatible)', () => {
+ expect(applyColumnAllowlist(columnOptions, undefined)).toEqual(columnOptions);
+});
+
+test('returns all options when the allowlist is empty (no restriction)', () => {
+ expect(applyColumnAllowlist(columnOptions, [])).toEqual(columnOptions);
+});
+
+test('keeps only allowlisted columns and preserves their order', () => {
+ expect(applyColumnAllowlist(columnOptions, ['city', 'country'])).toEqual([
+ { label: 'Country', value: 'country' },
+ { label: 'City', value: 'city' },
+ ]);
+});
+
+test('ignores allowlist entries that are not real columns', () => {
+ expect(
+ applyColumnAllowlist(columnOptions, ['state', 'does_not_exist']),
+ ).toEqual([{ label: 'State', value: 'state' }]);
+});
+
const groupByCustomization: ChartCustomization = {
id: 'groupby-1',
name: 'Group By',
@@ -63,6 +97,73 @@ const groupByCustomization: ChartCustomization = {
defaultDataMask: {},
};
+const datasetResponse = {
+ json: {
+ result: {
+ table_name: 'cleaned_sales_data',
+ columns: [
+ { column_name: 'country', verbose_name: 'Country', filterable: true },
+ { column_name: 'state', verbose_name: 'State', filterable: true },
+ { column_name: 'city', verbose_name: 'City', filterable: true },
+ ],
+ },
+ },
+};
+
+test('only offers allowlisted columns to viewers', async () => {
+ mockedCachedSupersetGet.mockImplementationOnce(
+ () =>
+ Promise.resolve(datasetResponse) as unknown as ReturnType<
+ typeof cachedSupersetGet
+ >,
+ );
+
+ render(
+ <GroupByFilterCard
+ customizationItem={{
+ ...groupByCustomization,
+ controlValues: { columnsAllowlist: ['country', 'city'] },
+ }}
+ />,
+ {
+ useRedux: true,
+ initialState: {
+ dataMask: {},
+ nativeFilters: { filters: {} },
+ },
+ },
+ );
+
+ userEvent.click(await screen.findByRole('combobox'));
+
+ expect(await screen.findByText('Country')).toBeInTheDocument();
+ expect(screen.getByText('City')).toBeInTheDocument();
+ expect(screen.queryByText('State')).not.toBeInTheDocument();
+});
+
+test('offers every groupable column when no allowlist is configured', async () => {
+ mockedCachedSupersetGet.mockImplementationOnce(
+ () =>
+ Promise.resolve(datasetResponse) as unknown as ReturnType<
+ typeof cachedSupersetGet
+ >,
+ );
+
+ render(<GroupByFilterCard customizationItem={groupByCustomization} />, {
+ useRedux: true,
+ initialState: {
+ dataMask: {},
+ nativeFilters: { filters: {} },
+ },
+ });
+
+ userEvent.click(await screen.findByRole('combobox'));
+
+ expect(await screen.findByText('Country')).toBeInTheDocument();
+ expect(screen.getByText('State')).toBeInTheDocument();
+ expect(screen.getByText('City')).toBeInTheDocument();
+});
+
test('renders the column-loading spinner small and muted', async () => {
render(<GroupByFilterCard customizationItem={groupByCustomization} />, {
useRedux: true,
diff --git a/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/FilterControls/GroupByFilterCard.tsx b/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/FilterControls/GroupByFilterCard.tsx
index 7363dfcab68..932b6b412bf 100644
--- a/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/FilterControls/GroupByFilterCard.tsx
+++ b/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/FilterControls/GroupByFilterCard.tsx
@@ -217,6 +217,21 @@ const DescriptionTooltip = ({ description }: { description: string }) => (
</ToolTipContainer>
);
+// Restrict the groupable column options to the builder-configured allowlist.
+// An unset or empty allowlist means "no restriction" so existing Group By
+// customizations (which never stored an allowlist) keep offering every
+// groupable column, preserving backwards compatibility.
+export const applyColumnAllowlist = <T extends { value: string }>(
+ options: T[],
+ allowlist?: string[] | null,
+): T[] => {
+ if (!Array.isArray(allowlist) || allowlist.length === 0) {
+ return options;
+ }
+ const allowed = new Set(allowlist);
+ return options.filter(option => allowed.has(option.value));
+};
+
// Sort display values by label: ascending when sortAscending is true, descending
// when false, and source order (no sort) when it is unset.
export const createLabelSortComparator =
@@ -355,6 +370,16 @@ const GroupByFilterCard: FC<GroupByFilterCardProps> = ({
[sortAscending],
);
+ // Builder-configured allowlist of columns viewers are allowed to group by.
+ const columnsAllowlist = customizationItem.controlValues?.columnsAllowlist as
+ | string[]
+ | undefined;
+
+ const allowedColumnOptions = useMemo(
+ () => applyColumnAllowlist(columnOptions, columnsAllowlist),
+ [columnOptions, columnsAllowlist],
+ );
+
const columnDisplayName = useMemo(() => {
if (customizationItem.name) {
return customizationItem.name;
@@ -599,7 +624,7 @@ const GroupByFilterCard: FC<GroupByFilterCardProps> = ({
placeholder={t('Search columns...')}
value={currentValue}
onChange={handleColumnChange}
- options={columnOptions}
+ options={allowedColumnOptions}
showSearch
mode={canSelectMultiple ? 'multiple' : undefined}
filterOption={(input, option) =>
@@ -629,7 +654,7 @@ const GroupByFilterCard: FC<GroupByFilterCardProps> = ({
placeholder={t('Search columns...')}
value={currentValue}
onChange={handleColumnChange}
- options={columnOptions}
+ options={allowedColumnOptions}
showSearch
mode={canSelectMultiple ? 'multiple' : undefined}
filterOption={(input, option) =>
diff --git a/superset-frontend/src/dashboard/components/nativeFilters/FiltersConfigModal/FiltersConfigForm/FiltersConfigForm.tsx b/superset-frontend/src/dashboard/components/nativeFilters/FiltersConfigModal/FiltersConfigForm/FiltersConfigForm.tsx
index 9c7ff4dbbcb..04879323956 100644
--- a/superset-frontend/src/dashboard/components/nativeFilters/FiltersConfigModal/FiltersConfigForm/FiltersConfigForm.tsx
+++ b/superset-frontend/src/dashboard/components/nativeFilters/FiltersConfigModal/FiltersConfigForm/FiltersConfigForm.tsx
@@ -93,6 +93,7 @@ import {
mergeExtraFormData,
} from 'src/dashboard/components/nativeFilters/utils';
import { DatasetSelectLabel } from 'src/features/datasets/DatasetSelectLabel';
+import { ChartCustomizationPlugins } from 'src/constants';
import {
ALLOW_DEPENDENCIES as TYPES_SUPPORT_DEPENDENCIES,
getFiltersConfigModalTestId,
@@ -390,6 +391,12 @@ const FiltersConfigForm = (
// @ts-expect-error
!!nativeFilterAndCustomizationItems[itemTypeField]?.value?.datasourceCount;
+ // The Dynamic Group By customization lets builders curate which columns
+ // viewers may group by via a column allowlist (stored in controlValues).
+ const isDynamicGroupBy =
+ isChartCustomization &&
+ itemTypeField === ChartCustomizationPlugins.DynamicGroupBy;
+
const getDatasetId = () => {
if (isChartCustomization) {
if (formFilter?.dataset?.value) {
@@ -1192,6 +1199,17 @@ const FiltersConfigForm = (
datasourceType: newDatasourceType,
defaultDataMask: null,
column: null,
+ // Columns are dataset-specific, so drop any
+ // configured Group By allowlist when the
+ // dataset changes to avoid stale entries.
+ ...(isDynamicGroupBy
+ ? {
+ controlValues: {
+ ...formFilter?.controlValues,
+ columnsAllowlist: undefined,
+ },
+ }
+ : {}),
});
}
forceUpdate();
@@ -1214,6 +1232,47 @@ const FiltersConfigForm = (
)}
</StyledRowContainer>
)}
+ {isDynamicGroupBy && hasDataset && showDataset && (
+ <StyledRowFormItem
+ expanded={expanded}
+ name={[
+ 'filters',
+ filterId,
+ 'controlValues',
+ 'columnsAllowlist',
+ ]}
+ initialValue={
+ customizationToEdit?.controlValues?.columnsAllowlist
+ }
+ label={
+ <>
+ <StyledLabel>{t('Groupable columns')}</StyledLabel>
+
+ <InfoTooltip
+ placement="top"
+ tooltip={t(
+ 'Columns viewers are allowed to group by. Leave empty to allow all groupable columns.',
+ )}
+ />
+ </>
+ }
+ data-test="groupby-columns-allowlist"
+ >
+ <ColumnSelect
+ mode="multiple"
+ allowClear
+ form={form}
+ filterId={filterId}
+ datasetId={datasetId}
+ datasourceType={datasourceType}
+ filterValues={(column: Column) => !!column?.filterable}
+ onChange={() => {
+ forceUpdate();
+ formChanged();
+ }}
+ />
+ </StyledRowFormItem>
+ )}
<Collapse
modalMode
defaultActiveKey={activeFilterPanelKeys}
diff --git a/superset-frontend/src/dashboard/components/nativeFilters/FiltersConfigModal/FiltersConfigForm/GroupByColumnAllowlist.test.tsx b/superset-frontend/src/dashboard/components/nativeFilters/FiltersConfigModal/FiltersConfigForm/GroupByColumnAllowlist.test.tsx
new file mode 100644
index 00000000000..ef6a714f661
--- /dev/null
+++ b/superset-frontend/src/dashboard/components/nativeFilters/FiltersConfigModal/FiltersConfigForm/GroupByColumnAllowlist.test.tsx
@@ -0,0 +1,124 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import {
+ Behavior,
+ ChartMetadata,
+ ChartCustomization,
+ ChartCustomizationType,
+ getChartMetadataRegistry,
+} from '@superset-ui/core';
+import { Form } from '@superset-ui/core/components';
+import fetchMock from 'fetch-mock';
+import { render, screen, waitFor } from 'spec/helpers/testing-library';
+import { ChartCustomizationPlugins } from 'src/constants';
+import FiltersConfigForm from './FiltersConfigForm';
+
+// Register a minimal Group By customization so the config form treats it as a
+// dataset-backed chart customization (datasourceCount > 0 -> hasDataset).
+getChartMetadataRegistry().registerValue(
+ ChartCustomizationPlugins.DynamicGroupBy,
+ new ChartMetadata({
+ name: 'Group By',
+ datasourceCount: 1,
+ behaviors: [Behavior.ChartCustomization],
+ thumbnail: '',
+ }),
+);
+
+fetchMock.get('glob:*/api/v1/dataset/1?*', {
+ result: {
+ columns: [
+ { column_name: 'country', is_dttm: false, filterable: true },
+ { column_name: 'state', is_dttm: false, filterable: true },
+ ],
+ },
+});
+
+const FILTER_ID = 'CHART_CUSTOMIZATION-groupby';
+
+const customizationToEdit: ChartCustomization = {
+ id: FILTER_ID,
+ name: 'Group By',
+ filterType: ChartCustomizationPlugins.DynamicGroupBy,
+ type: ChartCustomizationType.ChartCustomization,
+ targets: [{ datasetId: 1 }],
+ scope: { rootPath: ['ROOT_ID'], excluded: [] },
+ controlValues: { columnsAllowlist: ['country'] },
+ defaultDataMask: {},
+};
+
+const noop = () => {};
+
+function Harness() {
+ const [form] = Form.useForm();
+ return (
+ <Form
+ form={form}
+ initialValues={{
+ filters: {
+ [FILTER_ID]: {
+ filterType: ChartCustomizationPlugins.DynamicGroupBy,
+ dataset: { value: 1, label: 'sales' },
+ },
+ },
+ }}
+ >
+ <FiltersConfigForm
+ filterId={FILTER_ID}
+ itemType="chartCustomization"
+ form={form}
+ customizationToEdit={customizationToEdit}
+ expanded
+ removedFilters={{}}
+ restoreFilter={noop}
+ onModifyFilter={noop}
+ getAvailableFilters={() => []}
+ handleActiveFilterPanelChange={noop}
+ activeFilterPanelKeys={[]}
+ isActive
+ setErroredFilters={() => []}
+ validateDependencies={noop}
+ getDependencySuggestion={() => ''}
+ />
+ </Form>
+ );
+}
+
+afterAll(() => {
+ fetchMock.clearHistory().removeRoutes();
+});
+
+test('shows the Groupable columns allowlist control for the Group By customization', async () => {
+ render(<Harness />, {
+ useRedux: true,
+ initialState: {
+ dashboardInfo: { id: 1 },
+ datasources: {},
+ charts: {},
+ },
+ });
+
+ await waitFor(() =>
+ expect(screen.getByText('Groupable columns')).toBeInTheDocument(),
+ );
+
+ // The previously-configured allowlist column is rendered as a selected value,
+ // proving the control reads back its persisted controlValues.columnsAllowlist.
+ expect(await screen.findByText('country')).toBeInTheDocument();
+});
diff --git a/superset-frontend/src/dashboard/components/nativeFilters/FiltersConfigModal/transformers/customizationTransformer.test.ts b/superset-frontend/src/dashboard/components/nativeFilters/FiltersConfigModal/transformers/customizationTransformer.test.ts
index 33f9f4f61ab..0c911866580 100644
--- a/superset-frontend/src/dashboard/components/nativeFilters/FiltersConfigModal/transformers/customizationTransformer.test.ts
+++ b/superset-frontend/src/dashboard/components/nativeFilters/FiltersConfigModal/transformers/customizationTransformer.test.ts
@@ -73,6 +73,31 @@ test('serializes a dataset-backed customization into a full ChartCustomization',
expect(result).not.toHaveProperty('defaultValueQueriesData');
});
+test('persists the Group By column allowlist from controlValues on save', () => {
+ const formItem = {
+ ...baseFormItem,
+ name: 'Group by',
+ filterType: 'chart_customization_dynamic_groupby',
+ dataset: { value: 42, label: 'sales' },
+ controlValues: {
+ canSelectMultiple: true,
+ columnsAllowlist: ['region', 'country'],
+ },
+ } as unknown as ChartCustomizationsFormItem;
+
+ const result = transformCustomizationForSave(
+ 'CHART_CUSTOMIZATION-allowlist',
+ formItem,
+ ) as ChartCustomization;
+
+ // The allowlist rides along in controlValues so it survives save/reload and
+ // dashboard export/import with no extra plumbing.
+ expect(result.controlValues).toEqual({
+ canSelectMultiple: true,
+ columnsAllowlist: ['region', 'country'],
+ });
+});
+
test('passes an already-saved ChartCustomization through untouched', () => {
const saved: ChartCustomization = {
id: 'CHART_CUSTOMIZATION-ghi',