Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changeset/26971-dashboard-refused-tile-left-out.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
'@object-ui/plugin-dashboard': patch
---

fix(plugin-dashboard): a dashboard tile whose data the viewer may not read is left out, not drawn as a permission error

Clause-②: no
Metadata-protocol: none

A viewer who may not read the data behind one dataset tile used to see that tile draw "You don't have permission to view the data behind this widget" among tiles that answered. Outside design mode, `DashboardRenderer` now leaves such a tile out of the layout, frame and title included, once the server refuses its query as a read refusal (403 / `PERMISSION_DENIED`), and the remaining tiles reflow. The server's refusal stays the only verdict: every tile is still queried, and nothing is hidden on a guess.

- In design mode the tile stays and draws the no-access state, so an author can still see and select it.
- A failure that is not a read refusal keeps the tile and its error, as before.
- The editable grid layout (`DashboardGridLayout`) keeps the tile and its no-access state, unchanged.
17 changes: 17 additions & 0 deletions ui/packages/plugin-dashboard/src/DashboardRenderer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,20 @@ const DashboardRendererInner = forwardRef<HTMLDivElement, DashboardRendererProps
const hasExplicitColumns = schema.columns != null || inferredColumns !== 4;
const [isMobile, setIsMobile] = useState(false);

// objectstack#26971 — the dataset-bound tiles whose query the server
// refused as a READ refusal, keyed by the tile and the dataset it names.
// Outside design mode such a tile is left out of the layout, so a viewer
// who may not read the data behind it does not see a permission-error
// tile and the other tiles reflow (span-flow: array order is visual
// order). In design mode the tile stays and draws `DatasetWidget`'s
// no-access state (objectui#10899): the author must still see and select
// it. Nothing here guesses a permission: the server's 403 is the only
// verdict, reported by `DatasetWidget`'s `onForbidden`.
const [refusedTiles, setRefusedTiles] = useState<ReadonlySet<string>>(() => new Set());
const markTileRefused = useCallback((tileKey: string) => {
setRefusedTiles((prev) => (prev.has(tileKey) ? prev : new Set(prev).add(tileKey)));
}, []);

// Dashboard-level filters (framework#2501). Filter values live as
// dashboard variables — the outer DashboardRenderer mounts a
// PageVariablesProvider when the schema declares filters, so
Expand Down Expand Up @@ -1087,6 +1101,8 @@ const DashboardRendererInner = forwardRef<HTMLDivElement, DashboardRendererProps
const resolvedTitle = tWidgetTitle(widget);
const resolvedDescription = tWidgetDescription(widget);
const widgetKey = widget.id || resolvedTitle || `widget-${index}`;
const refusedTileKey = datasetWidget ? `${widgetKey}::${String(datasetWidget.dataset)}` : undefined;
if (!designMode && refusedTileKey && refusedTiles.has(refusedTileKey)) return null;
const isSelected = designMode && selectedWidgetId === widget.id;

const designModeProps = designMode ? {
Expand Down Expand Up @@ -1156,6 +1172,7 @@ const DashboardRendererInner = forwardRef<HTMLDivElement, DashboardRendererProps
? <DatasetWidget
widget={datasetWidget}
dataSource={dataSource}
onForbidden={refusedTileKey ? () => markTileRefused(refusedTileKey) : undefined}
heading={datasetMetric
? { title: resolvedTitle || '', description: resolvedDescription || undefined }
: undefined}
Expand Down
15 changes: 14 additions & 1 deletion ui/packages/plugin-dashboard/src/DatasetWidget.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -658,7 +658,19 @@ function MetricHeadingRow({ heading, label }: { heading: DatasetMetricHeading; l
);
}

export function DatasetWidget({ widget, dataSource, heading }: { widget: any; dataSource: unknown; heading?: DatasetMetricHeading }) {
export function DatasetWidget({ widget, dataSource, heading, onForbidden }: {
widget: any;
dataSource: unknown;
heading?: DatasetMetricHeading;
/**
* Called when the server refuses this widget's query as a READ refusal
* (`classifyLoadError(e) === 'forbidden'`). A host that can leave the tile
* out of its layout does so for a viewer (objectstack#26971); the widget
* itself still draws its no-access state (objectui#10899) for a host that
* keeps it on screen. The 403 stays the enforcement: this only reports it.
*/
onForbidden?: () => void;
}) {
const datasetName = String(widget?.dataset ?? '');
const dimensions: string[] = useMemo(() => (Array.isArray(widget?.dimensions) ? widget.dimensions.filter(Boolean) : []), [widget]);
const values: string[] = useMemo(() => (Array.isArray(widget?.values) ? widget.values.filter(Boolean) : []), [widget]);
Expand Down Expand Up @@ -951,6 +963,7 @@ export function DatasetWidget({ widget, dataSource, heading }: { widget: any; da
// agnostic `classifyLoadError`, never by matching the message text.
if (classifyLoadError(e) === 'forbidden') {
setState({ status: 'error', rows: [], forbidden: true });
onForbidden?.();
return;
}
setState({ status: 'error', rows: [], error: String((e as Error)?.message ?? e) });
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
/**
* ObjectUI
* Copyright (c) 2024-present ObjectStack Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

/**
* objectstack#26971 item 1 — a viewer who may not read the data behind a
* dataset tile does not see a permission-error tile, and the other tiles
* still render.
*
* Measured on HotCRM's Sales Performance dashboard: a viewer holding only a
* marketing permission set saw 14 tiles answer and the 15th draw "You don't
* have permission to view the data behind this widget" (its dataset query
* answered 403). Outside design mode `DashboardRenderer` now leaves that tile
* out of the layout, Card frame and title included, once the server refuses
* the query as a READ refusal (`DatasetWidget`'s `onForbidden`). The 403 stays
* the enforcement: nothing is hidden before the server answers.
*
* CONTROLS: in design mode the refused tile stays and draws the no-access
* state (objectui#10899), so the author can still see and select it; and a
* failure that is not a read refusal keeps the tile and its error alert.
*
* The refusal carries the two fields `@object-ui/data-objectstack`'s
* `AnalyticsForbiddenError` declares (`httpStatus: 403`,
* `code: 'PERMISSION_DENIED'`), as `DatasetWidget.forbiddenState-10899.test.tsx`
* builds it.
*/

import '@testing-library/jest-dom/vitest';
import * as React from 'react';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, cleanup, waitFor } from '@testing-library/react';
import type { DashboardComponentSchema } from '@object-ui/types';
// Module scope (AGENTS.md 测试纪律): the table tile renders onward through the
// registry this barrel populates.
import '@object-ui/components';
import { DashboardRenderer } from '../DashboardRenderer';

beforeEach(() => {
// The dimension-label metadata probe (`useDatasetDimensionMeta`) falls back
// to the global fetch; answer it locally so no case reaches the network.
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, status: 200, json: async () => ({}), text: async () => '{}' })));
});
afterEach(() => {
vi.unstubAllGlobals();
cleanup();
});

const dashboard = (...widgets: Record<string, unknown>[]): DashboardComponentSchema =>
({ type: 'dashboard', name: 'sales_performance', widgets }) as unknown as DashboardComponentSchema;

const READABLE = {
id: 'pipeline_by_stage',
type: 'table',
title: 'Pipeline by Stage',
dataset: 'opportunity_metrics',
dimensions: ['stage'],
values: ['deal_count'],
};
const REFUSED = {
id: 'quota_attainment',
type: 'table',
title: 'Quota Attainment by Rep',
dataset: 'forecast_metrics',
dimensions: ['owner'],
values: ['attainment'],
};

function readRefusal() {
return Object.assign(new Error('Analytics query refused: this user may not read the data behind dataset "forecast_metrics".'), {
name: 'AnalyticsForbiddenError',
httpStatus: 403,
code: 'PERMISSION_DENIED',
});
}

/** Answers every dataset but `forecast_metrics`, which it refuses with `failure()`. */
function source(failure: () => Error = readRefusal) {
return {
queryDataset: vi.fn(async (dataset: string) => {
if (dataset === 'forecast_metrics') throw failure();
return {
rows: [{ stage: 'Closed Won', deal_count: 7 }],
fields: [
{ name: 'stage', label: 'Stage', type: 'text' },
{ name: 'deal_count', label: 'Deals', type: 'number' },
],
object: 'opportunity',
};
}),
};
}

describe('DashboardRenderer — a tile whose data the viewer may not read is left out (objectstack#26971)', () => {
it('drops the refused tile, frame and title included, and keeps the readable one', async () => {
const src = source();
render(<DashboardRenderer schema={dashboard(READABLE, REFUSED)} dataSource={src} />);

// The readable tile answers.
expect(await screen.findByText('Closed Won')).toBeInTheDocument();
expect(screen.getByText('Pipeline by Stage')).toBeInTheDocument();
// The refused tile was asked (no client-side guess), and once the server
// refused it, nothing of it is left: no no-access state, no titled frame.
expect(src.queryDataset).toHaveBeenCalledWith('forecast_metrics', expect.anything());
await waitFor(() => expect(screen.queryByText('Quota Attainment by Rep')).toBeNull());
expect(screen.queryByTestId('dataset-widget-forbidden')).toBeNull();
expect(screen.queryByText(/don’t have (access|permission)/)).toBeNull();
});

it('CONTROL — in design mode the refused tile stays and draws the no-access state', async () => {
render(
<DashboardRenderer
schema={dashboard(READABLE, REFUSED)}
dataSource={source()}
designMode
onWidgetClick={() => {}}
/>,
);

expect(await screen.findByTestId('dataset-widget-forbidden')).toHaveTextContent('You don’t have access');
expect(screen.getByTestId('dashboard-preview-widget-quota_attainment')).toHaveTextContent('Quota Attainment by Rep');
expect(await screen.findByText('Closed Won')).toBeInTheDocument();
});

it('CONTROL — a failure that is not a read refusal keeps the tile and its error', async () => {
render(
<DashboardRenderer
schema={dashboard(READABLE, REFUSED)}
dataSource={source(() => new Error('Dataset query failed: 400 Bad Request — relationship not declared in include'))}
/>,
);

expect(await screen.findByText(/relationship not declared in include/)).toBeInTheDocument();
expect(screen.getByText('Quota Attainment by Rep')).toBeInTheDocument();
expect(await screen.findByText('Closed Won')).toBeInTheDocument();
});
});
Loading