Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(evendrive): keep every contributing ancestor and edit them honestly (R1-H1)

M78e788480174
diff --git a/control-ui/app/globals.css b/control-ui/app/globals.css
index 9fe0ccfa3..303c1b4d7 100644
--- a/control-ui/app/globals.css
+++ b/control-ui/app/globals.css
@@ -13980,16 +13980,18 @@ button.cu-gfs-tree__button:focus-visible,
outline-offset: 2px;
}
-.cu-gfs-parent-update__columns {
+/* R1-H1: every affected ancestor folder plus the file, stacked. */
+.cu-gfs-parent-update__folders {
display: grid;
- grid-template-columns: repeat(2, minmax(0, 1fr));
- gap: var(--cu-space-2);
+ gap: var(--cu-space-1);
}
-.cu-gfs-parent-update__column {
- display: grid;
- gap: var(--cu-space-05);
- padding: var(--cu-space-2);
+.cu-gfs-parent-update__folder {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--cu-space-2);
+ padding: var(--cu-space-1) var(--cu-space-2);
border: 1px solid var(--cu-border-subtle);
border-radius: var(--cu-radius-sm);
background: var(--cu-bg-subtle);
diff --git a/control-ui/components/GfsGrantPanel.tsx b/control-ui/components/GfsGrantPanel.tsx
index e940f128b..0aeb4c82b 100644
--- a/control-ui/components/GfsGrantPanel.tsx
+++ b/control-ui/components/GfsGrantPanel.tsx
@@ -40,9 +40,10 @@ import type {
GfsFileAccessRow,
GfsGrantPanelProps,
GfsInheritedAccessItem,
+ GfsInheritedAccessSource,
} from './GfsGrantPanel.types'
import { buildGfsBulkSubjectOptions, toGfsBulkSubjectInputs } from './gfsGrantSubjectOptions'
-import { loadGfsInheritedAccess } from './gfsInheritedAccess'
+import { loadGfsInheritedAccess, planInheritedRoleChange } from './gfsInheritedAccess'
/**
* P4-S07 — Operator delegation panel for the Global File System. The operator
@@ -83,6 +84,12 @@ function hostOnlySubject(subject: { type: string }): boolean {
return subject.type === 'host'
}
+/** ["a", "b", "c"] → "a, b and c" — folder names for honest outcome toasts. */
+function joinFolderNames(names: string[]): string {
+ if (names.length <= 1) return names[0] ?? ''
+ return `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`
+}
+
/** Stable per-subject merge key. The operator variant carries no id. */
function subjectKey(subject: GfsSubjectInput): string {
return `${subject.type}:${'id' in subject ? subject.id : ''}`
@@ -131,9 +138,16 @@ export function GfsGrantPanel({ resource }: GfsGrantPanelProps): React.JSX.Eleme
const inheritedAccessRequest = useRef(0)
const inheritedAccessController = useRef<AbortController | null>(null)
// Pending parent-folder confirmation (role change or removal) for a member
- // whose access is inherited from an ancestor folder.
+ // whose access is inherited from ancestor folders. change-role carries the
+ // affected folders from the R1-H1 plan (downgrade: every folder above the
+ // target role; upgrade: the single strongest folder).
const [parentUpdate, setParentUpdate] = useState<
- | { row: GfsFileAccessRow; mode: 'change-role'; nextRole: AccessRole }
+ | {
+ row: GfsFileAccessRow
+ mode: 'change-role'
+ nextRole: AccessRole
+ affected: GfsInheritedAccessSource[]
+ }
| { row: GfsFileAccessRow; mode: 'remove' }
| null
>(null)
@@ -538,10 +552,15 @@ export function GfsGrantPanel({ resource }: GfsGrantPanelProps): React.JSX.Eleme
}
/**
- * Confirmed edit of an inherited row: the change is applied to the parent
- * folder that configures the access (its grant cascades to everything
- * inside), and the file's own direct rows are aligned so they cannot mask
- * the chosen role. Cancel never reaches this path — the dropdown reverts.
+ * Confirmed edit of an inherited row (R1-H1 semantics, verified against
+ * Google Drive): a removal revokes the member's rows on EVERY contributing
+ * ancestor folder; a downgrade lowers every ancestor above the target role;
+ * an upgrade raises the strongest ancestor. The file's own direct rows are
+ * aligned in every case so they cannot mask the outcome. The confirm issues
+ * several sequential calls — on the first failure it stops, refreshes both
+ * lists so the dialog shows the TRUE partial state, and the toast says
+ * exactly how far the change got. Full success is never claimed on partial
+ * completion. Cancel never reaches this path — the dropdown reverts.
*/
async function confirmParentUpdate() {
const request = parentUpdate
@@ -552,25 +571,93 @@ export function GfsGrantPanel({ resource }: GfsGrantPanelProps): React.JSX.Eleme
setParentUpdate(null)
return
}
- const source = inherited.source
+ const sources = inherited.sources
setParentUpdate(null)
setBusy(true)
setError('')
const reload = async () => {
await Promise.all([loadExistingAccess(), loadInheritedAccess()])
}
+ /** Partial-failure honesty: state the true outcome, show the server error, reload. */
+ const failPartially = async (caught: unknown, summary: string) => {
+ if (!isAlreadyMissing(caught)) {
+ setError(caught instanceof Error ? caught.message : 'Failed to update access')
+ }
+ showToast(summary, { tone: 'error' })
+ await reload()
+ }
try {
- if (request.mode === 'change-role') {
- const permissions = rolePermissions(request.nextRole, hostOnlySubject(row.subject))
- await putGfsGrant({
- drive: DRIVE,
- resourceId: source.resourceId,
- subject: row.subject,
- permissions,
- inherit: true,
- })
- for (const shareId of source.shareIds) await deleteGfsShare(shareId)
+ if (request.mode === 'remove') {
+ let removed = 0
+ for (const source of sources) {
+ try {
+ if (source.grantId) await deleteGfsGrant(source.grantId)
+ for (const shareId of source.shareIds) await deleteGfsShare(shareId)
+ removed += 1
+ } catch (caught) {
+ if (isAlreadyMissing(caught)) {
+ removed += 1
+ continue
+ }
+ await failPartially(
+ caught,
+ `Removed from ${removed} of ${sources.length} folders — ${source.name} still grants access.`
+ )
+ return
+ }
+ }
if (row.direct) {
+ try {
+ if (row.direct.grantId) await deleteGfsGrant(row.direct.grantId)
+ for (const shareId of row.direct.shareIds) await deleteGfsShare(shareId)
+ } catch (caught) {
+ if (!isAlreadyMissing(caught)) {
+ await failPartially(
+ caught,
+ `Removed from ${sources.length} of ${sources.length} folders — direct access on ${resource.name} could not be removed.`
+ )
+ return
+ }
+ }
+ }
+ showToast(
+ sources.length === 1
+ ? `Access removed on ${sources[0].name} and everything inside it.`
+ : `Access removed on ${sources.length} folders and everything inside them.`,
+ { tone: 'success' }
+ )
+ await reload()
+ return
+ }
+ const affected = request.affected
+ const permissions = rolePermissions(request.nextRole, hostOnlySubject(row.subject))
+ const affectedNames = affected.map(source => source.name)
+ let updated = 0
+ for (const source of affected) {
+ try {
+ await putGfsGrant({
+ drive: DRIVE,
+ resourceId: source.resourceId,
+ subject: row.subject,
+ permissions,
+ inherit: true,
+ })
+ for (const shareId of source.shareIds) await deleteGfsShare(shareId)
+ updated += 1
+ } catch (caught) {
+ if (isAlreadyMissing(caught)) {
+ updated += 1
+ continue
+ }
+ await failPartially(
+ caught,
+ `Updated ${updated} of ${affected.length} folders — ${source.name} still grants access.`
+ )
+ return
+ }
+ }
+ if (row.direct) {
+ try {
await putGfsGrant({
drive: DRIVE,
resourceId: resource.resourceId,
@@ -579,23 +666,20 @@ export function GfsGrantPanel({ resource }: GfsGrantPanelProps): React.JSX.Eleme
inherit: row.direct.inherit,
})
for (const shareId of row.direct.shareIds) await deleteGfsShare(shareId)
+ } catch (caught) {
+ await failPartially(
+ caught,
+ `Updated ${affected.length} of ${affected.length} folders — direct access on ${resource.name} still shows the old role.`
+ )
+ return
}
- showToast(
- `${subjectLabel(row)} is now ${request.nextRole === 'editor' ? 'an Editor' : 'Read-only'} on ${source.name} and everything inside it.`,
- { tone: 'success' }
- )
- } else {
- if (source.grantId) await deleteGfsGrant(source.grantId)
- for (const shareId of source.shareIds) await deleteGfsShare(shareId)
- showToast(`Access removed on ${source.name} and everything inside it.`, {
- tone: 'success',
- })
- }
- await reload()
- } catch (caught) {
- if (!isAlreadyMissing(caught)) {
- setError(caught instanceof Error ? caught.message : 'Failed to update access')
}
+ 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)
@@ -735,18 +819,29 @@ export function GfsGrantPanel({ resource }: GfsGrantPanelProps): React.JSX.Eleme
className="cu-gfs-existing-access__role"
disabled={actionPending}
multiple={false}
- onChange={next =>
- inherited
- ? setParentUpdate({
- row,
- mode: 'change-role',
- nextRole: (next[0] ?? 'read') as AccessRole,
- })
- : void updateAccessRole(
- row.direct as GfsExistingAccessItem,
- (next[0] ?? 'read') as AccessRole
- )
- }
+ onChange={next => {
+ if (!inherited) {
+ void updateAccessRole(
+ row.direct as GfsExistingAccessItem,
+ (next[0] ?? 'read') as AccessRole
+ )
+ return
+ }
+ const nextRole = (next[0] ?? 'read') as AccessRole
+ const affected = planInheritedRoleChange(
+ row.inherited as GfsInheritedAccessItem,
+ nextRole === 'editor'
+ )
+ // Selecting the already-held role with only
+ // inherited access changes nothing: no modal.
+ if (affected.length === 0 && !row.direct) return
+ setParentUpdate({
+ row,
+ mode: 'change-role',
+ nextRole,
+ affected,
+ })
+ }}
menuClassName="cu-gfs-existing-access__role-menu"
options={ROLE_OPTIONS}
placeholder="Role"
@@ -838,17 +933,21 @@ export function GfsGrantPanel({ resource }: GfsGrantPanelProps): React.JSX.Eleme
? {
mode: parentUpdate.mode,
memberLabel: subjectLabel(parentUpdate.row),
- parentFolderName: parentUpdate.row.inherited.source.name,
fileName: resource.name,
- parentCurrentRole: roleForPermissions(
- parentUpdate.row.inherited.source.permissions
- ),
+ // Removal touches every contributing folder; a role change
+ // touches only the R1-H1 plan's affected folders.
+ folders:
+ parentUpdate.mode === 'remove'
+ ? parentUpdate.row.inherited.sources.map(source => ({
+ name: source.name,
+ currentRole: roleForPermissions(source.permissions),
+ }))
+ : parentUpdate.affected.map(source => ({
+ name: source.name,
+ currentRole: roleForPermissions(source.permissions),
+ })),
fileCurrentRole: roleForPermissions(parentUpdate.row.permissions),
nextRole: parentUpdate.mode === 'change-role' ? parentUpdate.nextRole : undefined,
- fileRemainingRole:
- parentUpdate.mode === 'remove' && parentUpdate.row.direct
- ? roleForPermissions(parentUpdate.row.direct.permissions)
- : null,
}
: null
}
diff --git a/control-ui/components/GfsGrantPanel.types.ts b/control-ui/components/GfsGrantPanel.types.ts
index 3c79324ea..3141c4a57 100644
--- a/control-ui/components/GfsGrantPanel.types.ts
+++ b/control-ui/components/GfsGrantPanel.types.ts
@@ -63,10 +63,12 @@ export type GfsFileAccessRow = {
}
/**
- * The ancestor folder a subject's inherited access is edited through: the
- * contributing folder with the strongest role (nearest among equals). Its
- * grant/share ids let the Share dialog route a confirmed change to the
- * folder that actually configures the access.
+ * ONE contributing ancestor folder of a subject's inherited access: its
+ * inheriting grant (inherit=true) and/or descendant-covering share
+ * (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.
*/
export type GfsInheritedAccessSource = {
resourceId: string
@@ -78,8 +80,7 @@ export type GfsInheritedAccessSource = {
}
/**
- * An access row derived from an ancestor folder's inheriting grant
- * (inherit=true) or descendant-covering share (includeDescendants=true). The
+ * An access row derived from ancestor folders' inheriting grants/shares. The
* grants/shares GETs expose only direct rows, so inheritance is derived on
* the client by walking the resource's ancestor folders.
*/
@@ -88,6 +89,6 @@ export type GfsInheritedAccessItem = {
permissions: string[]
/** Contributing ancestor folder labels, nearest first, deduplicated. */
inheritedFrom: string[]
- /** The folder a confirmed role change or removal is applied to. */
- source: GfsInheritedAccessSource
+ /** Every contributing ancestor folder, nearest first (R1-H1). */
+ sources: GfsInheritedAccessSource[]
}
diff --git a/control-ui/components/GfsInheritedAccessDialog/index.tsx b/control-ui/components/GfsInheritedAccessDialog/index.tsx
index be7dcf9c5..0189b2491 100644
--- a/control-ui/components/GfsInheritedAccessDialog/index.tsx
+++ b/control-ui/components/GfsInheritedAccessDialog/index.tsx
@@ -30,7 +30,7 @@ export function GfsInheritedAccessDialog({
}: GfsInheritedAccessDialogProps): React.JSX.Element | null {
const titleId = useId()
const bodyId = useId()
- const columnsId = useId()
+ const foldersId = useId()
const cancelButtonRef = useRef<HTMLButtonElement | null>(null)
const [showHelp, setShowHelp] = useState(false)
@@ -59,18 +59,11 @@ export function GfsInheritedAccessDialog({
if (!request) return null
const isRemove = request.mode === 'remove'
- const nextLabel = isRemove
- ? request.fileRemainingRole
- ? ROLE_LABELS[request.fileRemainingRole]
- : 'No access'
- : request.nextRole
- ? ROLE_LABELS[request.nextRole]
- : ''
- const parentNextLabel = isRemove ? 'No access' : nextLabel
+ const nextLabel = isRemove ? 'Remove' : request.nextRole ? ROLE_LABELS[request.nextRole] : ''
const confirmLabel = isRemove ? 'Remove' : 'Update role'
- const title = isRemove ? 'Remove access on parent folder?' : 'Update role on parent folder?'
+ const title = isRemove ? 'Remove from parent folder?' : 'Update role on parent folder?'
const lead = isRemove
- ? `Removing ${request.memberLabel}'s access to this item will also remove their access on a parent folder.`
+ ? `Removing ${request.memberLabel} from this item will also remove them from a parent folder.`
: `Changing ${request.memberLabel}'s permissions on this item will also change permissions on a parent folder.`
return (
@@ -86,7 +79,7 @@ export function GfsInheritedAccessDialog({
role="alertdialog"
aria-modal="true"
aria-labelledby={titleId}
- aria-describedby={showHelp ? `${bodyId}` : `${bodyId} ${columnsId}`}
+ aria-describedby={showHelp ? `${bodyId}` : `${bodyId} ${foldersId}`}
onMouseDown={event => event.stopPropagation()}
>
<div className="cu-modal-panel__head">
@@ -114,20 +107,22 @@ export function GfsInheritedAccessDialog({
Learn more
</button>
</p>
- <div id={columnsId} className="cu-gfs-parent-update__columns">
- <div className="cu-gfs-parent-update__column">
- <span className="cu-gfs-parent-update__name">{request.parentFolderName}</span>
- <span className="cu-gfs-parent-update__change">
- <span className="cu-gfs-parent-update__role">
- {ROLE_LABELS[request.parentCurrentRole]}
- </span>
- <span aria-hidden="true">→</span>
- <span className="cu-gfs-parent-update__role cu-gfs-parent-update__role--next">
- {parentNextLabel}
+ <div id={foldersId} className="cu-gfs-parent-update__folders">
+ {request.folders.map(folder => (
+ <div className="cu-gfs-parent-update__folder" key={folder.name}>
+ <span className="cu-gfs-parent-update__name">{folder.name}</span>
+ <span className="cu-gfs-parent-update__change">
+ <span className="cu-gfs-parent-update__role">
+ {ROLE_LABELS[folder.currentRole]}
+ </span>
+ <span aria-hidden="true">→</span>
+ <span className="cu-gfs-parent-update__role cu-gfs-parent-update__role--next">
+ {nextLabel}
+ </span>
</span>
- </span>
- </div>
- <div className="cu-gfs-parent-update__column">
+ </div>
+ ))}
+ <div className="cu-gfs-parent-update__folder">
<span className="cu-gfs-parent-update__name">{request.fileName}</span>
<span className="cu-gfs-parent-update__change">
<span className="cu-gfs-parent-update__role">
diff --git a/control-ui/components/GfsInheritedAccessDialog/types.ts b/control-ui/components/GfsInheritedAccessDialog/types.ts
index cbce00bf1..657a001b5 100644
--- a/control-ui/components/GfsInheritedAccessDialog/types.ts
+++ b/control-ui/components/GfsInheritedAccessDialog/types.ts
@@ -1,20 +1,27 @@
export type GfsInheritedAccessRole = 'read' | 'editor'
+export type GfsInheritedAccessDialogFolder = {
+ name: string
+ /** Role the member holds on that ancestor folder today. */
+ currentRole: GfsInheritedAccessRole
+}
+
export type GfsInheritedAccessDialogRequest = {
- /** 'change-role' confirms a parent-folder role update; 'remove' removes the member from the parent folder. */
+ /** 'change-role' confirms a parent-folder role update; 'remove' removes the member from every contributing ancestor folder. */
mode: 'change-role' | 'remove'
memberLabel: string
- parentFolderName: string
/** The file whose Share dialog opened this confirmation. */
fileName: string
- /** Role the member holds on the parent folder today. */
- parentCurrentRole: GfsInheritedAccessRole
+ /**
+ * Every ancestor folder the confirm will touch (R1-H1): all contributing
+ * folders for a removal, the folders above the target role for a
+ * downgrade, the single raised folder for an upgrade.
+ */
+ folders: GfsInheritedAccessDialogFolder[]
/** Role the member effectively holds on this file today. */
fileCurrentRole: GfsInheritedAccessRole
- /** change-role: the role that will replace parentCurrentRole/fileCurrentRole. */
+ /** change-role: the role that will replace the folders'/file's current role. */
nextRole?: GfsInheritedAccessRole
- /** remove: the direct access that survives on the file, null for none. */
- fileRemainingRole?: GfsInheritedAccessRole | null
}
export interface GfsInheritedAccessDialogProps {
diff --git a/control-ui/components/__tests__/GfsGrantPanel.inherited.test.tsx b/control-ui/components/__tests__/GfsGrantPanel.inherited.test.tsx
index fa63ead01..bb9b54ee2 100644
--- a/control-ui/components/__tests__/GfsGrantPanel.inherited.test.tsx
+++ b/control-ui/components/__tests__/GfsGrantPanel.inherited.test.tsx
@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import {
deleteGfsGrant,
+ deleteGfsShare,
getAdminTeams,
getAdminUsers,
getGfsGrants,
@@ -37,6 +38,7 @@ const mockGetGfsShares = vi.mocked(getGfsShares)
const mockGetGfsResourceByPath = vi.mocked(getGfsResourceByPath)
const mockPutGfsGrant = vi.mocked(putGfsGrant)
const mockDeleteGfsGrant = vi.mocked(deleteGfsGrant)
+const mockDeleteGfsShare = vi.mocked(deleteGfsShare)
const FILE_ID = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'
const FOLDER_ID = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'
@@ -355,10 +357,10 @@ describe('GfsGrantPanel inherited access', () => {
fireEvent.click(await screen.findByRole('menuitem', { name: 'Remove access' }))
const dialog = await screen.findByRole('alertdialog')
- expect(within(dialog).getByText('Remove access on parent folder?')).toBeTruthy()
+ expect(within(dialog).getByText('Remove from parent folder?')).toBeTruthy()
expect(
within(dialog).getByText(
- "Removing Miguel's access to this item will also remove their access on a parent folder. Alternatively, create a folder with limited access."
+ /Removing Miguel from this item will also remove them from a parent folder\. Alternatively, create a folder with limited access\./
)
).toBeTruthy()
fireEvent.click(within(dialog).getByRole('button', { name: 'Remove' }))
@@ -521,7 +523,7 @@ describe('GfsGrantPanel inherited access', () => {
within(rows[0]).getByRole('button', { name: 'Access role for Miguel' }).textContent
).toContain('Editor')
- // A confirmed change routes to the strongest contributing folder.
+ // A confirmed downgrade routes only to the folders above the target.
await chooseRole(rows[0], 'Read')
const dialog = await screen.findByRole('alertdialog')
expect(within(dialog).getByText('team-docs')).toBeTruthy()
@@ -532,4 +534,243 @@ describe('GfsGrantPanel inherited access', () => {
)
)
})
+
+ // R1-H1 — Drive-aligned multi-ancestor semantics. Reference scenario:
+ // Marketing (Viewer) → Campaigns (Editor) → report.svg. The nested-file
+ // path is '/marketing/campaigns/report.md'.
+ describe('R1-H1 multi-ancestor edits', () => {
+ const MKT_ID = 'dddddddd-dddd-dddd-dddd-dddddddddddd'
+ const CMP_ID = 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee'
+ const MKT_GRANT_ID = 'mkt-grant-1'
+ const CMP_GRANT_ID = 'cmp-grant-1'
+ const EDITOR = ['read', 'write', 'delete', 'manage_acl', 'share']
+ const VIEWER = ['read', 'share']
+
+ const nestedFile = {
+ resourceId: FILE_ID,
+ name: 'report.svg',
+ gfsUri: 'gfs://main/report',
+ kind: 'file',
+ path: '/marketing/campaigns/report.svg',
+ }
+
+ /** marketing → campaigns → report.svg, with per-folder roles for Miguel. */
+ function driveScenario(folders: {
+ campaigns?: string[] | null
+ marketing?: string[] | null
+ rootShare?: string[] | null
+ fileGrant?: string[] | null
+ }) {
+ mockGetGfsResourceByPath.mockImplementation(async (_drive, path) => {
+ if (path === '/marketing/campaigns') return byPathView(CMP_ID, 'campaigns')
+ if (path === '/marketing') return byPathView(MKT_ID, 'marketing')
+ if (path === '/') return byPathView(ROOT_ID, '')
+ throw Object.assign(new Error('404 not_found'), { status: 404 })
+ })
+ mockGetGfsGrants.mockImplementation(async resourceId => {
+ if (resourceId === CMP_ID && folders.campaigns) {
+ return {
+ items: [
+ {
+ id: CMP_GRANT_ID,
+ drive: 'main',
+ resourceId: CMP_ID,
+ subject: miguel,
+ permissions: folders.campaigns,
+ inherit: true,
+ },
+ ],
+ }
+ }
+ if (resourceId === MKT_ID && folders.marketing) {
+ return {
+ items: [
+ {
+ id: MKT_GRANT_ID,
+ drive: 'main',
+ resourceId: MKT_ID,
+ subject: miguel,
+ permissions: folders.marketing,
+ inherit: true,
+ },
+ ],
+ }
+ }
+ if (resourceId === FILE_ID && folders.fileGrant) {
+ return {
+ items: [
+ {
+ id: FILE_GRANT_ID,
+ drive: 'main',
+ resourceId: FILE_ID,
+ subject: miguel,
+ permissions: folders.fileGrant,
+ inherit: false,
+ },
+ ],
+ }
+ }
+ return { items: [] }
+ })
+ mockGetGfsShares.mockImplementation(async resourceId => {
+ if (resourceId === ROOT_ID && folders.rootShare) {
+ return {
+ items: [
+ {
+ id: ROOT_SHARE_ID,
+ drive: 'main',
+ resourceId: ROOT_ID,
+ subject: miguel,
+ permissions: folders.rootShare,
+ includeDescendants: true,
+ },
+ ],
+ }
+ }
+ return { items: [] }
+ })
+ }
+
+ function grantError(status: number, code: string) {
+ return Object.assign(new Error(`${status} ${code}`), { status, code, serverMessage: code })
+ }
+
+ async function openRoleDialog(resource = nestedFile) {
+ renderPanel(resource)
+ const existing = await screen.findByRole('region', { name: 'People with access' })
+ const row = await within(existing).findByTestId('gfs-access-row-user')
+ return row
+ }
+
+ it('removes the member from EVERY contributing ancestor after confirmation', async () => {
+ driveScenario({ campaigns: EDITOR, rootShare: VIEWER, fileGrant: VIEWER })
+ const row = await openRoleDialog()
+
+ fireEvent.click(within(row).getByRole('button', { name: 'Actions for Miguel' }))
+ fireEvent.click(await screen.findByRole('menuitem', { name: 'Remove access' }))
+
+ const dialog = await screen.findByRole('alertdialog')
+ expect(within(dialog).getByText('Remove from parent folder?')).toBeTruthy()
+ // Every affected folder is listed with its own current role…
+ expect(within(dialog).getByText('campaigns')).toBeTruthy()
+ expect(within(dialog).getByText('main')).toBeTruthy()
+ expect(within(dialog).getByText('report.svg')).toBeTruthy()
+
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Remove' }))
+
+ // …and every ancestor row is revoked: both folders plus the file's
+ // own direct grant.
+ await waitFor(() => expect(mockDeleteGfsGrant).toHaveBeenCalledWith(CMP_GRANT_ID))
+ await waitFor(() => expect(mockDeleteGfsShare).toHaveBeenCalledWith(ROOT_SHARE_ID))
+ await waitFor(() => expect(mockDeleteGfsGrant).toHaveBeenCalledWith(FILE_GRANT_ID))
+ await waitFor(() =>
+ expect(screen.getByText('Access removed on 2 folders and everything inside them.'))
+ )
+ })
+
+ it('downgrades only the ancestors above the target role (Drive: campaigns Editor→Read, marketing untouched)', async () => {
+ driveScenario({ campaigns: EDITOR, marketing: VIEWER })
+ const row = await openRoleDialog()
+
+ await chooseRole(row, 'Read')
+ const dialog = await screen.findByRole('alertdialog')
+ // Only the editor folder is affected; marketing stays untouched.
+ expect(within(dialog).getByText('campaigns')).toBeTruthy()
+ expect(within(dialog).queryByText('marketing')).toBeNull()
+
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Update role' }))
+
+ await waitFor(() => expect(mockPutGfsGrant).toHaveBeenCalledTimes(1))
+ expect(mockPutGfsGrant).toHaveBeenCalledWith({
+ drive: 'main',
+ resourceId: CMP_ID,
+ subject: miguel,
+ permissions: VIEWER,
+ inherit: true,
+ })
+ await waitFor(() =>
+ expect(screen.getByText('Miguel is now Read-only on campaigns and everything inside it.'))
+ )
+ })
+
+ it('lowers EVERY editor ancestor when all sit above the target', async () => {
+ driveScenario({ campaigns: EDITOR, marketing: EDITOR })
+ const row = await openRoleDialog()
+
+ await chooseRole(row, 'Read')
+ const dialog = await screen.findByRole('alertdialog')
+ expect(within(dialog).getByText('campaigns')).toBeTruthy()
+ expect(within(dialog).getByText('marketing')).toBeTruthy()
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Update role' }))
+
+ await waitFor(() => expect(mockPutGfsGrant).toHaveBeenCalledTimes(2))
+ const touched = mockPutGfsGrant.mock.calls.map(call => call[0].resourceId)
+ expect(touched).toEqual([CMP_ID, MKT_ID])
+ await waitFor(() =>
+ expect(
+ screen.getByText(
+ 'Miguel is now Read-only on campaigns and marketing and everything inside them.'
+ )
+ )
+ )
+ })
+
+ it('raises exactly ONE strongest ancestor on upgrade', async () => {
+ driveScenario({ campaigns: VIEWER, marketing: VIEWER })
+ const row = await openRoleDialog()
+
+ await chooseRole(row, 'Editor')
+ const dialog = await screen.findByRole('alertdialog')
+ expect(within(dialog).getByText('campaigns')).toBeTruthy()
+ expect(within(dialog).queryByText('marketing')).toBeNull()
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Update role' }))
+
+ await waitFor(() => expect(mockPutGfsGrant).toHaveBeenCalledTimes(1))
+ expect(mockPutGfsGrant).toHaveBeenCalledWith(
+ expect.objectContaining({ resourceId: CMP_ID, permissions: EDITOR, inherit: true })
+ )
+ })
+
+ it('states the true partial outcome when a folder update fails mid-run', async () => {
+ driveScenario({ campaigns: EDITOR, marketing: EDITOR })
+ mockPutGfsGrant.mockImplementation(async body => {
+ if (body.resourceId === MKT_ID) throw grantError(403, 'escalation_rejected')
+ return { ok: true, resourceId: body.resourceId, updated: [], count: 0 }
+ })
+ const row = await openRoleDialog()
+
+ await chooseRole(row, 'Read')
+ const dialog = await screen.findByRole('alertdialog')
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Update role' }))
+
+ // The nearest folder was updated; marketing failed — the toast says
+ // exactly how far the change got and never claims full success.
+ await waitFor(() =>
+ expect(screen.getByText('Updated 1 of 2 folders — marketing still grants access.'))
+ )
+ // The server verdict is surfaced and both lists reload so the dialog
+ // shows the TRUE partial state.
+ const alert = await screen.findByRole('alert')
+ expect(alert.textContent).toContain('escalation_rejected')
+ await waitFor(() => expect(mockGetGfsGrants.mock.calls.length).toBeGreaterThan(2))
+ })
+
+ it('states the true partial outcome when a folder removal fails mid-run', async () => {
+ driveScenario({ campaigns: EDITOR, marketing: EDITOR })
+ mockDeleteGfsGrant.mockImplementation(async id => {
+ if (id === MKT_GRANT_ID) throw grantError(403, 'escalation_rejected')
+ })
+ const row = await openRoleDialog()
+
+ fireEvent.click(within(row).getByRole('button', { name: 'Actions for Miguel' }))
+ fireEvent.click(await screen.findByRole('menuitem', { name: 'Remove access' }))
+ const dialog = await screen.findByRole('alertdialog')
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Remove' }))
+
+ await waitFor(() =>
+ expect(screen.getByText('Removed from 1 of 2 folders — marketing still grants access.'))
+ )
+ expect(mockDeleteGfsGrant).toHaveBeenCalledWith(CMP_GRANT_ID)
+ })
+ })
})
diff --git a/control-ui/components/gfsInheritedAccess.ts b/control-ui/components/gfsInheritedAccess.ts
index adc738c13..454a00212 100644
--- a/control-ui/components/gfsInheritedAccess.ts
+++ b/control-ui/components/gfsInheritedAccess.ts
@@ -5,7 +5,7 @@ import {
getGfsShares,
} from '@lib/api'
import type { GfsSubjectInput } from '@lib/api'
-import type { GfsInheritedAccessItem } from './GfsGrantPanel.types'
+import type { GfsInheritedAccessItem, GfsInheritedAccessSource } from './GfsGrantPanel.types'
/**
* Frontend inheritance derivation for the Share dialog. The grants/shares GETs
@@ -13,10 +13,10 @@ import type { GfsInheritedAccessItem } from './GfsGrantPanel.types'
* inherited access is derived by walking the ancestor folders of the
* resource's canonical path and keeping the rows that apply to descendants
* (grants with inherit=true, shares with includeDescendants=true — the same
- * rule the server's allow() evaluation uses). Rows are merged per subject and
- * each subject keeps the strongest contributing folder as its editable
- * `source` (with the grant/share ids to mutate), so a confirmed change is
- * applied on the folder that configures the access.
+ * rule the server's allow() evaluation uses). Rows are merged per subject;
+ * EVERY contributing ancestor folder is kept as an editable `source` (with
+ * the grant/share ids to mutate), so a confirmed removal revokes all of them
+ * and a confirmed downgrade lowers each one above the target role (R1-H1).
*/
/** `/docs/report.md` → `['/docs', '/']` (nearest ancestor first). */
@@ -39,10 +39,48 @@ function inheritedSubjectKey(subject: GfsSubjectInput): string {
}
/** Editor-strength rows (write/delete/manage_acl) outrank read-only rows. */
-function isEditorPermissions(permissions: string[]): boolean {
+export function isEditorPermissions(permissions: string[]): boolean {
return permissions.some(permission => ['write', 'delete', 'manage_acl'].includes(permission))
}
+/** The strongest contributing folder: editor beats read, nearest among equals. */
+export function strongestInheritedSource(
+ sources: GfsInheritedAccessSource[]
+): GfsInheritedAccessSource | null {
+ return sources.reduce<GfsInheritedAccessSource | null>(
+ (strongest, source) =>
+ strongest === null ||
+ (!isEditorPermissions(strongest.permissions) && isEditorPermissions(source.permissions))
+ ? source
+ : strongest,
+ null
+ )
+}
+
+/**
+ * Which ancestor folders a confirmed role change to `targetRole` must touch
+ * (R1-H1 semantics, verified against Google Drive):
+ * - downgrade: EVERY source whose role is above the target (ancestors at or
+ * below the target stay untouched);
+ * - upgrade: the single strongest source (nearest among equals) — the
+ * effective role is the strongest across sources, so one raise is enough;
+ * - no-op (target equals the effective role): none.
+ */
+export function planInheritedRoleChange(
+ item: Pick<GfsInheritedAccessItem, 'permissions' | 'sources'>,
+ targetRoleIsEditor: boolean
+): GfsInheritedAccessSource[] {
+ const effectiveIsEditor = isEditorPermissions(item.permissions)
+ if (targetRoleIsEditor === effectiveIsEditor) return []
+ if (!targetRoleIsEditor) {
+ // Downgrade: lower every editor source down to Read.
+ return item.sources.filter(source => isEditorPermissions(source.permissions))
+ }
+ // Upgrade: raise the strongest source (nearest among equals) to Editor.
+ const strongest = strongestInheritedSource(item.sources)
+ return strongest ? [strongest] : []
+}
+
/** One inheriting row on an ancestor folder, carrying its mutable row ids. */
interface InheritingRow {
subject: GfsSubjectInput
@@ -122,13 +160,15 @@ export async function loadGfsInheritedAccess(
subject: row.subject,
permissions: [...row.permissions],
inheritedFrom: [folderLabel],
- source: {
- resourceId: folder.resourceId,
- name: folderLabel,
- permissions: [...row.permissions],
- grantId: row.grantId,
- shareIds: [...row.shareIds],
- },
+ sources: [
+ {
+ resourceId: folder.resourceId,
+ name: folderLabel,
+ permissions: [...row.permissions],
+ grantId: row.grantId,
+ shareIds: [...row.shareIds],
+ },
+ ],
})
continue
}
@@ -136,30 +176,23 @@ export async function loadGfsInheritedAccess(
if (!existing.inheritedFrom.includes(folderLabel)) {
existing.inheritedFrom.push(folderLabel)
}
- const sameFolder = existing.source.resourceId === folder.resourceId
+ const sameFolder = existing.sources.find(source => source.resourceId === folder.resourceId)
if (sameFolder) {
// A grant and a share for one subject on the same folder are edited
// together: union the ids so the change consolidates both rows.
- existing.source = {
- ...existing.source,
- permissions: [...new Set([...existing.source.permissions, ...row.permissions])],
- grantId: existing.source.grantId ?? row.grantId,
- shareIds: [...new Set([...existing.source.shareIds, ...row.shareIds])],
- }
- } else if (
- !isEditorPermissions(existing.source.permissions) &&
- isEditorPermissions(row.permissions)
- ) {
- // The editable source is the strongest contributing folder (nearest
- // among equals): editing a weaker ancestor could not change the
- // subject's effective access.
- existing.source = {
+ sameFolder.permissions = [...new Set([...sameFolder.permissions, ...row.permissions])]
+ sameFolder.grantId = sameFolder.grantId ?? row.grantId
+ sameFolder.shareIds = [...new Set([...sameFolder.shareIds, ...row.shareIds])]
+ } else {
+ // R1-H1: keep EVERY contributing ancestor folder — removals revoke
+ // all of them and downgrades lower each one above the target role.
+ existing.sources.push({
resourceId: folder.resourceId,
name: folderLabel,
permissions: [...row.permissions],
grantId: row.grantId,
shareIds: [...row.shareIds],
- }
+ })
}
}
}
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index d2ca01301..5b9fba7e2 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.590",
+ "version": "0.1.591",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.590",
+ "version": "0.1.591",
"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.json
index 2cd46ba7e..7920bbe71 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.590",
+ "version": "0.1.591",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",
diff --git a/desktop-app/ui/src/gfs/GfsInheritedAccessDialog/index.tsx b/desktop-app/ui/src/gfs/GfsInheritedAccessDialog/index.tsx
index 94256820d..58970abf3 100644
--- a/desktop-app/ui/src/gfs/GfsInheritedAccessDialog/index.tsx
+++ b/desktop-app/ui/src/gfs/GfsInheritedAccessDialog/index.tsx
@@ -55,17 +55,10 @@ export function GfsInheritedAccessDialog({
if (!request) return null
const isRemove = request.mode === 'remove'
- const nextLabel = isRemove
- ? request.fileRemainingRole
- ? ROLE_LABELS[request.fileRemainingRole]
- : 'No access'
- : request.nextRole
- ? ROLE_LABELS[request.nextRole]
- : ''
- const parentNextLabel = isRemove ? 'No access' : nextLabel
- const title = isRemove ? 'Remove access on parent folder?' : 'Update role on parent folder?'
+ const nextLabel = isRemove ? 'Remove' : request.nextRole ? ROLE_LABELS[request.nextRole] : ''
+ const title = isRemove ? 'Remove from parent folder?' : 'Update role on parent folder?'
const lead = isRemove
- ? `Removing ${request.memberLabel}'s access to this item will also remove their access on a parent folder.`
+ ? `Removing ${request.memberLabel} from this item will also remove them from a parent folder.`
: `Changing ${request.memberLabel}'s permissions on this item will also change permissions on a parent folder.`
return (
@@ -105,22 +98,22 @@ export function GfsInheritedAccessDialog({
Learn more
</button>
</p>
- <div className="da-gfs-parent-update-dialog__columns">
- <div className="da-gfs-parent-update-dialog__column">
- <span className="da-gfs-parent-update-dialog__name">
- {request.parentFolderName}
- </span>
- <span className="da-gfs-parent-update-dialog__change">
- <span className="da-gfs-parent-update-dialog__role">
- {ROLE_LABELS[request.parentCurrentRole]}
- </span>
- <span aria-hidden="true">→</span>
- <span className="da-gfs-parent-update-dialog__role da-gfs-parent-update-dialog__role--next">
- {parentNextLabel}
+ <div className="da-gfs-parent-update-dialog__folders">
+ {request.folders.map(folder => (
+ <div className="da-gfs-parent-update-dialog__folder" key={folder.name}>
+ <span className="da-gfs-parent-update-dialog__name">{folder.name}</span>
+ <span className="da-gfs-parent-update-dialog__change">
+ <span className="da-gfs-parent-update-dialog__role">
+ {ROLE_LABELS[folder.currentRole]}
+ </span>
+ <span aria-hidden="true">→</span>
+ <span className="da-gfs-parent-update-dialog__role da-gfs-parent-update-dialog__role--next">
+ {nextLabel}
+ </span>
</span>
- </span>
- </div>
- <div className="da-gfs-parent-update-dialog__column">
+ </div>
+ ))}
+ <div className="da-gfs-parent-update-dialog__folder">
<span className="da-gfs-parent-update-dialog__name">{request.fileName}</span>
<span className="da-gfs-parent-update-dialog__change">
<span className="da-gfs-parent-update-dialog__role">
diff --git a/desktop-app/ui/src/gfs/GfsInheritedAccessDialog/types.ts b/desktop-app/ui/src/gfs/GfsInheritedAccessDialog/types.ts
index cbce00bf1..657a001b5 100644
--- a/desktop-app/ui/src/gfs/GfsInheritedAccessDialog/types.ts
+++ b/desktop-app/ui/src/gfs/GfsInheritedAccessDialog/types.ts
@@ -1,20 +1,27 @@
export type GfsInheritedAccessRole = 'read' | 'editor'
+export type GfsInheritedAccessDialogFolder = {
+ name: string
+ /** Role the member holds on that ancestor folder today. */
+ currentRole: GfsInheritedAccessRole
+}
+
export type GfsInheritedAccessDialogRequest = {
- /** 'change-role' confirms a parent-folder role update; 'remove' removes the member from the parent folder. */
+ /** 'change-role' confirms a parent-folder role update; 'remove' removes the member from every contributing ancestor folder. */
mode: 'change-role' | 'remove'
memberLabel: string
- parentFolderName: string
/** The file whose Share dialog opened this confirmation. */
fileName: string
- /** Role the member holds on the parent folder today. */
- parentCurrentRole: GfsInheritedAccessRole
+ /**
+ * Every ancestor folder the confirm will touch (R1-H1): all contributing
+ * folders for a removal, the folders above the target role for a
+ * downgrade, the single raised folder for an upgrade.
+ */
+ folders: GfsInheritedAccessDialogFolder[]
/** Role the member effectively holds on this file today. */
fileCurrentRole: GfsInheritedAccessRole
- /** change-role: the role that will replace parentCurrentRole/fileCurrentRole. */
+ /** change-role: the role that will replace the folders'/file's current role. */
nextRole?: GfsInheritedAccessRole
- /** remove: the direct access that survives on the file, null for none. */
- fileRemainingRole?: GfsInheritedAccessRole | null
}
export interface GfsInheritedAccessDialogProps {
diff --git a/desktop-app/ui/src/gfs/__tests__/GfsGrantList.test.tsx b/desktop-app/ui/src/gfs/__tests__/GfsGrantList.test.tsx
index 8c23213f6..ab3aec73d 100644
--- a/desktop-app/ui/src/gfs/__tests__/GfsGrantList.test.tsx
+++ b/desktop-app/ui/src/gfs/__tests__/GfsGrantList.test.tsx
@@ -223,13 +223,15 @@ describe('GfsGrantList', () => {
subject: { type: 'user', id: 'user-2' },
permissions: ['read', 'write'],
inheritedFrom: ['team-docs'],
- source: {
- resourceId: 'folder-1',
- name: 'team-docs',
- permissions: ['read', 'write'],
- grantId: 'parent-grant-1',
- shareIds: [],
- },
+ sources: [
+ {
+ resourceId: 'folder-1',
+ name: 'team-docs',
+ permissions: ['read', 'write'],
+ grantId: 'parent-grant-1',
+ shareIds: [],
+ },
+ ],
...overrides,
})
diff --git a/desktop-app/ui/src/gfs/__tests__/GfsInheritedAccessDialog.test.tsx b/desktop-app/ui/src/gfs/__tests__/GfsInheritedAccessDialog.test.tsx
index d0f7a17a0..e5c7606b2 100644
--- a/desktop-app/ui/src/gfs/__tests__/GfsInheritedAccessDialog.test.tsx
+++ b/desktop-app/ui/src/gfs/__tests__/GfsInheritedAccessDialog.test.tsx
@@ -12,14 +12,13 @@ describe('GfsInheritedAccessDialog', () => {
const changeRequest = {
mode: 'change-role' as const,
memberLabel: 'Test Two',
- parentFolderName: 'Team folder',
fileName: 'report.txt',
- parentCurrentRole: 'editor' as const,
+ folders: [{ name: 'Team folder', currentRole: 'editor' as const }],
fileCurrentRole: 'editor' as const,
nextRole: 'read' as const,
}
- it('renders the two-column before/after for a role change', () => {
+ it('renders the before/after list for a role change', () => {
render(
<GfsInheritedAccessDialog request={changeRequest} onCancel={vi.fn()} onConfirm={vi.fn()} />
)
@@ -37,17 +36,20 @@ describe('GfsInheritedAccessDialog', () => {
expect(within(dialog).getAllByText('Read')).toHaveLength(2)
})
- it('adapts to removal with the surviving direct role on the file column', () => {
+ // R1-H1 — removal lists EVERY affected folder plus the file, each dropping
+ // to Remove, with Drive's exact wording.
+ it('lists every affected folder for a removal', () => {
render(
<GfsInheritedAccessDialog
request={{
mode: 'remove',
memberLabel: 'Test Two',
- parentFolderName: 'Team folder',
fileName: 'report.txt',
- parentCurrentRole: 'editor',
+ folders: [
+ { name: 'Campaigns', currentRole: 'editor' },
+ { name: 'Marketing', currentRole: 'read' },
+ ],
fileCurrentRole: 'editor',
- fileRemainingRole: 'read',
}}
onCancel={vi.fn()}
onConfirm={vi.fn()}
@@ -55,10 +57,26 @@ describe('GfsInheritedAccessDialog', () => {
)
const dialog = screen.getByRole('alertdialog')
- expect(within(dialog).getByText('Remove access on parent folder?')).toBeTruthy()
- // Parent column drops to No access; the file keeps its direct-only role.
- expect(within(dialog).getAllByText('No access')).toHaveLength(1)
+ expect(within(dialog).getByText('Remove from parent folder?')).toBeTruthy()
+ expect(
+ within(dialog).getByText(
+ /Removing Test Two from this item will also remove them from a parent folder\. Alternatively, create a folder with limited access\./
+ )
+ ).toBeTruthy()
+ // Each affected folder keeps its own current role and drops to Remove…
+ expect(within(dialog).getByText('Campaigns')).toBeTruthy()
+ expect(within(dialog).getByText('Marketing')).toBeTruthy()
+ // …and so does the file (effective role -> Remove).
+ expect(within(dialog).getByText('report.txt')).toBeTruthy()
+ expect(within(dialog).getAllByText('Editor')).toHaveLength(2)
expect(within(dialog).getAllByText('Read')).toHaveLength(1)
+ // Three transitions to Remove: both folders plus the file (the fourth
+ // "Remove" text is the confirm button).
+ expect(
+ within(dialog).getAllByText('Remove', {
+ selector: '.da-gfs-parent-update-dialog__role--next',
+ })
+ ).toHaveLength(3)
expect(within(dialog).getByRole('button', { name: 'Remove' })).toBeTruthy()
})
diff --git a/desktop-app/ui/src/gfs/__tests__/inheritedAccess.test.ts b/desktop-app/ui/src/gfs/__tests__/inheritedAccess.test.ts
index 932d70eb5..d660b8891 100644
--- a/desktop-app/ui/src/gfs/__tests__/inheritedAccess.test.ts
+++ b/desktop-app/ui/src/gfs/__tests__/inheritedAccess.test.ts
@@ -105,26 +105,30 @@ describe('deriveGfsInheritedAccess', () => {
subject: { type: 'user', id: 'miguel' },
permissions: ['read', 'write'],
inheritedFrom: ['team-docs'],
- source: {
- resourceId: FOLDER_ID,
- name: 'team-docs',
- permissions: ['read', 'write'],
- grantId: 'g1',
- shareIds: [],
- },
+ sources: [
+ {
+ resourceId: FOLDER_ID,
+ name: 'team-docs',
+ permissions: ['read', 'write'],
+ grantId: 'g1',
+ shareIds: [],
+ },
+ ],
},
{
subject: { type: 'team', id: 'research' },
permissions: ['read'],
// The root's empty name falls back to the drive label.
inheritedFrom: ['main'],
- source: {
- resourceId: ROOT_ID,
- name: 'main',
- permissions: ['read'],
- grantId: null,
- shareIds: ['s1'],
- },
+ sources: [
+ {
+ resourceId: ROOT_ID,
+ name: 'main',
+ permissions: ['read'],
+ grantId: null,
+ shareIds: ['s1'],
+ },
+ ],
},
])
})
@@ -189,16 +193,24 @@ describe('deriveGfsInheritedAccess', () => {
const merged = items[0]
expect(merged?.permissions.sort()).toEqual(['read', 'share', 'write'])
expect(merged?.inheritedFrom).toEqual(['team-docs', 'main'])
- // The nearest editor folder is the editable source, even though the root
- // also grants read: editing the weaker ancestor could not change the
- // subject's effective access.
- expect(merged?.source).toEqual({
- resourceId: FOLDER_ID,
- name: 'team-docs',
- permissions: ['read', 'write'],
- grantId: `g-${FOLDER_ID}`,
- shareIds: [],
- })
+ // R1-H1: EVERY contributing folder is kept, nearest first — the nearest
+ // editor folder is the upgrade target, both are removal targets.
+ expect(merged?.sources).toEqual([
+ {
+ resourceId: FOLDER_ID,
+ name: 'team-docs',
+ permissions: ['read', 'write'],
+ grantId: `g-${FOLDER_ID}`,
+ shareIds: [],
+ },
+ {
+ resourceId: ROOT_ID,
+ name: 'main',
+ permissions: ['read', 'share'],
+ grantId: `g-${ROOT_ID}`,
+ shareIds: [],
+ },
+ ])
})
it('unions a grant and a share for one subject on the same folder into one source', async () => {
@@ -246,12 +258,14 @@ describe('deriveGfsInheritedAccess', () => {
const items = await deriveGfsInheritedAccess(FILE_ID)
expect(items).toHaveLength(1)
- expect(items[0]?.source).toEqual({
- resourceId: FOLDER_ID,
- name: 'team-docs',
- permissions: ['read', 'write'],
- grantId: 'g1',
- shareIds: ['s1'],
- })
+ expect(items[0]?.sources).toEqual([
+ {
+ resourceId: FOLDER_ID,
+ name: 'team-docs',
+ permissions: ['read', 'write'],
+ grantId: 'g1',
+ shareIds: ['s1'],
+ },
+ ])
})
})
diff --git a/desktop-app/ui/src/gfs/delegation.types.ts b/desktop-app/ui/src/gfs/delegation.types.ts
index 4b0d8a7b3..a692a0a4e 100644
--- a/desktop-app/ui/src/gfs/delegation.types.ts
+++ b/desktop-app/ui/src/gfs/delegation.types.ts
@@ -64,10 +64,12 @@ export interface GfsShareListItem {
}
/**
- * The ancestor folder a subject's inherited access is edited through: the
- * contributing folder with the strongest role (nearest among equals). Its
- * grant/share ids let the Share dialog route a confirmed change to the
- * folder that actually configures the access.
+ * ONE contributing ancestor folder of a subject's inherited access: its
+ * inheriting grant (inherit=true) and/or descendant-covering share
+ * (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.
*/
export interface GfsInheritedAccessSource {
resourceId: string
@@ -79,8 +81,8 @@ export interface GfsInheritedAccessSource {
}
/**
- * An inherited access row: an ancestor folder's inheriting grant
- * (inherit=true) or descendant-covering share (includeDescendants=true),
+ * An inherited access row: the ancestor folders' inheriting grants
+ * (inherit=true) and descendant-covering shares (includeDescendants=true),
* derived on the client because the grants/shares GETs list only direct rows.
* Rendered as a normal toggleable row; every edit routes through the
* parent-folder confirmation.
@@ -90,6 +92,6 @@ export interface GfsInheritedAccessItem {
permissions: string[]
/** Contributing ancestor folder labels, nearest first, deduplicated. */
inheritedFrom: string[]
- /** The folder a confirmed role change or removal is applied to. */
- source: GfsInheritedAccessSource
+ /** Every contributing ancestor folder, nearest first (R1-H1). */
+ sources: GfsInheritedAccessSource[]
}
diff --git a/desktop-app/ui/src/gfs/inheritedAccess.ts b/desktop-app/ui/src/gfs/inheritedAccess.ts
index 2b8df5913..6481d57cd 100644
--- a/desktop-app/ui/src/gfs/inheritedAccess.ts
+++ b/desktop-app/ui/src/gfs/inheritedAccess.ts
@@ -9,10 +9,11 @@ import type { GfsInheritedAccessItem, GfsInheritedAccessSource } from './delegat
* apply to descendants: grants with inherit=true and shares with
* includeDescendants=true — the server's allow() rule. The walk is
* best-effort: ancestors this caller cannot resolve or whose ACL it may not
- * view (view-ACL = manage-ACL server-side) are skipped. Each subject keeps
- * the strongest contributing folder as its editable `source` (with the
- * grant/share ids to mutate), so a confirmed change is applied on the folder
- * that configures the access.
+ * view (view-ACL = manage-ACL server-side) are skipped. Rows are merged per
+ * subject; EVERY contributing ancestor folder is kept as an editable source
+ * (with the grant/share ids to mutate), so a confirmed removal revokes all of
+ * them and a confirmed downgrade lowers each one above the target role
+ * (R1-H1).
*/
const DEFAULT_DRIVE = 'main'
@@ -26,10 +27,48 @@ function subjectKey(subject: { type: string; id?: string }): string {
}
/** Editor-strength rows (write/delete/manage_acl) outrank read-only rows. */
-function isEditorPermissions(permissions: string[]): boolean {
+export function isEditorPermissions(permissions: string[]): boolean {
return permissions.some(permission => ['write', 'delete', 'manage_acl'].includes(permission))
}
+/** The strongest contributing folder: editor beats read, nearest among equals. */
+export function strongestInheritedSource(
+ sources: GfsInheritedAccessSource[]
+): GfsInheritedAccessSource | null {
+ return sources.reduce<GfsInheritedAccessSource | null>(
+ (strongest, source) =>
+ strongest === null ||
+ (!isEditorPermissions(strongest.permissions) && isEditorPermissions(source.permissions))
+ ? source
+ : strongest,
+ null
+ )
+}
+
+/**
+ * Which ancestor folders a confirmed role change to the target role must
+ * touch (R1-H1 semantics, verified against Google Drive):
+ * - downgrade: EVERY source whose role is above the target (ancestors at or
+ * below the target stay untouched);
+ * - upgrade: the single strongest source (nearest among equals) — the
+ * effective role is the strongest across sources, so one raise is enough;
+ * - no-op (target equals the effective role): none.
+ */
+export function planInheritedRoleChange(
+ item: Pick<GfsInheritedAccessItem, 'permissions' | 'sources'>,
+ targetRoleIsEditor: boolean
+): GfsInheritedAccessSource[] {
+ const effectiveIsEditor = isEditorPermissions(item.permissions)
+ if (targetRoleIsEditor === effectiveIsEditor) return []
+ if (!targetRoleIsEditor) {
+ // Downgrade: lower every editor source down to Read.
+ return item.sources.filter(source => isEditorPermissions(source.permissions))
+ }
+ // Upgrade: raise the strongest source (nearest among equals) to Editor.
+ const strongest = strongestInheritedSource(item.sources)
+ return strongest ? [strongest] : []
+}
+
interface InheritingRow {
subject: { type: string; id?: string }
permissions: string[]
@@ -37,20 +76,6 @@ interface InheritingRow {
shareIds: string[]
}
-function sourceFor(
- row: InheritingRow,
- folderResourceId: string,
- folderLabel: string
-): GfsInheritedAccessSource {
- return {
- resourceId: folderResourceId,
- name: folderLabel,
- permissions: [...row.permissions],
- grantId: row.grantId,
- shareIds: [...row.shareIds],
- }
-}
-
function mergeInto(
bySubject: Map<string, GfsInheritedAccessItem>,
row: InheritingRow,
@@ -64,7 +89,15 @@ function mergeInto(
subject: row.subject,
permissions: [...row.permissions],
inheritedFrom: [folderLabel],
- source: sourceFor(row, folderResourceId, folderLabel),
+ sources: [
+ {
+ resourceId: folderResourceId,
+ name: folderLabel,
+ permissions: [...row.permissions],
+ grantId: row.grantId,
+ shareIds: [...row.shareIds],
+ },
+ ],
})
return
}
@@ -72,23 +105,23 @@ function mergeInto(
if (!existing.inheritedFrom.includes(folderLabel)) {
existing.inheritedFrom.push(folderLabel)
}
- if (existing.source.resourceId === folderResourceId) {
+ const sameFolder = existing.sources.find(source => source.resourceId === folderResourceId)
+ if (sameFolder) {
// A grant and a share for one subject on the same folder are edited
// together: union the ids so the change consolidates both rows.
- existing.source = {
- ...existing.source,
- permissions: [...new Set([...existing.source.permissions, ...row.permissions])],
- grantId: existing.source.grantId ?? row.grantId,
- shareIds: [...new Set([...existing.source.shareIds, ...row.shareIds])],
- }
- } else if (
- !isEditorPermissions(existing.source.permissions) &&
- isEditorPermissions(row.permissions)
- ) {
- // The editable source is the strongest contributing folder (nearest
- // among equals): editing a weaker ancestor could not change the
- // subject's effective access.
- existing.source = sourceFor(row, folderResourceId, folderLabel)
+ sameFolder.permissions = [...new Set([...sameFolder.permissions, ...row.permissions])]
+ sameFolder.grantId = sameFolder.grantId ?? row.grantId
+ sameFolder.shareIds = [...new Set([...sameFolder.shareIds, ...row.shareIds])]
+ } else {
+ // R1-H1: keep EVERY contributing ancestor folder — removals revoke all
+ // of them and downgrades lower each one above the target role.
+ existing.sources.push({
+ resourceId: folderResourceId,
+ name: folderLabel,
+ permissions: [...row.permissions],
+ grantId: row.grantId,
+ shareIds: [...row.shareIds],
+ })
}
}
diff --git a/desktop-app/ui/src/pages/FilesPage.tsx b/desktop-app/ui/src/pages/FilesPage.tsx
index ae86ebb96..8eb693be0 100644
--- a/desktop-app/ui/src/pages/FilesPage.tsx
+++ b/desktop-app/ui/src/pages/FilesPage.tsx
@@ -55,7 +55,9 @@ import {
type GfsDelegationSubjectOption,
type GfsGrantListItem,
} from '@/gfs/delegation'
+import type { GfsInheritedAccessSource } from '@/gfs/delegation.types'
import { GfsFilePicker } from '@/gfs/filePicker'
+import { planInheritedRoleChange } from '@/gfs/inheritedAccess'
import { GfsMoveDialog } from '@/gfs/moveDialog'
import type { TeamDirectoryResult } from '../../../src/types'
import type {
@@ -75,13 +77,17 @@ function roleForAccessPermissions(permissions: string[]): GfsAccessRole {
? 'editor'
: 'read'
}
-
/** The permission set a role stands for: hosts cap at read/write. */
function rolePermissionRequest(subjectType: string, role: GfsAccessRole): string[] {
if (subjectType === 'host') return role === 'editor' ? ['read', 'write'] : ['read']
return role === 'editor' ? ['read', 'write', 'delete', 'manage_acl', 'share'] : ['read', 'share']
}
+/** ["a", "b", "c"] → "a, b and c" — folder names for honest outcome toasts. */
+function joinFolderNames(names: string[]): string {
+ if (names.length <= 1) return names[0] ?? ''
+ return `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`
+}
function hasDraggedFiles(event: ReactDragEvent<HTMLElement>): boolean {
return Array.from(event.dataTransfer.types || []).includes('Files')
}
@@ -244,15 +250,16 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
const [shareDetailsOpen, setShareDetailsOpen] = useState(false)
const [updatingAccessRole, setUpdatingAccessRole] = useState(false)
// Pending parent-folder confirmation (role change or removal) for a member
- // whose file access is inherited from an ancestor folder. change-role
- // carries the bits the pre-flight validated on the parent folder itself.
+ // 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.
const [parentUpdate, setParentUpdate] = useState<
| {
row: GfsMergedAccessRow
label: string
mode: 'change-role'
nextRole: GfsAccessRole
- parentBits: string[]
+ updates: Array<{ source: GfsInheritedAccessSource; bits: string[] }>
}
| { row: GfsMergedAccessRow; label: string; mode: 'remove' }
| null
@@ -590,9 +597,9 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
}
}
- // A merged row whose access comes from a parent folder: any edit (upgrade,
- // downgrade, or removal — no exceptions) is confirmed against the parent
- // folder before anything is sent. Cancel reverts the dropdown untouched.
+ // A merged row whose access comes from parent folders: any edit (upgrade,
+ // downgrade, or removal — no exceptions) is confirmed against the affected
+ // folders before anything is sent. Cancel reverts the dropdown untouched.
const handleInheritedRoleChange = async (
row: GfsMergedAccessRow,
label: string,
@@ -600,35 +607,40 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
) => {
const inherited = row.inherited
if (!inherited) return
- const source = inherited.source
const subject = inherited.subject
- // Pre-flight: the parent grant is judged by the PARENT folder's own
- // grantable bits, never by the open file's affordances (which may be
- // missing or narrower). A role the folder cannot grant fails loudly here
- // — the confirmation never opens with a promise it cannot keep.
- let folderAffordances: { canDelegate: boolean; grantableBits: string[] }
- try {
- folderAffordances = await window.clerum.gfs.affordances(source.resourceId, GFS_DRIVE_MAIN)
- } catch (affordancesError) {
- if (failClosedOnAuthorizationError(affordancesError)) return
- pushToast?.(describeGfsGrantError(affordancesError).message, 'error')
- return
- }
- const parentBits = rolePermissionRequest(subject.type, role).filter(bit =>
- folderAffordances.grantableBits.includes(bit)
- )
- const expressesRole =
- role === 'editor'
- ? parentBits.includes('read') && parentBits.includes('write')
- : parentBits.includes('read')
- if (!folderAffordances.canDelegate || !expressesRole) {
- pushToast?.(
- `Your access on ${source.name} does not allow making ${label} ${role === 'editor' ? 'an Editor' : 'Read-only'}.`,
- 'error'
+ // 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
+ // 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) {
+ let folderAffordances: { canDelegate: boolean; grantableBits: string[] }
+ try {
+ folderAffordances = await window.clerum.gfs.affordances(source.resourceId, GFS_DRIVE_MAIN)
+ } catch (affordancesError) {
+ if (failClosedOnAuthorizationError(affordancesError)) return
+ pushToast?.(describeGfsGrantError(affordancesError).message, 'error')
+ return
+ }
+ const bits = rolePermissionRequest(subject.type, role).filter(bit =>
+ folderAffordances.grantableBits.includes(bit)
)
- return
+ const expressesRole =
+ role === 'editor' ? bits.includes('read') && bits.includes('write') : bits.includes('read')
+ if (!folderAffordances.canDelegate || !expressesRole) {
+ pushToast?.(
+ `Your access on ${source.name} does not allow making ${label} ${role === 'editor' ? 'an Editor' : 'Read-only'}.`,
+ 'error'
+ )
+ return
+ }
+ updates.push({ source, bits })
}
- setParentUpdate({ row, label, mode: 'change-role', nextRole: role, parentBits })
+ setParentUpdate({ row, label, mode: 'change-role', nextRole: role, updates })
}
const handleInheritedRemove = (row: GfsMergedAccessRow, label: string) => {
@@ -642,49 +654,104 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
setParentUpdate(null)
return
}
- const source = inherited.source
+ const sources = inherited.sources
const subject = inherited.subject
const subjectKey = subject.id ? `${subject.type}:${subject.id}` : subject.type
const label = request.label
setParentUpdate(null)
setUpdatingAccessRole(true)
+ // Partial-failure honesty (R1-H1): the confirm issues several sequential
+ // calls; the first failure stops the run, refreshes both lists so the
+ // dialog shows the TRUE partial state, and the toast says exactly how far
+ // the change got. Full success is never claimed on partial completion.
+ const failPartially = async (updateError: unknown, summary: string) => {
+ if (failClosedOnAuthorizationError(updateError)) return
+ pushToast?.(`${summary} (${describeGfsGrantError(updateError).message})`, 'error')
+ await Promise.all([ctrl.refreshGrants(), ctrl.refreshInheritedAccess()])
+ }
try {
- if (request.mode === 'change-role') {
- // The parent folder's grant is updated first with the bits the
- // pre-flight validated on the folder itself, and keeps cascading to
- // everything inside; its superseded share rows are consolidated.
- await window.clerum.gfs.grant(
- source.resourceId,
- [subjectKey],
- request.parentBits,
- GFS_DRIVE_MAIN,
- true
- )
- for (const shareId of source.shareIds) await ctrl.revokeShare(shareId)
- // 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.mode === 'remove') {
+ let removed = 0
+ for (const source of sources) {
+ try {
+ if (source.grantId) await ctrl.revokeGrant(source.grantId)
+ for (const shareId of source.shareIds) await ctrl.revokeShare(shareId)
+ removed += 1
+ } catch (updateError) {
+ await failPartially(
+ updateError,
+ `Removed from ${removed} of ${sources.length} folders — ${source.name} still grants access`
+ )
+ return
+ }
+ }
+ // The file's own direct rows are aligned with the removal.
if (request.row.grant || request.row.shares.length > 0) {
+ try {
+ if (request.row.grant) await ctrl.revokeGrant(request.row.grant.id)
+ for (const share of request.row.shares) await ctrl.revokeShare(share.id)
+ } catch (updateError) {
+ await failPartially(
+ updateError,
+ `Removed from ${sources.length} of ${sources.length} folders — direct access on ${current?.name ?? 'this file'} could not be removed`
+ )
+ return
+ }
+ }
+ pushToast?.(
+ sources.length === 1
+ ? `Access removed on ${sources[0].name} and everything inside it`
+ : `Access removed on ${sources.length} folders and everything inside them`,
+ 'success'
+ )
+ await Promise.all([ctrl.refreshGrants(), ctrl.refreshInheritedAccess()])
+ return
+ }
+ const updates = request.updates
+ const affectedNames = updates.map(update => update.source.name)
+ let updated = 0
+ 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)
+ updated += 1
+ } catch (updateError) {
+ await failPartially(
+ updateError,
+ `Updated ${updated} of ${updates.length} folders — ${source.name} still grants access`
+ )
+ 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) {
+ try {
const fileBits = rolePermissionRequest(subject.type, request.nextRole).filter(bit =>
affordances?.grantableBits.includes(bit)
)
await ctrl.grant([subjectKey], fileBits, request.row.grant?.inherit ?? false)
for (const share of request.row.shares) await ctrl.revokeShare(share.id)
+ } catch (updateError) {
+ await failPartially(
+ updateError,
+ `Updated ${updates.length} of ${updates.length} folders — direct access on ${current?.name ?? 'this file'} still shows the old role`
+ )
+ return
}
- pushToast?.(
- `${label} is now ${request.nextRole === 'editor' ? 'an Editor' : 'Read-only'} on ${source.name} and everything inside it`,
- 'success'
- )
- } else {
- if (source.grantId) await ctrl.revokeGrant(source.grantId)
- for (const shareId of source.shareIds) await ctrl.revokeShare(shareId)
- pushToast?.(`Access removed on ${source.name} and everything inside it`, 'success')
}
+ 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()])
- } catch (updateError) {
- if (failClosedOnAuthorizationError(updateError)) return
- pushToast?.(describeGfsGrantError(updateError).message, 'error')
} finally {
setUpdatingAccessRole(false)
}
@@ -1882,21 +1949,21 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
? {
mode: parentUpdate.mode,
memberLabel: parentUpdate.label,
- parentFolderName: parentUpdate.row.inherited.source.name,
fileName: current?.name ?? '',
- parentCurrentRole: roleForAccessPermissions(
- parentUpdate.row.inherited.source.permissions
- ),
+ // Removal touches every contributing folder; a role change
+ // touches only the R1-H1 plan's affected folders.
+ folders:
+ parentUpdate.mode === 'remove'
+ ? parentUpdate.row.inherited.sources.map(source => ({
+ name: source.name,
+ currentRole: roleForAccessPermissions(source.permissions),
+ }))
+ : parentUpdate.updates.map(update => ({
+ name: update.source.name,
+ currentRole: roleForAccessPermissions(update.source.permissions),
+ })),
fileCurrentRole: roleForAccessPermissions(parentUpdate.row.permissions),
nextRole: parentUpdate.mode === 'change-role' ? parentUpdate.nextRole : undefined,
- fileRemainingRole:
- parentUpdate.mode === 'remove' &&
- (parentUpdate.row.grant || parentUpdate.row.shares.length > 0)
- ? roleForAccessPermissions([
- ...(parentUpdate.row.grant?.permissions ?? []),
- ...parentUpdate.row.shares.flatMap(share => share.permissions),
- ])
- : null,
}
: null
}
diff --git a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
index 32ce0e2d3..1cb5aca6e 100644
--- a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
@@ -1697,13 +1697,15 @@ describe('FilesPage', () => {
subject: { type: 'user', id: 'user-2' },
permissions: ['read', 'write'],
inheritedFrom: ['Team folder'],
- source: {
- resourceId: 'folder-1',
- name: 'Team folder',
- permissions: ['read', 'write'],
- grantId: 'parent-grant-1',
- shareIds: [],
- },
+ sources: [
+ {
+ resourceId: 'folder-1',
+ name: 'Team folder',
+ permissions: ['read', 'write'],
+ grantId: 'parent-grant-1',
+ shareIds: [],
+ },
+ ],
},
],
...overrides,
@@ -1960,7 +1962,28 @@ describe('FilesPage', () => {
)
const parentGrant = (window.clerum.gfs as { grant: ReturnType<typeof vi.fn> }).grant
const pushToast = vi.fn()
- hookMock.useGfsBrowserController.mockReturnValue(inheritedFileController())
+ // Read-only inherited floor: upgrading to Editor must be judged against
+ // the folder, which cannot grant write.
+ hookMock.useGfsBrowserController.mockReturnValue(
+ inheritedFileController({
+ inheritedAccess: [
+ {
+ subject: { type: 'user', id: 'user-2' },
+ permissions: ['read'],
+ inheritedFrom: ['Team folder'],
+ sources: [
+ {
+ resourceId: 'folder-1',
+ name: 'Team folder',
+ permissions: ['read'],
+ grantId: 'parent-grant-1',
+ shareIds: [],
+ },
+ ],
+ },
+ ],
+ })
+ )
renderFilesPage(pushToast)
await openManageDialog('report.txt')
@@ -1986,7 +2009,7 @@ describe('FilesPage', () => {
// The dropdown reverts to the server-backed role.
expect(
within(row).getByRole('button', { name: 'Access role for Test Two' }).textContent
- ).toContain('Editor')
+ ).toContain('Read')
})
// R1-M3 — a total derivation failure must not silently read as "no one".
@@ -2032,7 +2055,7 @@ describe('FilesPage', () => {
const confirmDialog = await screen.findByRole('alertdialog')
expect(
- within(confirmDialog).getByText('Remove access on parent folder?', { selector: 'h3' })
+ within(confirmDialog).getByText('Remove from parent folder?', { selector: 'h3' })
).toBeTruthy()
await act(async () => {
fireEvent.click(within(confirmDialog).getByRole('button', { name: 'Remove' }))
@@ -2041,6 +2064,232 @@ describe('FilesPage', () => {
await waitFor(() => expect(revokeGrant).toHaveBeenCalledWith('parent-grant-1'))
})
+ // R1-H1 — Drive-aligned multi-ancestor semantics. Reference scenario:
+ // Marketing (Viewer) → Campaigns (Editor) → report.txt.
+ describe('R1-H1 multi-ancestor edits', () => {
+ const CAMPAIGNS = {
+ resourceId: 'folder-cmp',
+ name: 'Campaigns',
+ permissions: ['read', 'write'],
+ grantId: 'cmp-grant-1',
+ shareIds: [],
+ }
+ const MARKETING = {
+ resourceId: 'folder-mkt',
+ name: 'Marketing',
+ permissions: ['read', 'share'],
+ grantId: 'mkt-grant-1',
+ shareIds: [],
+ }
+ const EDITOR_PERMISSIONS = ['read', 'write', 'delete', 'manage_acl', 'share']
+
+ function multiSourceController(
+ sources: Array<typeof CAMPAIGNS>,
+ overrides: Record<string, unknown> = {}
+ ) {
+ const permissions = [...new Set(sources.flatMap(source => source.permissions))]
+ return inheritedFileController({
+ grants: [],
+ inheritedAccess: [
+ {
+ subject: { type: 'user', id: 'user-2' },
+ permissions,
+ inheritedFrom: sources.map(source => source.name),
+ sources,
+ },
+ ],
+ ...overrides,
+ })
+ }
+
+ async function openMultiSourceRow(
+ sources: Array<typeof CAMPAIGNS>,
+ pushToast?: (message: string, tone: Tone) => void
+ ) {
+ 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')
+ return row
+ }
+
+ it('removes the member from every contributing ancestor and aligns the file rows', async () => {
+ installInheritedDirectoryMocks()
+ const revokeGrant = vi.fn(async () => undefined)
+ const revokeShare = vi.fn(async () => undefined)
+ const pushToast = vi.fn()
+ const directShare = {
+ id: 'file-share-1',
+ drive: 'main',
+ resourceId: 'file-1',
+ subject: { type: 'user', id: 'user-2' },
+ permissions: ['read', 'write'],
+ includeDescendants: false,
+ }
+ hookMock.useGfsBrowserController.mockReturnValue(
+ multiSourceController([CAMPAIGNS, MARKETING], {
+ revokeGrant,
+ revokeShare,
+ shares: [directShare],
+ })
+ )
+
+ const row = await openMultiSourceRow([CAMPAIGNS, MARKETING], pushToast)
+ await act(async () => {
+ fireEvent.click(within(row).getByRole('button', { name: 'Actions for Test Two' }))
+ })
+ await act(async () => {
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Remove access' }))
+ })
+
+ const confirmDialog = await screen.findByRole('alertdialog')
+ expect(within(confirmDialog).getByText('Remove from parent folder?', { selector: 'h3' }))
+ // Every affected folder is listed with its own current role.
+ expect(within(confirmDialog).getByText('Campaigns')).toBeTruthy()
+ expect(within(confirmDialog).getByText('Marketing')).toBeTruthy()
+ expect(within(confirmDialog).getByText('report.txt')).toBeTruthy()
+ await act(async () => {
+ fireEvent.click(within(confirmDialog).getByRole('button', { name: 'Remove' }))
+ })
+
+ // Both ancestors' grants are revoked…
+ await waitFor(() => expect(revokeGrant).toHaveBeenCalledWith('cmp-grant-1'))
+ await waitFor(() => expect(revokeGrant).toHaveBeenCalledWith('mkt-grant-1'))
+ // …and the file's own direct share is aligned with the removal.
+ await waitFor(() => expect(revokeShare).toHaveBeenCalledWith('file-share-1'))
+ await waitFor(() =>
+ expect(pushToast).toHaveBeenCalledWith(
+ 'Access removed on 2 folders and everything inside them',
+ 'success'
+ )
+ )
+ })
+
+ it('downgrades only the ancestors above the target role', async () => {
+ installInheritedDirectoryMocks()
+ const parentGrant = (window.clerum.gfs as { grant: ReturnType<typeof vi.fn> }).grant
+ const pushToast = vi.fn()
+ // Marketing is already at Read; Campaigns sits above the target.
+ hookMock.useGfsBrowserController.mockReturnValue(
+ multiSourceController([CAMPAIGNS, MARKETING])
+ )
+
+ const row = await openMultiSourceRow([CAMPAIGNS, MARKETING], pushToast)
+ 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' }))
+ })
+
+ const confirmDialog = await screen.findByRole('alertdialog')
+ expect(within(confirmDialog).getByText('Campaigns')).toBeTruthy()
+ expect(within(confirmDialog).queryByText('Marketing')).toBeNull()
+ await act(async () => {
+ fireEvent.click(within(confirmDialog).getByRole('button', { name: 'Update role' }))
+ })
+
+ // Exactly one folder mutation: the editor source is lowered, the
+ // read-only source stays untouched.
+ await waitFor(() => expect(parentGrant).toHaveBeenCalledTimes(1))
+ expect(parentGrant).toHaveBeenCalledWith(
+ 'folder-cmp',
+ ['user:user-2'],
+ ['read', 'share'],
+ 'main',
+ true
+ )
+ await waitFor(() =>
+ expect(pushToast).toHaveBeenCalledWith(
+ 'Test Two is now Read-only on Campaigns and everything inside it',
+ 'success'
+ )
+ )
+ })
+
+ it('raises exactly one strongest ancestor on upgrade', async () => {
+ installInheritedDirectoryMocks()
+ const parentGrant = (window.clerum.gfs as { grant: ReturnType<typeof vi.fn> }).grant
+ const readCampaigns = { ...CAMPAIGNS, permissions: ['read', 'share'] }
+ const readMarketing = { ...MARKETING }
+ hookMock.useGfsBrowserController.mockReturnValue(
+ multiSourceController([readCampaigns, readMarketing])
+ )
+
+ const row = await openMultiSourceRow([readCampaigns, readMarketing])
+ await act(async () => {
+ fireEvent.click(within(row).getByRole('button', { name: 'Access role for Test Two' }))
+ })
+ await act(async () => {
+ fireEvent.click(screen.getByRole('option', { name: 'Editor' }))
+ })
+
+ const confirmDialog = await screen.findByRole('alertdialog')
+ expect(within(confirmDialog).getByText('Campaigns')).toBeTruthy()
+ expect(within(confirmDialog).queryByText('Marketing')).toBeNull()
+ await act(async () => {
+ fireEvent.click(within(confirmDialog).getByRole('button', { name: 'Update role' }))
+ })
+
+ // One raise on the nearest source is enough: effective = strongest.
+ await waitFor(() => expect(parentGrant).toHaveBeenCalledTimes(1))
+ expect(parentGrant).toHaveBeenCalledWith(
+ 'folder-cmp',
+ ['user:user-2'],
+ EDITOR_PERMISSIONS,
+ 'main',
+ true
+ )
+ })
+
+ it('states the true partial outcome when a folder removal fails mid-run', async () => {
+ installInheritedDirectoryMocks()
+ const revokeGrant = vi.fn(async (grantId: string) => {
+ if (grantId === 'mkt-grant-1') {
+ throw new Error('403 Forbidden: escalation_rejected')
+ }
+ })
+ const refreshGrants = vi.fn(async () => undefined)
+ const refreshInheritedAccess = vi.fn(async () => undefined)
+ const pushToast = vi.fn()
+ hookMock.useGfsBrowserController.mockReturnValue(
+ multiSourceController([CAMPAIGNS, MARKETING], {
+ revokeGrant,
+ refreshGrants,
+ refreshInheritedAccess,
+ })
+ )
+
+ const row = await openMultiSourceRow([CAMPAIGNS, MARKETING], pushToast)
+ await act(async () => {
+ fireEvent.click(within(row).getByRole('button', { name: 'Actions for Test Two' }))
+ })
+ await act(async () => {
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Remove access' }))
+ })
+ const confirmDialog = await screen.findByRole('alertdialog')
+ await act(async () => {
+ fireEvent.click(within(confirmDialog).getByRole('button', { name: 'Remove' }))
+ })
+
+ // The nearest folder was removed; Marketing failed — the toast says
+ // exactly how far the removal got, and both lists refresh to the TRUE
+ // partial state.
+ await waitFor(() =>
+ expect(pushToast).toHaveBeenCalledWith(
+ expect.stringContaining('Removed from 1 of 2 folders — Marketing still grants access'),
+ 'error'
+ )
+ )
+ expect(pushToast).not.toHaveBeenCalledWith(
+ 'Access removed on 2 folders and everything inside them',
+ 'success'
+ )
+ await waitFor(() => expect(refreshGrants).toHaveBeenCalled())
+ await waitFor(() => expect(refreshInheritedAccess).toHaveBeenCalled())
+ })
+ })
+
it('does not render resource options inside the share dialog', async () => {
Object.defineProperty(window, 'clerum', {
configurable: true,
diff --git a/desktop-app/ui/src/styles.css b/desktop-app/ui/src/styles.css
index a3c107471..221356777 100644
--- a/desktop-app/ui/src/styles.css
+++ b/desktop-app/ui/src/styles.css
@@ -16316,16 +16316,18 @@ pre {
outline-offset: 2px;
}
-.da-gfs-parent-update-dialog__columns {
+/* R1-H1: every affected ancestor folder plus the file, stacked. */
+.da-gfs-parent-update-dialog__folders {
display: grid;
- grid-template-columns: repeat(2, minmax(0, 1fr));
- gap: var(--space-2);
+ gap: var(--space-1);
}
-.da-gfs-parent-update-dialog__column {
- display: grid;
- gap: var(--space-1);
- padding: var(--space-3);
+.da-gfs-parent-update-dialog__folder {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-2);
+ padding: var(--space-2) var(--space-3);
border: 1px solid rgba(var(--edge-rgb), 0.32);
border-radius: var(--radius-lg);
background: var(--bg);