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
10 changes: 10 additions & 0 deletions .changeset/36448-view-management-metadata-gate.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@object-ui/app-shell': patch
---

fix(console): offer view management only to an administrator who may write views

Clause-②: no
Metadata-protocol: none

Manage views, the view settings panel and Create View on a list page, the plugin view's own Create View and view actions, the data page's Save as view, and a saved shared view's rename and save in place were offered to every workspace administrator. Each of them writes `view` metadata, which the server refuses without the `manage_metadata` capability, so an organization administrator who lacks it was offered them and met a refusal on the first save. They now read the answer the Shared choice of a new view already reads (`mayManageViews`): an administrator whose session holds `manage_metadata`. A metadata administrator sees them as before; a reader's own views are unchanged.
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ function wire() {
});
}
let client: MetadataClient;
/** objectstack#36448 — the principal's `manage_metadata` answer, set per case. */
const viewer = vi.hoisted(() => ({ canAuthorMetadata: true }));

vi.mock('./metadata-admin/useMetadata', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
Expand All @@ -110,10 +112,14 @@ vi.mock('@object-ui/permissions', async (importOriginal) => {
useFieldPermissions: () => ({ canRead: () => true, canWrite: () => true, permissions: [] }),
};
});
vi.mock('../hooks/useCanAuthorMetadata', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useCanAuthorMetadata: () => viewer.canAuthorMetadata,
}));
vi.mock('@object-ui/auth', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useAuth: () => ({ user: { id: 'u1', name: 'Ada' }, activeOrganization: null }),
// "Save as view" and its dialog are admin-only.
// "Save as view" and its dialog are for an admin holding `manage_metadata`.
useWorkspaceAdminStatus: () => ({ isAdmin: true, isResolved: true }),
createAuthenticatedFetch: () => vi.fn(),
}));
Expand Down Expand Up @@ -177,6 +183,7 @@ async function saveAsView() {
beforeEach(() => {
cleanup();
puts.length = 0;
viewer.canAuthorMetadata = true;
client = new MetadataClient({ baseUrl: 'http://localhost', fetch: wire() as unknown as typeof fetch });
vi.spyOn(console, 'error').mockImplementation(() => {});
// objectstack#35624 — the create asks the package list where the app saves
Expand Down Expand Up @@ -221,3 +228,31 @@ describe('"Save as view" says a refused save, and never reports it as saved (obj
expect(screen.queryByTestId('create-view-dialog')).toBeNull();
});
});

describe('objectstack#36448 — "Save as view" is offered to an administrator holding manage_metadata', () => {
const mount = () => render(
<ExpressionProvider user={{ id: 'u1', name: 'Ada' }}>
<MemoryRouter initialEntries={[PAGE]}>
<Routes>
<Route
path="/apps/:appName/:objectName/data"
element={<ObjectDataPage dataSource={{ find: vi.fn(async () => ({ data: [] })) }} objects={[DEAL]} />}
/>
</Routes>
</MemoryRouter>
</ExpressionProvider>,
);

it('an organization administrator without it is not offered the save the server refuses', () => {
viewer.canAuthorMetadata = false;
mount();
expect(screen.queryByTestId('object-data-save-as-view')).toBeNull();
expect(screen.queryByTestId('object-data-save-as-view-menu-item')).toBeNull();
expect(screen.queryByTestId('create-view-dialog')).toBeNull();
});

it('with it, the entry is offered (control)', () => {
mount();
expect(screen.getByTestId('object-data-save-as-view')).toBeTruthy();
});
});
13 changes: 10 additions & 3 deletions ui/packages/app-shell/src/views/ObjectDataPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,8 @@ import {
} from '../preview/PreviewModeContext.js';
import { usePreviewListDataSource } from '../preview/unpublishedObjectReads.js';
import { useTenancyPosture } from '../hooks/useTenancyPosture.js';
import { useCanAuthorMetadata } from '../hooks/useCanAuthorMetadata.js';
import { mayManageViews } from './objectViewViewSharing.js';
import { servedObjectLabel, servedObjectPluralLabel } from '../hooks/servedObjectLabel.js';
import type { RowCrudPredicates } from '../utils/crudAffordances.js';
import { servesRecordRead } from '../utils/recordReadServed.js';
Expand Down Expand Up @@ -332,6 +334,11 @@ export function ObjectDataPage({ dataSource, objects }: any) {
const { canRead } = useFieldPermissions(objectName ?? '');
const { user, activeOrganization } = useAuth();
const { isAdmin } = useWorkspaceAdminStatus();
// objectstack#36448 — "Save as view" writes `view` metadata, which the
// server refuses without `manage_metadata`: offered to an administrator
// holding it (`mayManageViews`), never to one the save would answer 403.
const canAuthorMetadata = useCanAuthorMetadata();
const canSaveAsView = mayManageViews(isAdmin, canAuthorMetadata);
const metadataClient = useMetadataClient();
// ADR-0105: group posture appends a trailing organization_id attribution
// column to the auto-derived columns (reads span all the user's orgs).
Expand Down Expand Up @@ -908,7 +915,7 @@ export function ObjectDataPage({ dataSource, objects }: any) {
<span className="hidden sm:inline">{t('console.objectView.new')}</span>
</Button>
) : null;
const saveAsViewButton = isAdmin ? (
const saveAsViewButton = canSaveAsView ? (
<Button
size="sm"
variant="outline"
Expand Down Expand Up @@ -981,7 +988,7 @@ export function ObjectDataPage({ dataSource, objects }: any) {
foldedActions={
newButton && <>
{newButton}
{isAdmin && (
{canSaveAsView && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
Expand Down Expand Up @@ -1130,7 +1137,7 @@ export function ObjectDataPage({ dataSource, objects }: any) {
</NavigationOverlay>
)}

{isAdmin && (
{canSaveAsView && (
<CreateViewDialog
open={showCreateViewDialog}
onOpenChange={setShowCreateViewDialog}
Expand Down
35 changes: 21 additions & 14 deletions ui/packages/app-shell/src/views/ObjectView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ import { ListDraftActions } from './ListDraftActions.js';
import { viewSaveRefusalText } from './viewSaveRefusal.js';
import { listDraftPreference, listDraftScope, useListDraft } from './listDraftStore.js';
import { useObjectViewViewCrud, useRuntimeCreateApp } from './objectViewViewCrud.js';
import { mayShareViews, useViewSharing } from './objectViewViewSharing.js';
import { mayManageViews, useViewSharing } from './objectViewViewSharing.js';
import { useCanAuthorMetadata } from '../hooks/useCanAuthorMetadata.js';
import {
PERSONAL_VIEW_OBJECT,
Expand Down Expand Up @@ -284,6 +284,15 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
const { user, activeOrganization } = useAuth();
const { isAdmin } = useWorkspaceAdminStatus();
const perms = usePermissions();
// objectstack#36448 — who is offered the object's views to change: an
// administrator holding `manage_metadata`, the capability every `view`
// metadata write asks (`./objectViewViewSharing.ts`). Manage views, the
// view settings panel, Create View, a Shared new view, and a saved view's
// rename and save in place all read this one answer, so an organization
// administrator without it is offered none of the writes the server
// refuses with 403. `isAdmin` alone still gates what only reads.
const canAuthorMetadata = useCanAuthorMetadata();
const canManageViews = mayManageViews(isAdmin, canAuthorMetadata);

// Get Object Definition. The outer ObjectView wrapper already guards the
// missing-object case, so this always resolves while this component is
Expand Down Expand Up @@ -911,7 +920,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
? savedViews.find((sv: any) => viewRowId(sv) === activeView.id)
: undefined;
const activeViewPackageSaveRead = usePackageSaveRead(studioPackageId(activeSavedViewRow));
const canSaveToSharedView = !isEnvironmentList && !activeIsPersonal && !!activeView && isAdmin
const canSaveToSharedView = !isEnvironmentList && !activeIsPersonal && !!activeView && canManageViews
&& activeViewPackageSaveRead === 'takes' && isSavedViewId(savedViews, String(activeView.id));
const handleSaveToSharedView = async () => {
if (!activeView || !canSaveToSharedView) return;
Expand Down Expand Up @@ -1166,10 +1175,8 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
});

// objectstack#36409 — only an administrator holding the shared view's write
// capability creates a shared view, and it is published at once
// (`./objectViewViewSharing.ts`).
const canAuthorMetadata = useCanAuthorMetadata();
const canShareViews = mayShareViews(isAdmin, canAuthorMetadata);
// capability (`canManageViews`, above) creates a shared view, and it is
// published at once (`./objectViewViewSharing.ts`).
const sharingApp = useRuntimeCreateApp(t);
const viewSharing = useViewSharing({
objectName: objectDef.name,
Expand Down Expand Up @@ -1197,7 +1204,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
viewAccess,
activeViewId,
handleViewChange,
isAdmin,
canManageViews,
handleAddView,
setManageViewsOpen,
pinnedViewId,
Expand All @@ -1218,7 +1225,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
createShared: viewSharing.createShared,
clearSourceListState,
canCreatePersonal: canCreatePersonalView,
canCreateShared: canShareViews,
canCreateShared: canManageViews,
hasUnsavedConditions: listDraftParts.some((part) => part === 'filters' || part === 'sort'),
},
onRenamePersonalView: personalViewsReady && personalGrant('update')
Expand Down Expand Up @@ -1325,7 +1332,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
? (label: string) => handleRenamePersonalView(String(activeView.id), label)
// A read-only package's view is renamed too (objectstack#35974):
// `updateView` writes the label into its customization pair.
: activeView && isAdmin && savedViews.some((sv: any) => viewRowId(sv) === activeView.id)
: activeView && canManageViews && savedViews.some((sv: any) => viewRowId(sv) === activeView.id)
? async (label: string) => { await handleRenameView(String(activeView.id), label); return true; }
: undefined,
save: !isEnvironmentList && listDraftParts.length > 0 ? saveToThisView : undefined,
Expand All @@ -1350,7 +1357,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
activeView,
objectDef,
onEdit,
isAdmin,
canManageViews,
location,
navigate,
viewId,
Expand Down Expand Up @@ -1600,7 +1607,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
the server refused alike. Its Manage views opens the dialog
below. On a phone the same switcher leads the list's toolbar
row (objectstack#27058). */}
{isAdmin && views.length >= 1 && (
{canManageViews && views.length >= 1 && (
<ManageViewsDialog
open={manageViewsOpen}
onOpenChange={setManageViewsOpen}
Expand Down Expand Up @@ -1644,12 +1651,12 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
<div
data-testid="view-config-panel-wrapper"
className={`transition-[max-width,opacity] duration-300 ease-in-out overflow-hidden ${
showViewConfigPanel && isAdmin ? 'max-w-[280px] opacity-100' : 'max-w-0 opacity-0'
showViewConfigPanel && canManageViews ? 'max-w-[280px] opacity-100' : 'max-w-0 opacity-0'
}`}
>
<Suspense fallback={null}>
<ViewConfigPanel
open={showViewConfigPanel && isAdmin}
open={showViewConfigPanel && canManageViews}
onClose={() => { setShowViewConfigPanel(false); setViewConfigPanelMode('edit'); }}
mode={viewConfigPanelMode}
activeView={activeView}
Expand All @@ -1666,7 +1673,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
</div>
<Suspense fallback={null}>
<CreateViewDialog
open={showCreateViewDialog && isAdmin}
open={showCreateViewDialog && canManageViews}
onOpenChange={setShowCreateViewDialog}
existingLabels={views.map((v: any) => v.label).filter(Boolean)}
objectDef={objectDef}
Expand Down
Loading
Loading