Skip to content

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

TypeScript

refactor(evendrive): extract pure inherited-access merge core with property tests (R1-M2)

Mf72911ef2818
diff --git a/control-ui/components/__tests__/gfsInheritedAccessMerge.prop.test.ts b/control-ui/components/__tests__/gfsInheritedAccessMerge.prop.test.ts
new file mode 100644
index 000000000..2cdc25ab3
--- /dev/null
+++ b/control-ui/components/__tests__/gfsInheritedAccessMerge.prop.test.ts
@@ -0,0 +1,220 @@
+import { describe, expect, it } from 'vitest'
+import fc from 'fast-check'
+import type { GfsInheritedAccessSource } from '../GfsGrantPanel.types'
+import {
+ type InheritedAccessContribution,
+ type InheritedAccessFolder,
+ isEditorPermissions,
+ mergeInheritedAccessItem,
+ planInheritedRoleChange,
+ roleRank,
+ strongestInheritedSource,
+} from '../gfsInheritedAccessMerge'
+
+/**
+ * R1-M2 — property suite for the pure inherited-access merge core:
+ * merge idempotency, no source dropped, effective role = strongest of
+ * sources, and a total role order.
+ */
+
+const PERMISSION_BITS = ['read', 'write', 'delete', 'manage_acl', 'share'] as const
+
+const permissionsArb = fc.uniqueArray(fc.constantFrom(...PERMISSION_BITS), {
+ minLength: 1,
+ maxLength: PERMISSION_BITS.length,
+})
+
+const subjectArb = fc.record({
+ type: fc.constantFrom('user', 'team', 'host'),
+ id: fc.string({ minLength: 1, maxLength: 8 }),
+})
+
+const idArb = fc.option(fc.string({ minLength: 1, maxLength: 12 }), { nil: null })
+
+const contributionArb = fc
+ .tuple(
+ subjectArb,
+ permissionsArb,
+ idArb,
+ fc.uniqueArray(fc.string({ minLength: 1, maxLength: 12 }))
+ )
+ .map(([subject, permissions, grantId, shareIds]) => ({
+ subject,
+ permissions,
+ grantId,
+ shareIds,
+ }))
+
+const distinctFoldersArb = fc.uniqueArray(
+ fc.record({
+ resourceId: fc.string({ minLength: 1, maxLength: 10 }),
+ name: fc.string({ minLength: 1, maxLength: 10 }),
+ }),
+ {
+ selector: folder => folder.resourceId,
+ minLength: 1,
+ maxLength: 6,
+ }
+)
+
+describe('gfsInheritedAccessMerge properties', () => {
+ it('merge is idempotent: merge(merge(a, b), b) == merge(a, b)', () => {
+ fc.assert(
+ fc.property(
+ contributionArb,
+ contributionArb,
+ distinctFoldersArb,
+ distinctFoldersArb,
+ (seed, repeat, seedFolders, repeatFolders) => {
+ const seedFolder = seedFolders[0]
+ const repeatFolder = repeatFolders[0]
+ const a = mergeInheritedAccessItem(null, seed, seedFolder)
+ const once = mergeInheritedAccessItem(a, repeat, repeatFolder)
+ const twice = mergeInheritedAccessItem(once, repeat, repeatFolder)
+ expect(twice).toEqual(once)
+ }
+ ),
+ { numRuns: 300 }
+ )
+ })
+
+ it('merging the same contribution twice changes nothing', () => {
+ fc.assert(
+ fc.property(contributionArb, distinctFoldersArb, (contribution, folders) => {
+ const once = mergeInheritedAccessItem(null, contribution, folders[0])
+ const twice = mergeInheritedAccessItem(once, contribution, folders[0])
+ expect(twice).toEqual(once)
+ }),
+ { numRuns: 300 }
+ )
+ })
+
+ it('never drops a source: every contributing folder survives the fold', () => {
+ fc.assert(
+ fc.property(
+ subjectArb,
+ distinctFoldersArb,
+ fc.array(permissionsArb, { minLength: 0, maxLength: 8 }),
+ (subject, folders, permissionSets) => {
+ let item = mergeInheritedAccessItem(
+ null,
+ { subject, permissions: permissionSets[0] ?? ['read'], grantId: null, shareIds: [] },
+ folders[0]
+ )
+ folders.slice(1).forEach((folder, index) => {
+ item = mergeInheritedAccessItem(
+ item,
+ {
+ subject,
+ permissions: permissionSets[(index + 1) % Math.max(permissionSets.length, 1)] ?? [
+ 'read',
+ ],
+ grantId: null,
+ shareIds: [],
+ },
+ folder
+ )
+ })
+ expect(new Set(item.sources.map(source => source.resourceId))).toEqual(
+ new Set(folders.map(folder => folder.resourceId))
+ )
+ }
+ ),
+ { numRuns: 300 }
+ )
+ })
+
+ it('effective role is the strongest of the kept sources', () => {
+ fc.assert(
+ fc.property(
+ subjectArb,
+ distinctFoldersArb,
+ fc.array(permissionsArb, { minLength: 1, maxLength: 8 }),
+ (subject, folders, permissionSets) => {
+ let item: ReturnType<typeof mergeInheritedAccessItem> | null = null
+ folders.forEach((folder, index) => {
+ item = mergeInheritedAccessItem(
+ item,
+ {
+ subject,
+ permissions: permissionSets[index % permissionSets.length],
+ grantId: null,
+ shareIds: [],
+ },
+ folder
+ )
+ })
+ const merged = item as NonNullable<typeof item>
+ const strongestRank = Math.max(
+ ...merged.sources.map(source => roleRank(source.permissions))
+ )
+ expect(roleRank(merged.permissions)).toBe(strongestRank)
+ expect(isEditorPermissions(merged.permissions)).toBe(
+ merged.sources.some(source => isEditorPermissions(source.permissions))
+ )
+ }
+ ),
+ { numRuns: 300 }
+ )
+ })
+
+ it('role order is total: any two permission sets compare exactly once, and max is order-independent', () => {
+ fc.assert(
+ fc.property(permissionsArb, permissionsArb, (left, right) => {
+ const leftRank = roleRank(left)
+ const rightRank = roleRank(right)
+ const comparisons = [leftRank < rightRank, leftRank === rightRank, leftRank > rightRank]
+ expect(comparisons.filter(Boolean)).toHaveLength(1)
+
+ const toSource = (permissions: string[]): GfsInheritedAccessSource => ({
+ resourceId: 'r',
+ name: 'r',
+ permissions,
+ grantId: null,
+ shareIds: [],
+ })
+ const forward = strongestInheritedSource([toSource(left), toSource(right)])
+ const backward = strongestInheritedSource([toSource(right), toSource(left)])
+ expect(roleRank(forward?.permissions ?? [])).toBe(roleRank(backward?.permissions ?? []))
+ }),
+ { numRuns: 300 }
+ )
+ })
+
+ it('the R1-H1 plan never drops an above-target source', () => {
+ fc.assert(
+ fc.property(
+ distinctFoldersArb,
+ fc.array(permissionsArb, { minLength: 1, maxLength: 8 }),
+ (folders, permissionSets) => {
+ const sources: GfsInheritedAccessSource[] = folders.map((folder, index) => ({
+ resourceId: folder.resourceId,
+ name: folder.name,
+ permissions: permissionSets[index % permissionSets.length],
+ grantId: null,
+ shareIds: [],
+ }))
+ const permissions = [...new Set(sources.flatMap(source => source.permissions))]
+ const item = { permissions, sources }
+ const editorSources = sources.filter(source => isEditorPermissions(source.permissions))
+ const readSources = sources.filter(source => !isEditorPermissions(source.permissions))
+
+ const downgrade = planInheritedRoleChange(item, false)
+ expect(downgrade).toHaveLength(editorSources.length)
+
+ const upgrade = planInheritedRoleChange(item, true)
+ if (isEditorPermissions(permissions)) {
+ expect(upgrade).toHaveLength(0)
+ } else {
+ expect(upgrade).toHaveLength(1)
+ }
+
+ const noOp = planInheritedRoleChange(item, isEditorPermissions(permissions))
+ expect(noOp).toHaveLength(0)
+ expect(readSources.length + editorSources.length).toBe(sources.length)
+ }
+ ),
+ { numRuns: 300 }
+ )
+ })
+})
diff --git a/control-ui/components/gfsInheritedAccess.ts b/control-ui/components/gfsInheritedAccess.ts
index 454a00212..2642e9719 100644
--- a/control-ui/components/gfsInheritedAccess.ts
+++ b/control-ui/components/gfsInheritedAccess.ts
@@ -4,8 +4,10 @@ import {
getGfsResourceByPath,
getGfsShares,
} from '@lib/api'
-import type { GfsSubjectInput } from '@lib/api'
-import type { GfsInheritedAccessItem, GfsInheritedAccessSource } from './GfsGrantPanel.types'
+import type { GfsInheritedAccessItem } from './GfsGrantPanel.types'
+import { inheritedSubjectKey, mergeInheritedAccessItem } from './gfsInheritedAccessMerge'
+
+export { planInheritedRoleChange, strongestInheritedSource } from './gfsInheritedAccessMerge'
/**
* Frontend inheritance derivation for the Share dialog. The grants/shares GETs
@@ -13,10 +15,12 @@ import type { GfsInheritedAccessItem, GfsInheritedAccessSource } from './GfsGran
* 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;
- * 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).
+ * rule the server's allow() evaluation uses). Rows are merged per subject
+ * through the pure merge core (`gfsInheritedAccessMerge.ts`, property tested
+ * in R1-M2); 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). */
@@ -33,57 +37,8 @@ export function gfsAncestorPaths(path: string): string[] {
return ancestors
}
-/** Stable per-subject merge key. Mirrors the panel's direct-row subject key. */
-function inheritedSubjectKey(subject: GfsSubjectInput): string {
- return `${subject.type}:${'id' in subject ? subject.id : ''}`
-}
-
-/** Editor-strength rows (write/delete/manage_acl) outrank read-only rows. */
-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
+ subject: { type: string; id?: string }
permissions: string[]
grantId: string | null
shareIds: string[]
@@ -154,46 +109,13 @@ export async function loadGfsInheritedAccess(
const folderLabel = folder.name || drive
for (const row of rows) {
const key = inheritedSubjectKey(row.subject)
- const existing = bySubject.get(key)
- if (!existing) {
- bySubject.set(key, {
- subject: row.subject,
- permissions: [...row.permissions],
- inheritedFrom: [folderLabel],
- sources: [
- {
- resourceId: folder.resourceId,
- name: folderLabel,
- permissions: [...row.permissions],
- grantId: row.grantId,
- shareIds: [...row.shareIds],
- },
- ],
- })
- continue
- }
- existing.permissions = [...new Set([...existing.permissions, ...row.permissions])]
- if (!existing.inheritedFrom.includes(folderLabel)) {
- existing.inheritedFrom.push(folderLabel)
- }
- 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.
- 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({
+ bySubject.set(
+ key,
+ mergeInheritedAccessItem(bySubject.get(key) ?? null, row, {
resourceId: folder.resourceId,
name: folderLabel,
- permissions: [...row.permissions],
- grantId: row.grantId,
- shareIds: [...row.shareIds],
})
- }
+ )
}
}
// Every ancestor path failed to resolve: the derivation as a whole
diff --git a/control-ui/components/gfsInheritedAccessMerge.ts b/control-ui/components/gfsInheritedAccessMerge.ts
new file mode 100644
index 000000000..014be52a4
--- /dev/null
+++ b/control-ui/components/gfsInheritedAccessMerge.ts
@@ -0,0 +1,130 @@
+import type { GfsSubjectInput } from '@lib/api'
+import type { GfsInheritedAccessItem, GfsInheritedAccessSource } from './GfsGrantPanel.types'
+
+/**
+ * Pure merge core for the client-side inherited-access derivation (R1-M2).
+ * No network — everything here is a function of its inputs, which is what
+ * the fast-check property suite in
+ * `__tests__/gfsInheritedAccessMerge.prop.test.ts` relies on: merge
+ * idempotency, no source dropped, effective role = strongest of sources,
+ * and a total role order.
+ */
+
+/** Stable per-subject merge key. Mirrors the panel's direct-row subject key. */
+export function inheritedSubjectKey(subject: { type: string; id?: string }): string {
+ return `${subject.type}:${subject.id ?? ''}`
+}
+
+/** Editor-strength rows (write/delete/manage_acl) outrank read-only rows. */
+export function isEditorPermissions(permissions: string[]): boolean {
+ return permissions.some(permission => ['write', 'delete', 'manage_acl'].includes(permission))
+}
+
+/** Total role order over permission sets: Read (0) < Editor (1). */
+export function roleRank(permissions: string[]): number {
+ return isEditorPermissions(permissions) ? 1 : 0
+}
+
+/** 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 || roleRank(strongest.permissions) < roleRank(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] : []
+}
+
+/** One inheriting row on an ancestor folder, carrying its mutable row ids. */
+export interface InheritedAccessContribution {
+ subject: { type: string; id?: string }
+ permissions: string[]
+ grantId: string | null
+ shareIds: string[]
+}
+
+/** The ancestor folder a contribution was collected from. */
+export interface InheritedAccessFolder {
+ resourceId: string
+ name: string
+}
+
+/**
+ * Folds one inheriting row into a subject's derived access item (creating it
+ * on first sight). Pure: never mutates its inputs. EVERY contributing folder
+ * is kept as an editable source (R1-H1); a grant and a share for one subject
+ * on the same folder consolidate into one source (unioned permissions and
+ * row ids) so a confirmed edit mutates them together.
+ */
+export function mergeInheritedAccessItem(
+ current: GfsInheritedAccessItem | null,
+ contribution: InheritedAccessContribution,
+ folder: InheritedAccessFolder
+): GfsInheritedAccessItem {
+ if (current === null) {
+ return {
+ subject: contribution.subject as GfsSubjectInput,
+ permissions: [...contribution.permissions],
+ inheritedFrom: [folder.name],
+ sources: [
+ {
+ resourceId: folder.resourceId,
+ name: folder.name,
+ permissions: [...contribution.permissions],
+ grantId: contribution.grantId,
+ shareIds: [...contribution.shareIds],
+ },
+ ],
+ }
+ }
+ const next: GfsInheritedAccessItem = {
+ ...current,
+ permissions: [...new Set([...current.permissions, ...contribution.permissions])],
+ inheritedFrom: current.inheritedFrom.includes(folder.name)
+ ? [...current.inheritedFrom]
+ : [...current.inheritedFrom, folder.name],
+ sources: current.sources.map(source => ({ ...source, shareIds: [...source.shareIds] })),
+ }
+ const sameFolder = next.sources.find(source => source.resourceId === folder.resourceId)
+ if (sameFolder) {
+ sameFolder.permissions = [...new Set([...sameFolder.permissions, ...contribution.permissions])]
+ sameFolder.grantId = sameFolder.grantId ?? contribution.grantId
+ sameFolder.shareIds = [...new Set([...sameFolder.shareIds, ...contribution.shareIds])]
+ } else {
+ next.sources.push({
+ resourceId: folder.resourceId,
+ name: folder.name,
+ permissions: [...contribution.permissions],
+ grantId: contribution.grantId,
+ shareIds: [...contribution.shareIds],
+ })
+ }
+ return next
+}
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index 5b9fba7e2..aa6fe2991 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.591",
+ "version": "0.1.592",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.591",
+ "version": "0.1.592",
"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 7920bbe71..a2f38f71b 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.591",
+ "version": "0.1.592",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",
diff --git a/desktop-app/ui/src/gfs/__tests__/inheritedAccessMerge.prop.test.ts b/desktop-app/ui/src/gfs/__tests__/inheritedAccessMerge.prop.test.ts
new file mode 100644
index 000000000..bbe004f68
--- /dev/null
+++ b/desktop-app/ui/src/gfs/__tests__/inheritedAccessMerge.prop.test.ts
@@ -0,0 +1,221 @@
+// @vitest-environment jsdom
+import { describe, expect, it } from 'vitest'
+import fc from 'fast-check'
+import type { GfsInheritedAccessSource } from '../delegation.types'
+import {
+ type InheritedAccessContribution,
+ type InheritedAccessFolder,
+ isEditorPermissions,
+ mergeInheritedAccessItem,
+ planInheritedRoleChange,
+ roleRank,
+ strongestInheritedSource,
+} from '../inheritedAccessMerge'
+
+/**
+ * R1-M2 — property suite for the pure inherited-access merge core:
+ * merge idempotency, no source dropped, effective role = strongest of
+ * sources, and a total role order.
+ */
+
+const PERMISSION_BITS = ['read', 'write', 'delete', 'manage_acl', 'share'] as const
+
+const permissionsArb = fc.uniqueArray(fc.constantFrom(...PERMISSION_BITS), {
+ minLength: 1,
+ maxLength: PERMISSION_BITS.length,
+})
+
+const subjectArb = fc.record({
+ type: fc.constantFrom('user', 'team', 'host'),
+ id: fc.option(fc.string({ minLength: 1, maxLength: 8 }), { nil: undefined }),
+})
+
+const idArb = fc.option(fc.string({ minLength: 1, maxLength: 12 }), { nil: null })
+
+const contributionArb = fc
+ .tuple(
+ subjectArb,
+ permissionsArb,
+ idArb,
+ fc.uniqueArray(fc.string({ minLength: 1, maxLength: 12 }))
+ )
+ .map(([subject, permissions, grantId, shareIds]) => ({
+ subject,
+ permissions,
+ grantId,
+ shareIds,
+ }))
+
+const distinctFoldersArb = fc.uniqueArray(
+ fc.record({
+ resourceId: fc.string({ minLength: 1, maxLength: 10 }),
+ name: fc.string({ minLength: 1, maxLength: 10 }),
+ }),
+ {
+ selector: folder => folder.resourceId,
+ minLength: 1,
+ maxLength: 6,
+ }
+)
+
+describe('inheritedAccessMerge properties', () => {
+ it('merge is idempotent: merge(merge(a, b), b) == merge(a, b)', () => {
+ fc.assert(
+ fc.property(
+ contributionArb,
+ contributionArb,
+ distinctFoldersArb,
+ distinctFoldersArb,
+ (seed, repeat, seedFolders, repeatFolders) => {
+ const seedFolder = seedFolders[0]
+ const repeatFolder = repeatFolders[0]
+ const a = mergeInheritedAccessItem(null, seed, seedFolder)
+ const once = mergeInheritedAccessItem(a, repeat, repeatFolder)
+ const twice = mergeInheritedAccessItem(once, repeat, repeatFolder)
+ expect(twice).toEqual(once)
+ }
+ ),
+ { numRuns: 300 }
+ )
+ })
+
+ it('merging the same contribution twice changes nothing', () => {
+ fc.assert(
+ fc.property(contributionArb, distinctFoldersArb, (contribution, folders) => {
+ const once = mergeInheritedAccessItem(null, contribution, folders[0])
+ const twice = mergeInheritedAccessItem(once, contribution, folders[0])
+ expect(twice).toEqual(once)
+ }),
+ { numRuns: 300 }
+ )
+ })
+
+ it('never drops a source: every contributing folder survives the fold', () => {
+ fc.assert(
+ fc.property(
+ subjectArb,
+ distinctFoldersArb,
+ fc.array(permissionsArb, { minLength: 0, maxLength: 8 }),
+ (subject, folders, permissionSets) => {
+ let item = mergeInheritedAccessItem(
+ null,
+ { subject, permissions: permissionSets[0] ?? ['read'], grantId: null, shareIds: [] },
+ folders[0]
+ )
+ folders.slice(1).forEach((folder, index) => {
+ item = mergeInheritedAccessItem(
+ item,
+ {
+ subject,
+ permissions: permissionSets[(index + 1) % Math.max(permissionSets.length, 1)] ?? [
+ 'read',
+ ],
+ grantId: null,
+ shareIds: [],
+ },
+ folder
+ )
+ })
+ expect(new Set(item.sources.map(source => source.resourceId))).toEqual(
+ new Set(folders.map(folder => folder.resourceId))
+ )
+ }
+ ),
+ { numRuns: 300 }
+ )
+ })
+
+ it('effective role is the strongest of the kept sources', () => {
+ fc.assert(
+ fc.property(
+ subjectArb,
+ distinctFoldersArb,
+ fc.array(permissionsArb, { minLength: 1, maxLength: 8 }),
+ (subject, folders, permissionSets) => {
+ let item: ReturnType<typeof mergeInheritedAccessItem> | null = null
+ folders.forEach((folder, index) => {
+ item = mergeInheritedAccessItem(
+ item,
+ {
+ subject,
+ permissions: permissionSets[index % permissionSets.length],
+ grantId: null,
+ shareIds: [],
+ },
+ folder
+ )
+ })
+ const merged = item as NonNullable<typeof item>
+ const strongestRank = Math.max(
+ ...merged.sources.map(source => roleRank(source.permissions))
+ )
+ expect(roleRank(merged.permissions)).toBe(strongestRank)
+ expect(isEditorPermissions(merged.permissions)).toBe(
+ merged.sources.some(source => isEditorPermissions(source.permissions))
+ )
+ }
+ ),
+ { numRuns: 300 }
+ )
+ })
+
+ it('role order is total: any two permission sets compare exactly once, and max is order-independent', () => {
+ fc.assert(
+ fc.property(permissionsArb, permissionsArb, (left, right) => {
+ const leftRank = roleRank(left)
+ const rightRank = roleRank(right)
+ const comparisons = [leftRank < rightRank, leftRank === rightRank, leftRank > rightRank]
+ expect(comparisons.filter(Boolean)).toHaveLength(1)
+
+ const toSource = (permissions: string[]): GfsInheritedAccessSource => ({
+ resourceId: 'r',
+ name: 'r',
+ permissions,
+ grantId: null,
+ shareIds: [],
+ })
+ const forward = strongestInheritedSource([toSource(left), toSource(right)])
+ const backward = strongestInheritedSource([toSource(right), toSource(left)])
+ expect(roleRank(forward?.permissions ?? [])).toBe(roleRank(backward?.permissions ?? []))
+ }),
+ { numRuns: 300 }
+ )
+ })
+
+ it('the R1-H1 plan never drops an above-target source', () => {
+ fc.assert(
+ fc.property(
+ distinctFoldersArb,
+ fc.array(permissionsArb, { minLength: 1, maxLength: 8 }),
+ (folders, permissionSets) => {
+ const sources: GfsInheritedAccessSource[] = folders.map((folder, index) => ({
+ resourceId: folder.resourceId,
+ name: folder.name,
+ permissions: permissionSets[index % permissionSets.length],
+ grantId: null,
+ shareIds: [],
+ }))
+ const permissions = [...new Set(sources.flatMap(source => source.permissions))]
+ const item = { permissions, sources }
+ const editorSources = sources.filter(source => isEditorPermissions(source.permissions))
+ const readSources = sources.filter(source => !isEditorPermissions(source.permissions))
+
+ const downgrade = planInheritedRoleChange(item, false)
+ expect(downgrade).toHaveLength(editorSources.length)
+
+ const upgrade = planInheritedRoleChange(item, true)
+ if (isEditorPermissions(permissions)) {
+ expect(upgrade).toHaveLength(0)
+ } else {
+ expect(upgrade).toHaveLength(1)
+ }
+
+ const noOp = planInheritedRoleChange(item, isEditorPermissions(permissions))
+ expect(noOp).toHaveLength(0)
+ expect(readSources.length + editorSources.length).toBe(sources.length)
+ }
+ ),
+ { numRuns: 300 }
+ )
+ })
+})
diff --git a/desktop-app/ui/src/gfs/inheritedAccess.ts b/desktop-app/ui/src/gfs/inheritedAccess.ts
index 6481d57cd..6a64d117d 100644
--- a/desktop-app/ui/src/gfs/inheritedAccess.ts
+++ b/desktop-app/ui/src/gfs/inheritedAccess.ts
@@ -1,5 +1,8 @@
import { GFS_BREADCRUMB_MAX_DEPTH } from '@constants/gfsBrowser'
-import type { GfsInheritedAccessItem, GfsInheritedAccessSource } from './delegation.types'
+import type { GfsInheritedAccessItem } from './delegation.types'
+import { inheritedSubjectKey, mergeInheritedAccessItem } from './inheritedAccessMerge'
+
+export { planInheritedRoleChange, strongestInheritedSource } from './inheritedAccessMerge'
/**
* Derives the inherited access for one resource on the client. The user-plane
@@ -10,10 +13,10 @@ import type { GfsInheritedAccessItem, GfsInheritedAccessSource } from './delegat
* 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. 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).
+ * subject through the pure merge core (`inheritedAccessMerge.ts`, property
+ * tested in R1-M2); EVERY contributing ancestor folder is kept as an editable
+ * source, 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'
@@ -22,109 +25,6 @@ function ridOf(resourceId: string): string {
return resourceId.replace(/-/g, '').toLowerCase()
}
-function subjectKey(subject: { type: string; id?: string }): string {
- return `${subject.type}:${subject.id ?? ''}`
-}
-
-/** Editor-strength rows (write/delete/manage_acl) outrank read-only rows. */
-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[]
- grantId: string | null
- shareIds: string[]
-}
-
-function mergeInto(
- bySubject: Map<string, GfsInheritedAccessItem>,
- row: InheritingRow,
- folderResourceId: string,
- folderLabel: string
-): void {
- const key = subjectKey(row.subject)
- const existing = bySubject.get(key)
- if (!existing) {
- bySubject.set(key, {
- subject: row.subject,
- permissions: [...row.permissions],
- inheritedFrom: [folderLabel],
- sources: [
- {
- resourceId: folderResourceId,
- name: folderLabel,
- permissions: [...row.permissions],
- grantId: row.grantId,
- shareIds: [...row.shareIds],
- },
- ],
- })
- return
- }
- existing.permissions = [...new Set([...existing.permissions, ...row.permissions])]
- if (!existing.inheritedFrom.includes(folderLabel)) {
- existing.inheritedFrom.push(folderLabel)
- }
- 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.
- 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],
- })
- }
-}
-
export async function deriveGfsInheritedAccess(
resourceId: string,
drive: string = DEFAULT_DRIVE
@@ -157,31 +57,11 @@ export async function deriveGfsInheritedAccess(
])
for (const grant of grants) {
if (!grant.inherit) continue
- mergeInto(
- bySubject,
- {
- subject: grant.subject,
- permissions: grant.permissions,
- grantId: grant.id,
- shareIds: [],
- },
- parent.resourceId,
- folderLabel
- )
+ merge(grant.subject, grant.permissions, grant.id, [], parent.resourceId, folderLabel)
}
for (const share of shares) {
if (!share.includeDescendants) continue
- mergeInto(
- bySubject,
- {
- subject: share.subject,
- permissions: share.permissions,
- grantId: null,
- shareIds: [share.id],
- },
- parent.resourceId,
- folderLabel
- )
+ merge(share.subject, share.permissions, null, [share.id], parent.resourceId, folderLabel)
}
} catch {
// Viewing an ancestor's ACL requires manage_acl on it; an ancestor
@@ -192,4 +72,24 @@ export async function deriveGfsInheritedAccess(
}
return [...bySubject.values()]
+
+ /** Folds one inheriting row into the per-subject map via the pure core. */
+ function merge(
+ subject: { type: string; id?: string },
+ permissions: string[],
+ grantId: string | null,
+ shareIds: string[],
+ folderResourceId: string,
+ folderLabel: string
+ ): void {
+ const key = inheritedSubjectKey(subject)
+ bySubject.set(
+ key,
+ mergeInheritedAccessItem(
+ bySubject.get(key) ?? null,
+ { subject, permissions, grantId, shareIds },
+ { resourceId: folderResourceId, name: folderLabel }
+ )
+ )
+ }
}
diff --git a/desktop-app/ui/src/gfs/inheritedAccessMerge.ts b/desktop-app/ui/src/gfs/inheritedAccessMerge.ts
new file mode 100644
index 000000000..f9db5a11e
--- /dev/null
+++ b/desktop-app/ui/src/gfs/inheritedAccessMerge.ts
@@ -0,0 +1,128 @@
+import type { GfsInheritedAccessItem, GfsInheritedAccessSource } from './delegation.types'
+
+/**
+ * Pure merge core for the client-side inherited-access derivation (R1-M2).
+ * No window, no network — everything here is a function of its inputs, which
+ * is what the fast-check property suite in `__tests__/inheritedAccessMerge.prop.test.ts`
+ * relies on: merge idempotency, no source dropped, effective role = strongest
+ * of sources, and a total role order.
+ */
+
+/** Stable per-subject merge key. */
+export function inheritedSubjectKey(subject: { type: string; id?: string }): string {
+ return `${subject.type}:${subject.id ?? ''}`
+}
+
+/** Editor-strength rows (write/delete/manage_acl) outrank read-only rows. */
+export function isEditorPermissions(permissions: string[]): boolean {
+ return permissions.some(permission => ['write', 'delete', 'manage_acl'].includes(permission))
+}
+
+/** Total role order over permission sets: Read (0) < Editor (1). */
+export function roleRank(permissions: string[]): number {
+ return isEditorPermissions(permissions) ? 1 : 0
+}
+
+/** 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 || roleRank(strongest.permissions) < roleRank(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] : []
+}
+
+/** One inheriting row on an ancestor folder, carrying its mutable row ids. */
+export interface InheritedAccessContribution {
+ subject: { type: string; id?: string }
+ permissions: string[]
+ grantId: string | null
+ shareIds: string[]
+}
+
+/** The ancestor folder a contribution was collected from. */
+export interface InheritedAccessFolder {
+ resourceId: string
+ name: string
+}
+
+/**
+ * Folds one inheriting row into a subject's derived access item (creating it
+ * on first sight). Pure: never mutates its inputs. EVERY contributing folder
+ * is kept as an editable source (R1-H1); a grant and a share for one subject
+ * on the same folder consolidate into one source (unioned permissions and
+ * row ids) so a confirmed edit mutates them together.
+ */
+export function mergeInheritedAccessItem(
+ current: GfsInheritedAccessItem | null,
+ contribution: InheritedAccessContribution,
+ folder: InheritedAccessFolder
+): GfsInheritedAccessItem {
+ if (current === null) {
+ return {
+ subject: contribution.subject,
+ permissions: [...contribution.permissions],
+ inheritedFrom: [folder.name],
+ sources: [
+ {
+ resourceId: folder.resourceId,
+ name: folder.name,
+ permissions: [...contribution.permissions],
+ grantId: contribution.grantId,
+ shareIds: [...contribution.shareIds],
+ },
+ ],
+ }
+ }
+ const next: GfsInheritedAccessItem = {
+ ...current,
+ permissions: [...new Set([...current.permissions, ...contribution.permissions])],
+ inheritedFrom: current.inheritedFrom.includes(folder.name)
+ ? [...current.inheritedFrom]
+ : [...current.inheritedFrom, folder.name],
+ sources: current.sources.map(source => ({ ...source, shareIds: [...source.shareIds] })),
+ }
+ const sameFolder = next.sources.find(source => source.resourceId === folder.resourceId)
+ if (sameFolder) {
+ sameFolder.permissions = [...new Set([...sameFolder.permissions, ...contribution.permissions])]
+ sameFolder.grantId = sameFolder.grantId ?? contribution.grantId
+ sameFolder.shareIds = [...new Set([...sameFolder.shareIds, ...contribution.shareIds])]
+ } else {
+ next.sources.push({
+ resourceId: folder.resourceId,
+ name: folder.name,
+ permissions: [...contribution.permissions],
+ grantId: contribution.grantId,
+ shareIds: [...contribution.shareIds],
+ })
+ }
+ return next
+}