Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(gfs): r1-m5 preserve grant and share sources during role edits
M829b4b632a67
diff --git a/control-ui/components/GfsGrantPanel.tsx b/control-ui/components/GfsGrantPanel.tsxindex 7783c999c..f9a5ea4c7 100644--- a/control-ui/components/GfsGrantPanel.tsx+++ b/control-ui/components/GfsGrantPanel.tsx@@ -2,6 +2,7 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { RecordList, RecordListRow, RowActionMenu } from '@clerum/frontend-components'+import { planGfsInheritedRoleChange } from '@clerum/gfs-interaction-policy'import { useConfirmDialog } from '@components/ConfirmDialog'import { GfsInheritedAccessDialog } from '@components/GfsInheritedAccessDialog'import { GfsSubjectPicker } from '@components/GfsSubjectPicker'@@ -43,7 +44,8 @@ import type {GfsInheritedAccessSource,} from './GfsGrantPanel.types'import { buildGfsBulkSubjectOptions, toGfsBulkSubjectInputs } from './gfsGrantSubjectOptions'-import { loadGfsInheritedAccess, planInheritedRoleChange } from './gfsInheritedAccess'+import { loadGfsInheritedAccess } from './gfsInheritedAccess'+import { isEditorPermissions } from './gfsInheritedAccessMerge'/*** P4-S07 — Operator delegation panel for the Global File System. The operator@@ -147,6 +149,11 @@ export function GfsGrantPanel({ resource }: GfsGrantPanelProps): React.JSX.Elememode: 'change-role'nextRole: AccessRoleaffected: Array<{ source: GfsInheritedAccessSource; permissions: string[] }>+ /** Editor share-only sources excluded from writes (residual access). */+ residualSources: GfsInheritedAccessSource[]+ /** Grant-backed folders skipped because their own scope flag was+ * unknown — never written with a defaulted scope (R1-M5). */+ skippedFolderNames: string[]}| { row: GfsFileAccessRow; mode: 'remove' }| null@@ -175,7 +182,15 @@ export function GfsGrantPanel({ resource }: GfsGrantPanelProps): React.JSX.Elemeconst key = subjectKey(subject)let entry = bySubject.get(key)if (!entry) {- entry = { subject, permissions: [], inherit: false, grantId: null, shareIds: [] }+ entry = {+ subject,+ permissions: [],+ inherit: false,+ grantInherit: false,+ grantId: null,+ shareIds: [],+ shareEntries: [],+ }bySubject.set(key, entry)}return entry@@ -184,12 +199,22 @@ export function GfsGrantPanel({ resource }: GfsGrantPanelProps): React.JSX.Elemeconst entry = entryFor(grant.subject)entry.grantId = grant.identry.inherit = entry.inherit || grant.inherit+ // R1-M5: the GRANT row's own scope flag, never OR'd with share+ // coverage — a role write preserves exactly this.+ entry.grantInherit = grant.inheritentry.permissions = [...new Set([...entry.permissions, ...grant.permissions])]}for (const share of shareResult.items) {const entry = entryFor(share.subject)entry.shareIds.push(share.id)entry.inherit = entry.inherit || share.includeDescendants+ // R1-M5: each share row's own bits/scope survive the merge so role+ // edits can disclose residual access truthfully.+ entry.shareEntries.push({+ rowId: share.id,+ permissions: [...share.permissions],+ includeDescendants: share.includeDescendants,+ })entry.permissions = [...new Set([...entry.permissions, ...share.permissions])]}setExistingAccess([...bySubject.values()])@@ -509,7 +534,22 @@ export function GfsGrantPanel({ resource }: GfsGrantPanelProps): React.JSX.Eleme}}- async function updateAccessRole(item: GfsExistingAccessItem, nextRole: AccessRole) {+ async function updateAccessRole(+ item: GfsExistingAccessItem,+ nextRole: AccessRole,+ inheritedSources: GfsInheritedAccessSource[] = [],+ skippedFolderNames: string[] = []+ ) {+ // R1-M5: role editing never creates a grant. A share-only direct row has+ // no grant to rewrite and there is no share-update surface — refuse with+ // honest feedback instead of converting the share into a grant.+ if (item.grantId === null) {+ showToast(+ `${subjectLabel(item)}'s access comes from a sharing entry that can only be removed, not changed here.`,+ { tone: 'error' }+ )+ return+ }const permissions = rolePermissions(nextRole, hostOnlySubject(item.subject))setBusy(true)setError('')@@ -519,17 +559,49 @@ export function GfsGrantPanel({ resource }: GfsGrantPanelProps): React.JSX.ElemeresourceId: resource.resourceId,subject: item.subject,permissions,- inherit: item.inherit,+ // R1-M5: the grant row's OWN scope flag — share coverage is never+ // OR'd into a role write.+ inherit: item.grantInherit,})- // The upserted grant supersedes any legacy URI share for this subject;- // the server has no share-update surface, so consolidation happens here.- for (const shareId of item.shareIds) await deleteGfsShare(shareId)- showToast(- `${subjectLabel(item)} is now ${nextRole === 'editor' ? 'an Editor' : 'Read-only'}.`,- {- tone: 'success',- }- )+ // Shares survive role edits (R1-M5); when an editor-strength share+ // remains, the effective role claim must say so.+ const residualNames =+ nextRole === 'read'+ ? [+ ...new Set([+ ...inheritedSources+ .filter(source =>+ source.shareEntries.some(entry => isEditorPermissions(entry.permissions))+ )+ .map(source => source.name),+ ...(item.shareEntries.some(entry => isEditorPermissions(entry.permissions))+ ? [resource.name]+ : []),+ ]),+ ]+ : []+ const details: string[] = []+ if (skippedFolderNames.length > 0) {+ details.push(+ `Sharing details on ${joinFolderNames(skippedFolderNames)} could not be verified; existing access was kept.`+ )+ }+ if (residualNames.length > 0) {+ details.push(+ `Sharing entries on ${joinFolderNames(residualNames)} still grant Editor access.`+ )+ }+ if (details.length > 0) {+ showToast(+ `Changed grant access to ${nextRole === 'editor' ? 'Editor' : 'Read-only'} on ${resource.name}. ${details.join(' ')}`,+ { tone: skippedFolderNames.length > 0 ? 'error' : 'info' }+ )+ } else {+ showToast(+ `${subjectLabel(item)} is now ${nextRole === 'editor' ? 'an Editor' : 'Read-only'}.`,+ { tone: 'success' }+ )+ }await loadExistingAccess()} catch (caught) {setError(caught instanceof Error ? caught.message : 'Failed to update access')@@ -553,20 +625,56 @@ export function GfsGrantPanel({ resource }: GfsGrantPanelProps): React.JSX.Eleme* the access rows it can already read and lets the server accept or reject* each mutation. Per-folder affordance preflight is deferred to the backend* contract tracked separately from this PR.+ *+ * R1-M5: the shared split planner separates grant-backed sources (rewritten+ * with their OWN scope flag) from share-only sources (never converted into+ * grants, never deleted — residual access survives and is disclosed).*/async function prepareParentRoleChange(row: GfsFileAccessRow, nextRole: AccessRole) {const inherited = row.inheritedif (!inherited) returnif (nextRole === roleForPermissions(row.permissions)) return- const affected = planInheritedRoleChange(inherited, nextRole === 'editor')- if (affected.length === 0) {- if (row.direct) await updateAccessRole(row.direct, nextRole)+ const plan = planGfsInheritedRoleChange(inherited, nextRole === 'editor')+ // Unknown own-scope folders are never written (no `?? true` default);+ // they surface through the partial summary at confirm time.+ const writable = plan.grantSources.filter(+ (source): source is GfsInheritedAccessSource & { grantInherit: boolean } =>+ typeof source.grantInherit === 'boolean'+ )+ const skippedFolderNames = plan.grantSources+ .filter(source => typeof source.grantInherit !== 'boolean')+ .map(source => source.name)+ if (writable.length === 0) {+ if (row.direct && row.direct.grantId !== null) {+ await updateAccessRole(row.direct, nextRole, plan.shareOnlySources, skippedFolderNames)+ return+ }+ // Unknown scope and non-editable shares are different reasons to keep access.+ if (skippedFolderNames.length > 0) {+ showToast(+ `Sharing details on ${joinFolderNames(skippedFolderNames)} could not be verified; existing access was kept.`,+ { tone: 'error' }+ )+ return+ }+ // Nothing writable anywhere: explain why nothing changed.+ showToast(+ `${subjectLabel(row)} still has ${roleForPermissions(row.permissions) === 'editor' ? 'Editor' : 'Read-only'} access from sharing entries that can't be edited here.`,+ { tone: 'info' }+ )return}const permissions = rolePermissions(nextRole, hostOnlySubject(row.subject))- const updates = affected.map(source => ({ source, permissions }))- setParentUpdate({ row, mode: 'change-role', nextRole, affected: updates })+ const updates = writable.map(source => ({ source, permissions }))+ setParentUpdate({+ row,+ mode: 'change-role',+ nextRole,+ affected: updates,+ residualSources: plan.shareOnlySources,+ skippedFolderNames,+ })}/**@@ -657,9 +765,11 @@ export function GfsGrantPanel({ resource }: GfsGrantPanelProps): React.JSX.ElemeresourceId: source.resourceId,subject: row.subject,permissions,- inherit: true,+ // R1-M5: the folder grant's OWN scope flag (prepare guaranteed a+ // known boolean) — share coverage is never OR'd in and the+ // folder's share rows are never touched by a role change.+ inherit: source.grantInherit === true,})- for (const shareId of source.shareIds) await deleteGfsShare(shareId)updated += 1} catch (caught) {if (isAlreadyMissing(caught)) {@@ -673,7 +783,7 @@ export function GfsGrantPanel({ resource }: GfsGrantPanelProps): React.JSX.Elemereturn}}- if (row.direct) {+ if (row.direct && row.direct.grantId !== null) {try {const permissions = rolePermissions(request.nextRole, hostOnlySubject(row.subject))await putGfsGrant({@@ -681,9 +791,10 @@ export function GfsGrantPanel({ resource }: GfsGrantPanelProps): React.JSX.ElemeresourceId: resource.resourceId,subject: row.subject,permissions,- inherit: row.direct.inherit,+ // The direct GRANT's own scope flag; direct shares survive role+ // edits (R1-M5) and a share-only direct row never gains a grant.+ inherit: row.direct.grantInherit,})- for (const shareId of row.direct.shareIds) await deleteGfsShare(shareId)} catch (caught) {await failPartially(caught,@@ -692,12 +803,47 @@ export function GfsGrantPanel({ resource }: GfsGrantPanelProps): React.JSX.Elemereturn}}- showToast(- affectedNames.length > 0- ? `${subjectLabel(row)} is now ${request.nextRole === 'editor' ? 'an Editor' : 'Read-only'} on ${joinFolderNames(affectedNames)} and everything inside ${affectedNames.length > 1 ? 'them' : 'it'}.`- : `${subjectLabel(row)} is now ${request.nextRole === 'editor' ? 'an Editor' : 'Read-only'} on ${resource.name}.`,- { tone: 'success' }- )+ // Residual honesty (R1-M5): a downgrade never claims effective+ // Read-only while a surviving share entry still grants Editor.+ const residualNames =+ request.nextRole === 'read'+ ? [+ ...new Set([+ ...[...request.residualSources, ...affected.map(update => update.source)]+ .filter(source =>+ source.shareEntries.some(entry => isEditorPermissions(entry.permissions))+ )+ .map(source => source.name),+ ...(row.direct?.shareEntries.some(entry => isEditorPermissions(entry.permissions))+ ? [resource.name]+ : []),+ ]),+ ]+ : []+ const details: string[] = []+ if (request.skippedFolderNames.length > 0) {+ details.push(+ `Updated ${updated} of ${affected.length + request.skippedFolderNames.length} folders. Sharing details on ${joinFolderNames(request.skippedFolderNames)} could not be verified; existing access was kept.`+ )+ }+ if (residualNames.length > 0) {+ details.push(+ `Sharing entries on ${joinFolderNames(residualNames)} still grant Editor access.`+ )+ }+ if (details.length > 0) {+ showToast(+ `Changed grant access to ${request.nextRole === 'editor' ? 'Editor' : 'Read-only'} on ${affectedNames.length > 0 ? joinFolderNames(affectedNames) : resource.name}. ${details.join(' ')}`,+ { tone: request.skippedFolderNames.length > 0 ? 'error' : 'info' }+ )+ } else {+ showToast(+ affectedNames.length > 0+ ? `${subjectLabel(row)} is now ${request.nextRole === 'editor' ? 'an Editor' : 'Read-only'} on ${joinFolderNames(affectedNames)} and everything inside ${affectedNames.length > 1 ? 'them' : 'it'}.`+ : `${subjectLabel(row)} is now ${request.nextRole === 'editor' ? 'an Editor' : 'Read-only'} on ${resource.name}.`,+ { tone: 'success' }+ )+ }await reload()} finally {setBusy(false)@@ -812,6 +958,11 @@ export function GfsGrantPanel({ resource }: GfsGrantPanelProps): React.JSX.Elemeconst label = subjectLabel(row)const kind = subjectKind(row)const inherited = row.inherited !== null+ // R1-M5: a share-only direct row has no grant to rewrite and+ // no share-edit surface — the role control stays disabled+ // instead of offering a change that would create a grant.+ const shareOnlyDirect =+ !inherited && row.direct !== null && row.direct.grantId === nullreturn (<RecordListRowclassName="cu-gfs-existing-access__item"@@ -834,7 +985,7 @@ export function GfsGrantPanel({ resource }: GfsGrantPanelProps): React.JSX.Eleme<SelectionDropdownariaLabel={`Access role for ${label}`}className="cu-gfs-existing-access__role"- disabled={actionPending}+ disabled={actionPending || shareOnlyDirect}multiple={false}onChange={next => {if (!inherited) {diff --git a/control-ui/components/GfsGrantPanel.types.ts b/control-ui/components/GfsGrantPanel.types.tsindex 3141c4a57..b9e6be9ad 100644--- a/control-ui/components/GfsGrantPanel.types.ts+++ b/control-ui/components/GfsGrantPanel.types.ts@@ -35,17 +35,27 @@ export interface GfsGrantPanelProps {/*** One displayed access row per subject: the direct grant plus any legacy URI- * shares for that same subject, merged. The server has no share-update- * surface, so any role change (or revoke) consolidates the subject onto the- * single grant — the upsert preserves effective permissions (inherit ⊔- * includeDescendants) and the superseded share rows are deleted.+ * shares for that same subject, merged. Role changes rewrite only the grant+ * row and preserve its own scope flag; share rows survive role edits and are+ * removed only through explicit removal (R1-M5) — the server has no+ * share-update surface, so a share-only row is not role-editable and a role+ * change never creates a grant for it.*/export type GfsExistingAccessItem = {subject: GfsSubjectInputpermissions: string[]+ /** Union display flag (grant inherit ⊔ share includeDescendants) — display only. */inherit: boolean+ /** The direct GRANT row's own scope flag, exactly what a role write preserves. */+ grantInherit: booleangrantId: string | nullshareIds: string[]+ /** Every direct share row with its own bits and descendant scope (R1-M5). */+ shareEntries: Array<{+ rowId: string+ permissions: string[]+ includeDescendants: boolean+ }>}/**@@ -68,7 +78,9 @@ export type GfsFileAccessRow = {* (includeDescendants=true), consolidated per folder with the row ids a* confirmed edit mutates. Derivation keeps EVERY contributing folder* (R1-H1): a removal revokes all of them and a downgrade lowers each one- * above the target role.+ * above the target role. Per-row provenance (R1-M5): the grant's own bits and+ * scope flag and every share's own bits/scope are retained — a role change+ * rewrites only grant-backed rows and never deletes or converts shares.*/export type GfsInheritedAccessSource = {resourceId: string@@ -77,6 +89,16 @@ export type GfsInheritedAccessSource = {permissions: string[]grantId: string | nullshareIds: string[]+ /** Exact bits of this folder's grant row, when one contributes. */+ grantPermissions: string[] | null+ /** The grant row's own scope flag; null when no grant row exists. */+ grantInherit: boolean | null+ /** Every contributing share row with its own bits and descendant scope. */+ shareEntries: Array<{+ rowId: string+ permissions: string[]+ includeDescendants: boolean+ }>}/**diff --git a/control-ui/components/__tests__/GfsGrantPanel.bulk.test.tsx b/control-ui/components/__tests__/GfsGrantPanel.bulk.test.tsxindex 1c9f17431..afce01956 100644--- a/control-ui/components/__tests__/GfsGrantPanel.bulk.test.tsx+++ b/control-ui/components/__tests__/GfsGrantPanel.bulk.test.tsx@@ -306,7 +306,9 @@ describe('GfsGrantPanel bulk access', () => {// The descendant-coverage badge stays out of the row.expect(within(existing).queryByText('Includes contents')).toBeNull()- // Role change consolidates: the grant upsert supersedes the legacy share.+ // R1-M5: a role change rewrites only the grant row — with its OWN scope+ // flag (false here; the share's includeDescendants is never OR'd in) —+ // and the legacy share row survives.fireEvent.click(within(existing).getByRole('button', { name: 'Access role for Ada Lovelace' }))fireEvent.click(screen.getByRole('option', { name: 'Editor' }))@@ -316,15 +318,17 @@ describe('GfsGrantPanel bulk access', () => {resourceId: resource.resourceId,subject: userSubject,permissions: ['read', 'write', 'delete', 'manage_acl', 'share'],- inherit: true,+ inherit: false,}))- await waitFor(() =>- expect(mockDeleteGfsShare).toHaveBeenCalledWith('44444444-4444-4444-4444-444444444444')- )+ expect(mockDeleteGfsShare).not.toHaveBeenCalled()})- it('offers a toggleable role for a share-only principal and migrates it on change', async () => {+ // R1-M5 — a share-only principal has no grant to rewrite and no+ // share-update surface: the role control is disabled and a role change can+ // never migrate the share into a grant. Explicit grant creation through the+ // composer is the only path that creates grants.+ it('disables the role toggle for a share-only principal instead of migrating it', async () => {mockGetGfsShares.mockResolvedValue({items: [{@@ -348,21 +352,12 @@ describe('GfsGrantPanel bulk access', () => {expect(role).toHaveTextContent('Read')expect(within(existing).queryByText(/direct share|\buser\b/i)).toBeNull()+ // The dropdown is disabled: no selection, no migration, no deletion.+ expect(role.hasAttribute('disabled')).toBe(true)fireEvent.click(role)- fireEvent.click(screen.getByRole('option', { name: 'Editor' }))-- await waitFor(() =>- expect(mockPutGfsGrant).toHaveBeenCalledWith({- drive: 'main',- resourceId: resource.resourceId,- subject: userSubject,- permissions: ['read', 'write', 'delete', 'manage_acl', 'share'],- inherit: true,- })- )- await waitFor(() =>- expect(mockDeleteGfsShare).toHaveBeenCalledWith('44444444-4444-4444-4444-444444444444')- )+ expect(screen.queryByRole('option', { name: 'Editor' })).toBeNull()+ await waitFor(() => expect(mockPutGfsGrant).not.toHaveBeenCalled())+ expect(mockDeleteGfsShare).not.toHaveBeenCalled()})it('sorts access records by visible principal identity', async () => {diff --git a/control-ui/components/__tests__/GfsGrantPanel.inherited.test.tsx b/control-ui/components/__tests__/GfsGrantPanel.inherited.test.tsxindex 6c26dc2d5..d45e8e613 100644--- a/control-ui/components/__tests__/GfsGrantPanel.inherited.test.tsx+++ b/control-ui/components/__tests__/GfsGrantPanel.inherited.test.tsx@@ -355,6 +355,273 @@ describe('GfsGrantPanel inherited access', () => {).toContain('Editor')})+ // R1-M5 — a confirmed role change rewrites only the folder's GRANT (with+ // its own scope flag); the folder's share rows survive as residual access+ // and the outcome copy discloses the surviving Editor.+ it('keeps the folder’s share rows on a confirmed role change and discloses the residual Editor', async () => {+ const FOLDER_SHARE_ID = '88888888-8888-8888-8888-888888888888'+ mockGetGfsGrants.mockImplementation(async resourceId => {+ if (resourceId === FOLDER_ID) {+ return {+ items: [+ {+ id: FOLDER_GRANT_ID,+ drive: 'main',+ resourceId: FOLDER_ID,+ subject: miguel,+ permissions: ['read', 'write'],+ inherit: true,+ },+ ],+ }+ }+ return { items: [] }+ })+ mockGetGfsShares.mockImplementation(async resourceId => {+ if (resourceId === FOLDER_ID) {+ return {+ items: [+ {+ id: FOLDER_SHARE_ID,+ drive: 'main',+ resourceId: FOLDER_ID,+ subject: miguel,+ permissions: ['read', 'write'],+ includeDescendants: true,+ },+ ],+ }+ }+ return { items: [] }+ })+ renderPanel()+ const existing = await screen.findByRole('region', { name: 'People with access' })+ const miguelRow = await within(existing).findByTestId(miguelRowTestId)++ await chooseRole(miguelRow, 'Read')+ const dialog = await screen.findByRole('alertdialog')+ fireEvent.click(within(dialog).getByRole('button', { name: 'Update role' }))++ await waitFor(() =>+ expect(mockPutGfsGrant).toHaveBeenCalledWith({+ drive: 'main',+ resourceId: FOLDER_ID,+ subject: miguel,+ permissions: ['read', 'share'],+ inherit: true,+ })+ )+ // The role change NEVER deletes the folder's share row.+ expect(mockDeleteGfsShare).not.toHaveBeenCalledWith(FOLDER_SHARE_ID)+ // The honest outcome names the changed folder and discloses the residual.+ expect(+ await screen.findByText(+ 'Changed grant access to Read-only on team-docs. Sharing entries on team-docs still grant Editor access.'+ )+ ).toBeTruthy()+ })++ // R1-M5 — a share-only ancestor is never converted into a grant: nothing+ // is written, the confirmation never opens, and the user is told why.+ it('refuses a share-only ancestor role change without creating a grant', async () => {+ const FOLDER_SHARE_ID = '99999999-9999-9999-9999-999999999999'+ mockGetGfsGrants.mockImplementation(async () => ({ items: [] }))+ mockGetGfsShares.mockImplementation(async resourceId => {+ if (resourceId === FOLDER_ID) {+ return {+ items: [+ {+ id: FOLDER_SHARE_ID,+ drive: 'main',+ resourceId: FOLDER_ID,+ subject: miguel,+ permissions: ['read', 'write'],+ includeDescendants: true,+ },+ ],+ }+ }+ return { items: [] }+ })+ renderPanel()+ const existing = await screen.findByRole('region', { name: 'People with access' })+ const miguelRow = await within(existing).findByTestId(miguelRowTestId)++ await chooseRole(miguelRow, 'Read')++ expect(screen.queryByRole('alertdialog')).toBeNull()+ expect(mockPutGfsGrant).not.toHaveBeenCalled()+ expect(mockDeleteGfsShare).not.toHaveBeenCalled()+ expect(+ await screen.findByText(+ /still has Editor access from sharing entries that can't be edited here/+ )+ ).toBeTruthy()+ })++ it('discloses inherited Editor shares when only a direct grant can be changed', async () => {+ mockGetGfsGrants.mockImplementation(async resourceId => ({+ items:+ resourceId === FILE_ID+ ? [+ {+ id: FILE_GRANT_ID,+ drive: 'main',+ resourceId: FILE_ID,+ subject: miguel,+ permissions: ['read', 'write'],+ inherit: false,+ },+ ]+ : [],+ }))+ mockGetGfsShares.mockImplementation(async resourceId => ({+ items:+ resourceId === FOLDER_ID+ ? [+ {+ id: ROOT_SHARE_ID,+ drive: 'main',+ resourceId: FOLDER_ID,+ subject: miguel,+ permissions: ['read', 'write'],+ includeDescendants: true,+ },+ ]+ : [],+ }))+ renderPanel()+ const existing = await screen.findByRole('region', { name: 'People with access' })+ const row = await within(existing).findByTestId(miguelRowTestId)+ await chooseRole(row, 'Read')+ await waitFor(() =>+ expect(mockPutGfsGrant).toHaveBeenCalledWith({+ drive: 'main',+ resourceId: FILE_ID,+ subject: miguel,+ permissions: ['read', 'share'],+ inherit: false,+ })+ )+ expect(mockPutGfsGrant).toHaveBeenCalledTimes(1)+ expect(mockDeleteGfsShare).not.toHaveBeenCalled()+ expect(+ await screen.findByText(+ 'Changed grant access to Read-only on report.md. Sharing entries on team-docs still grant Editor access.'+ )+ ).toBeTruthy()+ })++ // R1-M5 — a share-only DIRECT row is not role-editable: the dropdown is+ // disabled (no grant would be created by a role change).+ it('disables the role dropdown for a share-only direct row', async () => {+ const FILE_SHARE_ID = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'+ mockGetGfsGrants.mockImplementation(async () => ({ items: [] }))+ mockGetGfsShares.mockImplementation(async resourceId => {+ if (resourceId === FILE_ID) {+ return {+ items: [+ {+ id: FILE_SHARE_ID,+ drive: 'main',+ resourceId: FILE_ID,+ subject: marcela,+ permissions: ['read', 'write'],+ includeDescendants: false,+ },+ ],+ }+ }+ return { items: [] }+ })+ renderPanel()++ const existing = await screen.findByRole('region', { name: 'People with access' })+ const marcelaRow = await within(existing).findByTestId(marcelaRowTestId)+ const trigger = within(marcelaRow).getByRole('button', { name: 'Access role for Marcela' })+ expect(trigger.hasAttribute('disabled')).toBe(true)+ // A disabled dropdown never opens, so no role selection — and no grant+ // write — can originate from a share-only direct row.+ fireEvent.click(trigger)+ expect(screen.queryByRole('option', { name: 'Editor' })).toBeNull()+ await waitFor(() => expect(mockPutGfsGrant).not.toHaveBeenCalled())+ })++ // R1-M5 — a direct role write preserves the GRANT row's own scope flag+ // (never the OR with share coverage) and keeps the share rows.+ it('preserves the direct grant’s own inherit flag and its share rows on a role change', async () => {+ const FILE_SHARE_ID = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb'+ mockGetGfsGrants.mockImplementation(async resourceId => {+ if (resourceId === FILE_ID) {+ return {+ items: [+ {+ id: FILE_GRANT_ID,+ drive: 'main',+ resourceId: FILE_ID,+ subject: marcela,+ permissions: ['read'],+ inherit: false,+ },+ ],+ }+ }+ if (resourceId === FOLDER_ID) {+ return {+ items: [+ {+ id: FOLDER_GRANT_ID,+ drive: 'main',+ resourceId: FOLDER_ID,+ subject: miguel,+ permissions: ['read', 'write'],+ inherit: true,+ },+ ],+ }+ }+ return { items: [] }+ })+ mockGetGfsShares.mockImplementation(async resourceId => {+ if (resourceId === FILE_ID) {+ return {+ items: [+ {+ id: FILE_SHARE_ID,+ drive: 'main',+ resourceId: FILE_ID,+ subject: marcela,+ permissions: ['read'],+ includeDescendants: true,+ },+ ],+ }+ }+ return { items: [] }+ })+ renderPanel()++ const existing = await screen.findByRole('region', { name: 'People with access' })+ const marcelaRow = within(existing)+ .getAllByTestId(marcelaRowTestId)+ .find(row => within(row).queryByText('Marcela') !== null)+ await chooseRole(marcelaRow as HTMLElement, 'Editor')++ // Direct row: no confirmation modal, the file grant is updated directly —+ // with the grant's OWN inherit flag (false), not the OR'd union.+ expect(screen.queryByRole('alertdialog')).toBeNull()+ await waitFor(() =>+ expect(mockPutGfsGrant).toHaveBeenCalledWith({+ drive: 'main',+ resourceId: FILE_ID,+ subject: marcela,+ permissions: ['read', 'write', 'delete', 'manage_acl', 'share'],+ inherit: false,+ })+ )+ expect(mockDeleteGfsShare).not.toHaveBeenCalled()+ })+it('removes an inherited member from the parent folder after confirmation', async () => {renderPanel()const existing = await screen.findByRole('region', { name: 'People with access' })diff --git a/control-ui/components/__tests__/gfsInheritedAccessMerge.prop.test.ts b/control-ui/components/__tests__/gfsInheritedAccessMerge.prop.test.tsindex 5005149d7..5952c1733 100644--- a/control-ui/components/__tests__/gfsInheritedAccessMerge.prop.test.ts+++ b/control-ui/components/__tests__/gfsInheritedAccessMerge.prop.test.ts@@ -247,4 +247,58 @@ describe('gfsInheritedAccessMerge properties', () => {{ numRuns: 300 })})++ // R1-M5 — the adapter projection PRESERVES per-row provenance: a+ // grant-backed folder keeps the grant's own bits and scope flag, every+ // share keeps its own row id/bits/scope, and re-folding a projected item+ // (provenance-projected input) keeps them stable.+ it('keeps each grant and share row’s own provenance through the projection', () => {+ fc.assert(+ fc.property(+ subjectArb,+ permissionsArb,+ permissionsArb,+ distinctFoldersArb,+ (subject, grantBits, shareBits, folders) => {+ const folder = folders[0]!+ const grantId = 'grant-row'+ const shareId = 'share-row'+ const item = mergeInheritedAccessItem(+ null,+ { subject, permissions: grantBits, grantId, shareIds: [] },+ folder+ )+ const withShare = mergeInheritedAccessItem(+ item,+ { subject, permissions: shareBits, grantId: null, shareIds: [shareId] },+ folder+ )+ const source = withShare.sources.find(entry => entry.resourceId === folder.resourceId)+ expect(source).toBeTruthy()+ // The grant row's OWN bits and scope flag survive (the walker+ // pre-filters inheriting grants, so inherit=true here).+ expect(source?.grantId).toBe(grantId)+ expect(source?.grantPermissions).toEqual(grantBits)+ expect(source?.grantInherit).toBe(true)+ // The share row keeps its own identity and bits — never OR'd into+ // the grant's scope.+ expect(source?.shareIds).toEqual([shareId])+ expect(source?.shareEntries).toHaveLength(1)+ expect(source?.shareEntries[0]).toEqual({+ rowId: shareId,+ permissions: shareBits,+ includeDescendants: true,+ })+ // Re-folding the projected item is stable (idempotent projection).+ const refolded = mergeInheritedAccessItem(+ withShare,+ { subject, permissions: grantBits, grantId, shareIds: [] },+ folder+ )+ expect(refolded).toEqual(withShare)+ }+ ),+ { numRuns: 300 }+ )+ })})diff --git a/control-ui/components/gfsInheritedAccessMerge.ts b/control-ui/components/gfsInheritedAccessMerge.tsindex 7eb3c5332..2e63732bf 100644--- a/control-ui/components/gfsInheritedAccessMerge.ts+++ b/control-ui/components/gfsInheritedAccessMerge.ts@@ -84,10 +84,9 @@ export function planInheritedRoleChange(/*** Folds one inheriting row into a subject's derived access item (creating it* on first sight) through the shared pure core, then projects the result back- * to the app's legacy-exact source shape. The policy core carries richer- * per-row provenance (grant bits/scope flag, share entries) for the upcoming- * scoped per-source edit work; this adapter exposes exactly the fields the- * app consumes today, so importers and tests observe byte-identical items.+ * to the app's source shape INCLUDING the policy's per-row provenance+ * (R1-M5: grant bits/scope flag and share entries survive the projection so+ * role edits can preserve each row's own scope and never touch shares).*/export function mergeInheritedAccessItem(current: GfsInheritedAccessItem | null,@@ -139,7 +138,7 @@ export function mergeInheritedAccessItem(return toAppInheritedAccessItem(folded)}-/** Project a policy item onto the app's legacy-exact item/source shape. */+/** Project a policy item onto the app item/source shape (provenance kept, R1-M5). */function toAppInheritedAccessItem(item: PolicyInheritedAccessItem | null): GfsInheritedAccessItem {return {subject: item?.subject ?? { type: 'user' },@@ -151,6 +150,14 @@ function toAppInheritedAccessItem(item: PolicyInheritedAccessItem | null): GfsInpermissions: [...source.permissions],grantId: source.grantId,shareIds: [...source.shareIds],+ grantPermissions:+ source.grantPermissions === null ? null : [...(source.grantPermissions ?? [])],+ grantInherit: source.grantInherit ?? null,+ shareEntries: (source.shareEntries ?? []).map(entry => ({+ rowId: entry.rowId,+ permissions: [...entry.permissions],+ includeDescendants: entry.includeDescendants,+ })),})),} as GfsInheritedAccessItem}diff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex 15c63a871..c8e6c55d0 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.735",+ "version": "0.1.736","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.735",+ "version": "0.1.736","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/frontend-components": "file:../packages/frontend-components",diff --git a/control-ui/package.json b/control-ui/package.jsonindex aedbdfe14..e0dec5632 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.735",+ "version": "0.1.736","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",diff --git a/desktop-app/ui/src/gfs/__tests__/inheritedAccess.test.ts b/desktop-app/ui/src/gfs/__tests__/inheritedAccess.test.tsindex adcb958d2..3ed5472fd 100644--- a/desktop-app/ui/src/gfs/__tests__/inheritedAccess.test.ts+++ b/desktop-app/ui/src/gfs/__tests__/inheritedAccess.test.ts@@ -122,6 +122,9 @@ describe('deriveGfsInheritedAccess', () => {permissions: ['read', 'write'],grantId: 'g1',shareIds: [],+ grantPermissions: ['read', 'write'],+ grantInherit: true,+ shareEntries: [],},],},@@ -137,6 +140,9 @@ describe('deriveGfsInheritedAccess', () => {permissions: ['read'],grantId: null,shareIds: ['s1'],+ grantPermissions: null,+ grantInherit: null,+ shareEntries: [{ rowId: 's1', permissions: ['read'], includeDescendants: true }],},],},@@ -192,6 +198,9 @@ describe('deriveGfsInheritedAccess', () => {permissions: ['read', 'write'],grantId: 'g1',shareIds: [],+ grantPermissions: ['read', 'write'],+ grantInherit: true,+ shareEntries: [],},],},@@ -265,6 +274,9 @@ describe('deriveGfsInheritedAccess', () => {permissions: ['read'],grantId: null,shareIds: ['s1'],+ grantPermissions: null,+ grantInherit: null,+ shareEntries: [{ rowId: 's1', permissions: ['read'], includeDescendants: true }],},],},@@ -279,6 +291,9 @@ describe('deriveGfsInheritedAccess', () => {permissions: ['read'],grantId: 'g-root',shareIds: [],+ grantPermissions: ['read'],+ grantInherit: true,+ shareEntries: [],},],},@@ -333,6 +348,9 @@ describe('deriveGfsInheritedAccess', () => {permissions: ['read'],grantId: null,shareIds: ['s1'],+ grantPermissions: null,+ grantInherit: null,+ shareEntries: [{ rowId: 's1', permissions: ['read'], includeDescendants: true }],},],},@@ -505,6 +523,9 @@ describe('deriveGfsInheritedAccess', () => {permissions: ['read', 'write'],grantId: `g-${FOLDER_ID}`,shareIds: [],+ grantPermissions: ['read', 'write'],+ grantInherit: true,+ shareEntries: [],},{resourceId: ROOT_ID,@@ -512,6 +533,9 @@ describe('deriveGfsInheritedAccess', () => {permissions: ['read', 'share'],grantId: `g-${ROOT_ID}`,shareIds: [],+ grantPermissions: ['read', 'share'],+ grantInherit: true,+ shareEntries: [],},])})@@ -569,6 +593,9 @@ describe('deriveGfsInheritedAccess', () => {permissions: ['read', 'write'],grantId: 'g1',shareIds: ['s1'],+ grantPermissions: ['read', 'write'],+ grantInherit: true,+ shareEntries: [{ rowId: 's1', permissions: ['read'], includeDescendants: true }],},])})diff --git a/desktop-app/ui/src/gfs/__tests__/inheritedAccessMerge.prop.test.ts b/desktop-app/ui/src/gfs/__tests__/inheritedAccessMerge.prop.test.tsindex 7bce6d577..d173785d7 100644--- a/desktop-app/ui/src/gfs/__tests__/inheritedAccessMerge.prop.test.ts+++ b/desktop-app/ui/src/gfs/__tests__/inheritedAccessMerge.prop.test.ts@@ -248,4 +248,58 @@ describe('inheritedAccessMerge properties', () => {{ numRuns: 300 })})++ // R1-M5 — the adapter projection PRESERVES per-row provenance: a+ // grant-backed folder keeps the grant's own bits and scope flag, every+ // share keeps its own row id/bits/scope, and re-folding a projected item+ // (provenance-projected input) keeps them stable.+ it('keeps each grant and share row’s own provenance through the projection', () => {+ fc.assert(+ fc.property(+ subjectArb,+ permissionsArb,+ permissionsArb,+ distinctFoldersArb,+ (subject, grantBits, shareBits, folders) => {+ const folder = folders[0]!+ const grantId = 'grant-row'+ const shareId = 'share-row'+ const item = mergeInheritedAccessItem(+ null,+ { subject, permissions: grantBits, grantId, shareIds: [] },+ folder+ )+ const withShare = mergeInheritedAccessItem(+ item,+ { subject, permissions: shareBits, grantId: null, shareIds: [shareId] },+ folder+ )+ const source = withShare.sources.find(entry => entry.resourceId === folder.resourceId)+ expect(source).toBeTruthy()+ // The grant row's OWN bits and scope flag survive (the walker+ // pre-filters inheriting grants, so inherit=true here).+ expect(source?.grantId).toBe(grantId)+ expect(source?.grantPermissions).toEqual(grantBits)+ expect(source?.grantInherit).toBe(true)+ // The share row keeps its own identity and bits — never OR'd into+ // the grant's scope.+ expect(source?.shareIds).toEqual([shareId])+ expect(source?.shareEntries).toHaveLength(1)+ expect(source?.shareEntries[0]).toEqual({+ rowId: shareId,+ permissions: shareBits,+ includeDescendants: true,+ })+ // Re-folding the projected item is stable (idempotent projection).+ const refolded = mergeInheritedAccessItem(+ withShare,+ { subject, permissions: grantBits, grantId, shareIds: [] },+ folder+ )+ expect(refolded).toEqual(withShare)+ }+ ),+ { numRuns: 300 }+ )+ })})diff --git a/desktop-app/ui/src/gfs/delegation.types.ts b/desktop-app/ui/src/gfs/delegation.types.tsindex aa9da3017..c18b1745f 100644--- a/desktop-app/ui/src/gfs/delegation.types.ts+++ b/desktop-app/ui/src/gfs/delegation.types.ts@@ -69,7 +69,9 @@ export interface GfsShareListItem {* (includeDescendants=true), consolidated per folder with the row ids a* confirmed edit mutates. Derivation keeps EVERY contributing folder* (R1-H1): a removal revokes all of them and a downgrade lowers each one- * above the target role.+ * above the target role. Per-row provenance (R1-M5): the grant's own bits and+ * scope flag and every share's own bits/scope are retained — a role change+ * rewrites only grant-backed rows and never deletes or converts shares.*/export interface GfsInheritedAccessSource {resourceId: string@@ -78,6 +80,16 @@ export interface GfsInheritedAccessSource {permissions: string[]grantId: string | nullshareIds: string[]+ /** Exact bits of this folder's grant row, when one contributes. */+ grantPermissions: string[] | null+ /** The grant row's own scope flag; null when no grant row exists. */+ grantInherit: boolean | null+ /** Every contributing share row with its own bits and descendant scope. */+ shareEntries: Array<{+ rowId: string+ permissions: string[]+ includeDescendants: boolean+ }>}/**diff --git a/desktop-app/ui/src/gfs/inheritedAccessMerge.ts b/desktop-app/ui/src/gfs/inheritedAccessMerge.tsindex 8c705c188..32da5821c 100644--- a/desktop-app/ui/src/gfs/inheritedAccessMerge.ts+++ b/desktop-app/ui/src/gfs/inheritedAccessMerge.ts@@ -84,10 +84,9 @@ export function planInheritedRoleChange(/*** Folds one inheriting row into a subject's derived access item (creating it* on first sight) through the shared pure core, then projects the result back- * to the app's legacy-exact source shape. The policy core carries richer- * per-row provenance (grant bits/scope flag, share entries) for the upcoming- * scoped per-source edit work; this adapter exposes exactly the fields the- * app consumes today, so importers and tests observe byte-identical items.+ * to the app's source shape INCLUDING the policy's per-row provenance+ * (R1-M5: grant bits/scope flag and share entries survive the projection so+ * role edits can preserve each row's own scope and never touch shares).*/export function mergeInheritedAccessItem(current: GfsInheritedAccessItem | null,@@ -139,7 +138,7 @@ export function mergeInheritedAccessItem(return toAppInheritedAccessItem(folded)}-/** Project a policy item onto the app's legacy-exact item/source shape. */+/** Project a policy item onto the app item/source shape (provenance kept, R1-M5). */function toAppInheritedAccessItem(item: PolicyInheritedAccessItem | null): GfsInheritedAccessItem {return {subject: item?.subject ?? { type: 'user' },@@ -151,6 +150,14 @@ function toAppInheritedAccessItem(item: PolicyInheritedAccessItem | null): GfsInpermissions: [...source.permissions],grantId: source.grantId,shareIds: [...source.shareIds],+ grantPermissions:+ source.grantPermissions === null ? null : [...(source.grantPermissions ?? [])],+ grantInherit: source.grantInherit ?? null,+ shareEntries: (source.shareEntries ?? []).map(entry => ({+ rowId: entry.rowId,+ permissions: [...entry.permissions],+ includeDescendants: entry.includeDescendants,+ })),})),} as GfsInheritedAccessItem}diff --git a/desktop-app/ui/src/pages/FilesPage.tsx b/desktop-app/ui/src/pages/FilesPage.tsxindex 9f35c9b46..947a20ee8 100644--- a/desktop-app/ui/src/pages/FilesPage.tsx+++ b/desktop-app/ui/src/pages/FilesPage.tsx@@ -15,6 +15,7 @@ import {gfsUploadNameRetryDecision,normalizeGfsResourceName,} from '@clerum/gfs-interaction-policy'+import { isEditorGfsPermissions, planGfsInheritedRoleChange } from '@clerum/gfs-interaction-policy'import { Badge, Button, EmptyState, IconButton, StatusBanner, TextInput } from '@components/Common'import { ConfirmDialog } from '@components/ConfirmDialog'import { GfsFileIcon } from '@components/GfsFileIcon'@@ -71,7 +72,6 @@ import { useGfsDragAdjudication } from '@/gfs/dragAdjudication'import type { GfsDragSource, GfsDropRejection, GfsDropVerdict } from '@/gfs/dragSession'import { useGfsDragSession } from '@/gfs/dragSession'import { GfsFilePicker } from '@/gfs/filePicker'-import { planInheritedRoleChange } from '@/gfs/inheritedAccess'import { commitGfsMove, suggestNumberedMoveName } from '@/gfs/moveCommit'import type { MoveCommitOutcome } from '@/gfs/moveCommit'import { GfsMoveConfirmDialog } from '@/gfs/moveConfirmDialog'@@ -273,8 +273,11 @@ export function FilesPage({const [updatingAccessRole, setUpdatingAccessRole] = useState(false)// Pending parent-folder confirmation (role change or removal) for a member// whose file access is inherited from ancestor folders. change-role carries- // the R1-H1 plan's affected folders, each with the bits the pre-flight- // validated on that folder itself.+ // the split plan's affected grant-backed folders (R1-M5: each rewritten+ // with its OWN scope flag; share rows never touched), each with the bits+ // the pre-flight validated on that folder itself, plus the share-only+ // editor sources (residual access) and any unknown-scope folders skipped+ // rather than written with a defaulted scope.const [parentUpdate, setParentUpdate] = useState<| {row: GfsMergedAccessRow@@ -282,6 +285,8 @@ export function FilesPage({mode: 'change-role'nextRole: GfsAccessRoleupdates: Array<{ source: GfsInheritedAccessSource; bits: string[] }>+ residualSources: GfsInheritedAccessSource[]+ skippedFolderNames: string[]}| { row: GfsMergedAccessRow; label: string; mode: 'remove' }| null@@ -680,16 +685,51 @@ export function FilesPage({// comparing it against the inherited-only floor instead would open the// parent-update modal and escalate the parent folder for a non-change.if (role === roleForAccessPermissions(row.permissions)) return- // R1-H1 plan: downgrade lowers every folder above the target; upgrade- // raises the single strongest folder; same-role selection touches none.- const affected = planInheritedRoleChange(inherited, role === 'editor')- if (affected.length === 0 && !row.grant && row.shares.length === 0) return+ // R1-M5 split plan: grant-backed folders are rewritten with their OWN+ // scope flag; share-only sources are never converted into grants or+ // deleted (residual access survives and is disclosed). Folders whose own+ // scope flag is unknown are never written with a defaulted scope.+ const plan = planGfsInheritedRoleChange(inherited, role === 'editor')+ const writable = plan.grantSources.filter(source => typeof source.grantInherit === 'boolean')+ const skippedFolderNames = plan.grantSources+ .filter(source => typeof source.grantInherit !== 'boolean')+ .map(source => source.name)+ if (writable.length === 0) {+ if (row.grant) {+ // Direct-grant-only alignment keeps the existing confirmation path.+ setParentUpdate({+ row,+ label,+ mode: 'change-role',+ nextRole: role,+ updates: [],+ residualSources: plan.shareOnlySources,+ skippedFolderNames,+ })+ return+ }+ if (skippedFolderNames.length > 0) {+ pushToast?.(+ `Sharing details on ${joinFolderNames(skippedFolderNames)} could not be verified; existing access was kept.`,+ 'error'+ )+ return+ }+ // Nothing writable anywhere: explain the surviving share access.+ if (plan.shareOnlySources.length > 0 || row.shares.length > 0) {+ pushToast?.(+ `${label} still has ${roleForAccessPermissions(row.permissions) === 'editor' ? 'Editor' : 'Read-only'} access from sharing entries that can't be edited here.`,+ 'info'+ )+ }+ return+ }// Pre-flight: every affected folder's grant is judged by THAT folder's// own grantable bits, never by the open file's affordances (which may be// missing or narrower). A role a folder cannot grant fails loudly here —// the confirmation never opens with a promise it cannot keep.const updates: Array<{ source: GfsInheritedAccessSource; bits: string[] }> = []- for (const source of affected) {+ for (const source of writable) {let folderAffordances: { canDelegate: boolean; grantableBits: string[] }try {folderAffordances = await window.clerum.gfs.affordances(source.resourceId, GFS_DRIVE_MAIN)@@ -712,7 +752,15 @@ export function FilesPage({}updates.push({ source, bits })}- setParentUpdate({ row, label, mode: 'change-role', nextRole: role, updates })+ setParentUpdate({+ row,+ label,+ mode: 'change-role',+ nextRole: role,+ updates,+ residualSources: plan.shareOnlySources,+ skippedFolderNames,+ })}const handleInheritedRemove = (row: GfsMergedAccessRow, label: string) => {@@ -790,10 +838,17 @@ export function FilesPage({for (const { source, bits } of updates) {try {// Each affected folder's grant is updated with the bits the- // pre-flight validated on that folder, and keeps cascading to- // everything inside; its superseded share rows are consolidated.- await window.clerum.gfs.grant(source.resourceId, [subjectKey], bits, GFS_DRIVE_MAIN, true)- for (const shareId of source.shareIds) await ctrl.revokeShare(shareId)+ // pre-flight validated on that folder, preserving the GRANT ROW'S+ // OWN scope flag (R1-M5 — the pre-flight guaranteed a known+ // boolean). The folder's share rows are never touched by a role+ // change; they survive as residual access and are disclosed below.+ await window.clerum.gfs.grant(+ source.resourceId,+ [subjectKey],+ bits,+ GFS_DRIVE_MAIN,+ source.grantInherit === true+ )updated += 1} catch (updateError) {await failPartially(@@ -803,28 +858,34 @@ export function FilesPage({return}}- // The file's own direct rows are aligned so they cannot mask the- // confirmed role: the grant upsert expresses the new role and every- // direct file share for the member is revoked after it — a stale- // editor share would otherwise keep the member an Editor.- if (request.row.grant || request.row.shares.length > 0) {+ const partialMessages: string[] = []+ if (request.skippedFolderNames.length > 0) {+ partialMessages.push(+ `Updated ${updated} of ${updates.length + request.skippedFolderNames.length} folders. Sharing details on ${joinFolderNames(request.skippedFolderNames)} could not be verified; existing access was kept.`+ )+ }+ // The file's own direct GRANT is aligned so it cannot mask the+ // confirmed role (R1-M5: a share-only direct row never gains a grant,+ // direct shares survive role edits, and unknown/empty direct authority+ // keeps the direct grant with an honest partial copy).+ if (request.row.grant) {try {const fileBits = rolePermissionRequest(subject.type, request.nextRole).filter(bit =>affordances?.grantableBits.includes(bit))- // N2: an empty bit set means the file's affordances are- // unavailable (or grant nothing). Do not send an empty grant after- // the parent update; revoke the old direct grant instead so it- // cannot keep masking the confirmed parent role.- if (fileBits.length > 0) {- await ctrl.grant([subjectKey], fileBits, request.row.grant?.inherit ?? false)- } else if (request.row.grant) {- // An empty affordance result cannot express the requested direct- // role. Remove the old grant so it cannot keep masking the- // parent-folder downgrade while the UI reports success.- await ctrl.revokeGrant(request.row.grant.id)+ const expressesRole =+ fileBits.includes('read') && (request.nextRole === 'read' || fileBits.includes('write'))+ if (expressesRole) {+ await ctrl.grant([subjectKey], fileBits, request.row.grant.inherit)+ } else {+ // N2 (R1-M5): an empty bit set means the file's affordances are+ // unavailable (or grant nothing) — keep the direct grant AND its+ // shares and say so; removing rights on an authority guess was+ // the defect.+ partialMessages.push(+ `Updated ${updated} of ${updates.length} folders — direct access on ${current?.name ?? 'this file'} could not be fully aligned`+ )}- for (const share of request.row.shares) await ctrl.revokeShare(share.id)} catch (updateError) {await failPartially(updateError,@@ -833,12 +894,42 @@ export function FilesPage({return}}- pushToast?.(- affectedNames.length > 0- ? `${label} is now ${request.nextRole === 'editor' ? 'an Editor' : 'Read-only'} on ${joinFolderNames(affectedNames)} and everything inside ${affectedNames.length > 1 ? 'them' : 'it'}`- : `${label} is now ${request.nextRole === 'editor' ? 'an Editor' : 'Read-only'} on ${current?.name ?? 'this file'}`,- 'success'- )+ // Residual honesty (R1-M5): a downgrade never claims effective+ // Read-only while a surviving share entry still grants Editor.+ const residualNames =+ request.nextRole === 'read'+ ? [+ ...new Set([+ ...[...request.residualSources, ...updates.map(update => update.source)]+ .filter(source =>+ source.shareEntries.some(entry => isEditorGfsPermissions(entry.permissions))+ )+ .map(source => source.name),+ ...(request.row.shares.some(share => isEditorGfsPermissions(share.permissions))+ ? [current?.name ?? 'this item']+ : []),+ ]),+ ]+ : []+ const residualMessage =+ residualNames.length > 0+ ? `Sharing entries on ${joinFolderNames(residualNames)} still grant Editor access.`+ : ''+ if (partialMessages.length > 0) {+ pushToast?.([...partialMessages, residualMessage].filter(Boolean).join(' '), 'error')+ } else if (residualMessage) {+ pushToast?.(+ `Changed grant access to ${request.nextRole === 'editor' ? 'Editor' : 'Read-only'} on ${affectedNames.length > 0 ? joinFolderNames(affectedNames) : (current?.name ?? 'this item')}. ${residualMessage}`,+ 'info'+ )+ } else {+ pushToast?.(+ affectedNames.length > 0+ ? `${label} is now ${request.nextRole === 'editor' ? 'an Editor' : 'Read-only'} on ${joinFolderNames(affectedNames)} and everything inside ${affectedNames.length > 1 ? 'them' : 'it'}`+ : `${label} is now ${request.nextRole === 'editor' ? 'an Editor' : 'Read-only'} on ${current?.name ?? 'this file'}`,+ 'success'+ )+ }await Promise.all([ctrl.refreshGrants(), ctrl.refreshInheritedAccess(), ctrl.refreshShares()])} finally {setUpdatingAccessRole(false)diff --git a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsxindex 994f5727d..fb7c03dfd 100644--- a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx+++ b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx@@ -1793,6 +1793,9 @@ describe('FilesPage', () => {permissions: ['read', 'write'],grantId: 'parent-grant-1',shareIds: [],+ grantPermissions: ['read', 'write'],+ grantInherit: true,+ shareEntries: [],},],},@@ -1884,6 +1887,9 @@ describe('FilesPage', () => {permissions: ['read', 'write'],grantId: 'root-grant-1',shareIds: [],+ grantPermissions: ['read', 'write'],+ grantInherit: true,+ shareEntries: [],},],},@@ -2040,7 +2046,11 @@ describe('FilesPage', () => {// R1-H2 — a stale direct file share must not survive a confirmed parent// role change: the editor share would keep masking the confirmed downgrade// while the toast claims Read-only.- it('revokes the file’s direct shares when a confirmed parent role change downgrades the member', async () => {+ // R1-M5 — a confirmed parent downgrade rewrites only the folder's grant;+ // the file's direct share rows SURVIVE the role change as residual access,+ // and the outcome copy discloses the surviving Editor instead of claiming+ // an effective downgrade.+ it('keeps the file’s direct shares on a confirmed parent downgrade and discloses the residual Editor', async () => {installInheritedDirectoryMocks()const parentGrant = (window.clerum.gfs as unknown as { grant: ReturnType<typeof vi.fn> }).grantconst directShare = {@@ -2062,32 +2072,28 @@ describe('FilesPage', () => {permissions: ['read', 'write'],grantId: 'parent-grant-1',shareIds: [],+ grantPermissions: ['read', 'write'],+ grantInherit: true,+ shareEntries: [],},],}const inheritedSource = inheritedEditor.sources[0]!- let refreshShareQuery: (() => void) | undefinedlet completeShareRefresh: (() => void) | undefinedlet downgradeInherited: (() => void) | undefinedparentGrant.mockImplementation(async () => {downgradeInherited?.()})- const fileGrant = vi.fn(async () => undefined)const revokeShare = vi.fn(async () => undefined)const refreshShares = vi.fn(() =>new Promise<void>(resolve => {- completeShareRefresh = () => {- refreshShareQuery?.()- resolve()- }+ completeShareRefresh = () => resolve()}))const pushToast = vi.fn()hookMock.useGfsBrowserController.mockImplementation(() => {- const [shares, setShares] = useState([directShare])const [inheritedAccess, setInheritedAccess] = useState([inheritedEditor])- refreshShareQuery = () => setShares([])downgradeInherited = () =>setInheritedAccess([{@@ -2098,9 +2104,8 @@ describe('FilesPage', () => {])return inheritedFileController({grants: [],- shares,+ shares: [directShare],inheritedAccess,- grant: fileGrant,revokeShare,refreshShares,})@@ -2127,57 +2132,40 @@ describe('FilesPage', () => {fireEvent.click(within(confirmDialog).getByRole('button', { name: 'Update role' }))})- // The revoke mutation does not alter rendered/query state by itself.- await waitFor(() => expect(revokeShare).toHaveBeenCalledWith('file-share-1'))- expect(- within(screen.getByTestId('gfs-access-row-inherited-user:user-2')).getByRole('button', {- name: 'Access role for Test Two',- }).textContent- ).toContain('Editor')- // …after the replacement grant expresses the confirmed role.+ // Only the parent folder's grant is rewritten, with its own scope flag…await waitFor(() =>- expect(fileGrant).toHaveBeenCalledWith(['user:user-2'], ['read', 'share'], false)+ expect(parentGrant).toHaveBeenCalledWith(+ 'folder-1',+ ['user:user-2'],+ ['read', 'share'],+ 'main',+ true+ ))+ // …and the role change NEVER revokes share rows.+ expect(revokeShare).not.toHaveBeenCalled()await waitFor(() => expect(refreshShares).toHaveBeenCalledTimes(1))+ await act(async () => {+ completeShareRefresh?.()+ })+ // The merged row truthfully stays Editor: the surviving direct share+ // still grants it.expect(within(screen.getByTestId('gfs-access-row-inherited-user:user-2')).getByRole('button', {name: 'Access role for Test Two',}).textContent).toContain('Editor')- await act(async () => {- completeShareRefresh?.()- })- await waitFor(() =>- expect(- within(screen.getByTestId('gfs-access-row-inherited-user:user-2')).getByRole('button', {- name: 'Access role for Test Two',- }).textContent- ).toContain('Read')- )expect(pushToast).toHaveBeenCalledWith(- 'Test Two is now Read-only on Team folder and everything inside it',- 'success'+ 'Changed grant access to Read-only on Team folder. Sharing entries on report.txt still grant Editor access.',+ 'info')})- // R1-H2 — a partial revoke also waits for refreshed server-backed shares- // before showing the effective role.- it('refreshes shares after a partial inherited-access mutation failure', async () => {+ // R1-H2/R1-M5 — a partial parent-grant failure refreshes the server-backed+ // lists before the effective role settles, and never touches shares.+ it('refreshes lists after a partial inherited-access mutation failure without touching shares', async () => {installInheritedDirectoryMocks()const parentGrant = (window.clerum.gfs as unknown as { grant: ReturnType<typeof vi.fn> }).grant- const editorShare = {- id: 'file-editor-share',- drive: 'main',- resourceId: 'file-1',- subject: { type: 'user', id: 'user-2' },- permissions: ['read', 'write'],- includeDescendants: false,- }- const readShare = {- ...editorShare,- id: 'file-read-share',- permissions: ['read'],- }const inheritedEditor = {subject: { type: 'user', id: 'user-2' },permissions: ['read', 'write'],@@ -2189,57 +2177,34 @@ describe('FilesPage', () => {permissions: ['read', 'write'],grantId: 'parent-grant-1',shareIds: [],+ grantPermissions: ['read', 'write'],+ grantInherit: true,+ shareEntries: [],},],}- const inheritedSource = inheritedEditor.sources[0]!- let refreshShareQuery: (() => void) | undefined- let completeShareRefresh: (() => void) | undefined- let downgradeInherited: (() => void) | undefined- parentGrant.mockImplementation(async () => downgradeInherited?.())- const revokeShare = vi- .fn<(shareId: string) => Promise<void>>()- .mockResolvedValueOnce(undefined)- .mockRejectedValueOnce(new Error('share revoke failed'))- const refreshShares = vi.fn(- () =>- new Promise<void>(resolve => {- completeShareRefresh = () => {- refreshShareQuery?.()- resolve()- }- })- )+ const revokeShare = vi.fn(async () => undefined)+ const refreshGrants = vi.fn(async () => undefined)+ const refreshInheritedAccess = vi.fn(async () => undefined)+ const refreshShares = vi.fn(async () => undefined)const pushToast = vi.fn()- hookMock.useGfsBrowserController.mockImplementation(() => {- const [shares, setShares] = useState([editorShare, readShare])- const [inheritedAccess, setInheritedAccess] = useState([inheritedEditor])- refreshShareQuery = () => setShares([readShare])- downgradeInherited = () =>- setInheritedAccess([- {- ...inheritedEditor,- permissions: ['read'],- sources: [{ ...inheritedSource, permissions: ['read'] }],- },- ])- return inheritedFileController({+ parentGrant.mockRejectedValueOnce(new Error('403 Forbidden: escalation_rejected'))+ hookMock.useGfsBrowserController.mockReturnValue(+ inheritedFileController({grants: [],- shares,- inheritedAccess,+ inheritedAccess: [inheritedEditor],revokeShare,+ refreshGrants,+ refreshInheritedAccess,refreshShares,})- })+ )renderFilesPage(pushToast)await openManageDialog('report.txt')const manageDialog = await screen.findByRole('dialog', { name: 'Share file report.txt' })const row = await within(manageDialog).findByTestId('gfs-access-row-inherited-user:user-2')- expect(- within(row).getByRole('button', { name: 'Access role for Test Two' }).textContent- ).toContain('Editor')await act(async () => {fireEvent.click(within(row).getByRole('button', { name: 'Access role for Test Two' }))})@@ -2251,29 +2216,24 @@ describe('FilesPage', () => {fireEvent.click(within(confirmDialog).getByRole('button', { name: 'Update role' }))})- await waitFor(() => expect(revokeShare).toHaveBeenCalledTimes(2))- expect(revokeShare).toHaveBeenNthCalledWith(1, 'file-editor-share')- expect(revokeShare).toHaveBeenNthCalledWith(2, 'file-read-share')+ await waitFor(() =>+ expect(pushToast).toHaveBeenCalledWith(+ expect.stringContaining('Updated 0 of 1 folders — Team folder still grants access'),+ 'error'+ )+ )+ // The partial failure refreshes every server-backed list…+ await waitFor(() => expect(refreshGrants).toHaveBeenCalledTimes(1))+ await waitFor(() => expect(refreshInheritedAccess).toHaveBeenCalledTimes(1))await waitFor(() => expect(refreshShares).toHaveBeenCalledTimes(1))+ // …and a failed role change never revokes shares.+ expect(revokeShare).not.toHaveBeenCalled()+ // The merged row truthfully stays Editor.expect(within(screen.getByTestId('gfs-access-row-inherited-user:user-2')).getByRole('button', {name: 'Access role for Test Two',}).textContent).toContain('Editor')- await act(async () => {- completeShareRefresh?.()- })- await waitFor(() =>- expect(- within(screen.getByTestId('gfs-access-row-inherited-user:user-2')).getByRole('button', {- name: 'Access role for Test Two',- }).textContent- ).toContain('Read')- )- expect(pushToast).toHaveBeenCalledWith(- expect.stringContaining('direct access on report.txt could not be fully aligned'),- 'error'- )})// R1-M1 — the parent grant's bits are judged by the PARENT folder's@@ -2328,8 +2288,69 @@ describe('FilesPage', () => {))expect(pushToast).toHaveBeenCalledWith(- 'Test Two is now Read-only on Team folder and everything inside it',- 'success'+ 'Updated 1 of 1 folders — direct access on report.txt could not be fully aligned',+ 'error'+ )+ expect(pushToast.mock.calls.some(([, tone]) => tone === 'success')).toBe(false)+ })++ // R1-M5 — a share-only ancestor is never converted into a grant: nothing+ // is written, no confirmation opens, and the user is told why nothing+ // changed — never a silent no-op.+ it('refuses a share-only ancestor role change without creating a grant', async () => {+ installInheritedDirectoryMocks()+ const parentGrant = (window.clerum.gfs as unknown as { grant: ReturnType<typeof vi.fn> }).grant+ const inheritedEditor = {+ subject: { type: 'user', id: 'user-2' },+ permissions: ['read', 'write'],+ inheritedFrom: ['Team folder'],+ sources: [+ {+ resourceId: 'folder-1',+ name: 'Team folder',+ permissions: ['read', 'write'],+ grantId: null,+ shareIds: ['folder-share-1'],+ grantPermissions: null,+ grantInherit: null,+ shareEntries: [+ {+ rowId: 'folder-share-1',+ permissions: ['read', 'write'],+ includeDescendants: true,+ },+ ],+ },+ ],+ }+ const revokeShare = vi.fn(async () => undefined)+ const pushToast = vi.fn()+ hookMock.useGfsBrowserController.mockReturnValue(+ inheritedFileController({+ grants: [],+ inheritedAccess: [inheritedEditor],+ revokeShare,+ })+ )++ renderFilesPage(pushToast)+ await openManageDialog('report.txt')+ const manageDialog = await screen.findByRole('dialog', { name: 'Share file report.txt' })+ const row = await within(manageDialog).findByTestId('gfs-access-row-inherited-user:user-2')++ await act(async () => {+ fireEvent.click(within(row).getByRole('button', { name: 'Access role for Test Two' }))+ })+ await act(async () => {+ fireEvent.click(screen.getByRole('option', { name: 'Read' }))+ })++ expect(screen.queryByRole('alertdialog')).toBeNull()+ expect(parentGrant).not.toHaveBeenCalled()+ expect(revokeShare).not.toHaveBeenCalled()+ expect(pushToast).toHaveBeenCalledWith(+ "Test Two still has Editor access from sharing entries that can't be edited here.",+ 'info')})@@ -2361,6 +2382,9 @@ describe('FilesPage', () => {permissions: ['read'],grantId: 'parent-grant-1',shareIds: [],+ grantPermissions: ['read'],+ grantInherit: true,+ shareEntries: [],},],},@@ -2456,6 +2480,9 @@ describe('FilesPage', () => {permissions: ['read', 'write'],grantId: 'cmp-grant-1',shareIds: [],+ grantPermissions: ['read', 'write'],+ grantInherit: true,+ shareEntries: [],}const MARKETING = {resourceId: 'folder-mkt',@@ -2463,6 +2490,9 @@ describe('FilesPage', () => {permissions: ['read', 'share'],grantId: 'mkt-grant-1',shareIds: [],+ grantPermissions: ['read', 'share'],+ grantInherit: true,+ shareEntries: [],}const EDITOR_PERMISSIONS = ['read', 'write', 'delete', 'manage_acl', 'share']@@ -2664,6 +2694,9 @@ describe('FilesPage', () => {permissions: ['read'],grantId: 'parent-grant-1',shareIds: [],+ grantPermissions: ['read'],+ grantInherit: true,+ shareEntries: [],},],},@@ -2699,10 +2732,11 @@ describe('FilesPage', () => {)})- // N2 — when the file's affordances are unavailable (empty grantable- // bits), the old direct grant must be revoked so it cannot keep masking- // the parent update.- it('revokes an unexpressible direct grant and renders the effective role after refresh', async () => {+ // N2 (R1-M5) — when the file's affordances are unavailable (empty+ // grantable bits), the direct grant AND its shares are KEPT: rights are+ // never removed on an authority guess, and the partial outcome is stated+ // through the existing honest copy.+ it('keeps an unexpressible direct grant and states the partial alignment honestly', async () => {installInheritedDirectoryMocks()const parentGrant = (window.clerum.gfs as unknown as { grant: ReturnType<typeof vi.fn> }).grant@@ -2725,25 +2759,24 @@ describe('FilesPage', () => {permissions: ['read', 'write'],grantId: 'parent-grant-1',shareIds: [],+ grantPermissions: ['read', 'write'],+ grantInherit: true,+ shareEntries: [],},],}- let removeEditorGrant: (() => void) | undefinedlet downgradeInherited: (() => void) | undefinedparentGrant.mockImplementation(async () => {downgradeInherited?.()})- const revokeGrant = vi.fn(async () => {- removeEditorGrant?.()- })+ const revokeGrant = vi.fn(async () => undefined)+ const fileGrant = vi.fn(async () => undefined)const refreshGrants = vi.fn(async () => undefined)const refreshInheritedAccess = vi.fn(async () => undefined)const refreshShares = vi.fn(async () => undefined)const pushToast = vi.fn()hookMock.useGfsBrowserController.mockImplementation(() => {- const [grants, setGrants] = useState([editorGrant])const [inheritedAccess, setInheritedAccess] = useState([inheritedEditor])- removeEditorGrant = () => setGrants([])downgradeInherited = () =>setInheritedAccess([{@@ -2753,7 +2786,7 @@ describe('FilesPage', () => {},])return inheritedFileController({- grants,+ grants: [editorGrant],inheritedAccess,affordances: {held: ['read', 'manage_acl'],@@ -2761,6 +2794,7 @@ describe('FilesPage', () => {grantableBits: [],canCreateShare: false,},+ grant: fileGrant,revokeGrant,refreshGrants,refreshInheritedAccess,@@ -2784,7 +2818,8 @@ describe('FilesPage', () => {fireEvent.click(within(confirmDialog).getByRole('button', { name: 'Update role' }))})- // The parent update succeeded with its pre-validated folder bits…+ // The parent update succeeded with its pre-validated folder bits and+ // the folder grant's OWN scope flag.await waitFor(() =>expect(parentGrant).toHaveBeenCalledWith('folder-1',@@ -2794,27 +2829,25 @@ describe('FilesPage', () => {true))- // The stale direct Editor grant is revoked instead of being left to- // mask the parent result.- await waitFor(() => expect(revokeGrant).toHaveBeenCalledWith('file-editor-grant'))- // The observable merged row now reflects the effective Read role after- // both the parent and direct surfaces refresh.- await waitFor(() =>- expect(- within(screen.getByTestId('gfs-access-row-inherited-user:user-2')).getByRole('button', {- name: 'Access role for Test Two',- }).textContent- ).toContain('Read')- )+ // The direct grant is NEVER revoked on the unknown authority — and no+ // replacement grant is invented either.+ await waitFor(() => expect(refreshGrants).toHaveBeenCalledTimes(1))+ expect(revokeGrant).not.toHaveBeenCalled()+ expect(fileGrant).not.toHaveBeenCalled()+ // The observable merged row truthfully stays Editor: the kept direct+ // grant still grants it.+ expect(+ within(screen.getByTestId('gfs-access-row-inherited-user:user-2')).getByRole('button', {+ name: 'Access role for Test Two',+ }).textContent+ ).toContain('Editor')await waitFor(() =>expect(pushToast).toHaveBeenCalledWith(- 'Test Two is now Read-only on Team folder and everything inside it',- 'success'+ 'Updated 1 of 1 folders — direct access on report.txt could not be fully aligned',+ 'error'))- pushToast.mock.calls.forEach(([message, tone]) => {- expect(tone).not.toBe('error')- })+ expect(pushToast.mock.calls.some(([, tone]) => tone === 'success')).toBe(false)})it('states the true partial outcome when a folder removal fails mid-run', async () => {