Skip to content

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

TypeScript

feat(gfs): shared inherited-access policy in gfs-interaction-policy

Md9ea0962334a
diff --git a/packages/gfs-interaction-policy/index.cjs b/packages/gfs-interaction-policy/index.cjs
index 4efb1d660..cf7ec677f 100644
--- a/packages/gfs-interaction-policy/index.cjs
+++ b/packages/gfs-interaction-policy/index.cjs
@@ -182,6 +182,7 @@ module.exports = {
...require('./fileClassifier.cjs'),
...require('./fileReference.cjs'),
...require('./dragPolicy.cjs'),
+ ...require('./inheritedAccess.cjs'),
GFS_RESOURCE_NAME_MAX_LENGTH,
GFS_UPLOAD_NAME_EXHAUSTED_MESSAGE,
GFS_UPLOAD_NAME_RETRY_LIMIT,
diff --git a/packages/gfs-interaction-policy/index.d.ts b/packages/gfs-interaction-policy/index.d.ts
index e54516128..a9ea10b07 100644
--- a/packages/gfs-interaction-policy/index.d.ts
+++ b/packages/gfs-interaction-policy/index.d.ts
@@ -1,5 +1,6 @@
export * from './fileClassifier'
export * from './fileReference'
+export * from './inheritedAccess'
export * from './dragPolicy'
export declare const GFS_RESOURCE_NAME_MAX_LENGTH: number
diff --git a/packages/gfs-interaction-policy/inheritedAccess.cjs b/packages/gfs-interaction-policy/inheritedAccess.cjs
new file mode 100644
index 000000000..c1ccbeb8a
--- /dev/null
+++ b/packages/gfs-interaction-policy/inheritedAccess.cjs
@@ -0,0 +1,282 @@
+'use strict'
+
+/**
+ * Pure, browser-safe inherited-access policy shared by Control UI and Desktop.
+ * Coverage classification, per-subject source merging (every contributing row
+ * preserved with its own scope flags), and the scoped role-edit planner.
+ * Transports, presentation, and caches stay inside each application.
+ */
+
+const GFS_INHERITED_WALK_MAX_DEPTH = 64
+const GFS_RETRY_AFTER_MAX_SECONDS = 300
+
+/** Stable per-subject merge key (`operator` carries no id). */
+function gfsSubjectKeyOf(subject) {
+ return `${subject.type}:${subject.id ?? ''}`
+}
+
+/**
+ * `/docs/report.md` → `['/docs', '/']` (nearest ancestor first, depth-capped).
+ * Segment boundaries are literal path splits; no ancestor id is inferred.
+ */
+function gfsAncestorPathsOf(path) {
+ const segments = (path.startsWith('/') ? path : `/${path}`)
+ .split('/')
+ .filter(segment => segment.length > 0)
+ if (segments.length === 0) return []
+ const ancestors = []
+ for (let count = segments.length - 1; count > 0; count -= 1) {
+ ancestors.push(`/${segments.slice(0, count).join('/')}`)
+ }
+ ancestors.push('/')
+ return ancestors.slice(0, GFS_INHERITED_WALK_MAX_DEPTH)
+}
+
+function isObject(value) {
+ return value !== null && typeof value === 'object'
+}
+
+/**
+ * Best-effort HTTP status of a failed read. Explicit structured status wins
+ * (Control UI `ApiError.status`); the `httpStatus=` marker appended by the
+ * Desktop main process and a leading `NNN` status line follow.
+ */
+function gfsHttpStatusOf(error) {
+ const details = isObject(error) ? error : null
+ const structured = details?.status ?? details?.response?.status
+ if (structured !== undefined) {
+ const structuredNumber = Number(structured)
+ if (Number.isInteger(structuredNumber)) return structuredNumber
+ }
+ const message = error instanceof Error ? error.message : String(error ?? '')
+ const marker = message.match(/\bhttpStatus=(\d{3})\b/)
+ if (marker) return Number(marker[1])
+ const leading = message.match(/^\s*(\d{3})\b/)
+ if (leading) return Number(leading[1])
+ return null
+}
+
+/** Trailing vetted `retryAfterSeconds=N` marker, clamped to 300 s. */
+function gfsRetryAfterSecondsOf(error) {
+ const message = error instanceof Error ? error.message : String(error ?? '')
+ const match = message.match(/\bretryAfterSeconds=(\d+)\s*$/)
+ if (!match) return null
+ return Math.min(Number(match[1]), GFS_RETRY_AFTER_MAX_SECONDS)
+}
+
+/**
+ * Classify one failed ancestor/target ACL or resolve read:
+ * - 'denied' 403 — an expected privacy boundary (view-ACL = manage-ACL),
+ * never a session failure and never identities to reveal.
+ * - 'missing' 404/410 — the folder is gone (moved/tombstoned).
+ * - 'rate-limited' 429 — stop the walk, keep partial truth, retry later.
+ * - 'retryable' transient transport (408/425/5xx/network).
+ * - 'error' anything unexpected.
+ */
+function classifyGfsAclReadFailure(error) {
+ const status = gfsHttpStatusOf(error)
+ if (status !== null) {
+ if (status === 403 || status === 401) return 'denied'
+ if (status === 404 || status === 410) return 'missing'
+ if (status === 429) return 'rate-limited'
+ if (status === 408 || status === 425 || status >= 500) return 'retryable'
+ return 'error'
+ }
+ if (error instanceof TypeError) return 'retryable'
+ const message = error instanceof Error ? error.message : String(error ?? '')
+ if (/\bnetwork\b|\bfetch\b|\btimeout\b|\btimed out\b|\bsocket\b|\bconnection\b/i.test(message)) {
+ return 'retryable'
+ }
+ return 'error'
+}
+
+/** Editor-strength rows (write/delete/manage_acl) outrank read-only rows. */
+function isEditorGfsPermissions(permissions) {
+ return (permissions ?? []).some(permission =>
+ ['write', 'delete', 'manage_acl'].includes(permission)
+ )
+}
+
+/** Total role order over permission sets: Read (0) < Editor (1). */
+function gfsRoleRank(permissions) {
+ return isEditorGfsPermissions(permissions) ? 1 : 0
+}
+
+/** The strongest contributing folder: editor beats read, nearest among equals. */
+function strongestGfsInheritedSource(sources) {
+ return (sources ?? []).reduce(
+ (strongest, source) =>
+ strongest === null || gfsRoleRank(strongest.permissions) < gfsRoleRank(source.permissions)
+ ? source
+ : strongest,
+ null
+ )
+}
+
+/**
+ * Fold one contributing ACL row into a subject's derived access item (creating
+ * it on first sight). Pure: never mutates its inputs. EVERY contributing
+ * folder is kept as a source; a grant and a share for one subject on the same
+ * folder consolidate into one source while their row ids, bits, and scope
+ * flags (inherit / includeDescendants) stay separately recorded — no OR'd
+ * coverage is ever written back from this model.
+ */
+function mergeGfsInheritedAccessItem(current, contribution, folder) {
+ const contributionPermissions = [...(contribution.permissions ?? [])]
+ if (current === null) {
+ return {
+ subject: contribution.subject,
+ permissions: [...contributionPermissions],
+ inheritedFrom: [folder.name],
+ sources: [
+ {
+ resourceId: folder.resourceId,
+ name: folder.name,
+ permissions: [...contributionPermissions],
+ grantId: contribution.rowKind === 'grant' ? contribution.rowId : null,
+ shareIds: contribution.rowKind === 'share' ? [contribution.rowId] : [],
+ grantPermissions: contribution.rowKind === 'grant' ? [...contributionPermissions] : null,
+ grantInherit: contribution.rowKind === 'grant' ? Boolean(contribution.inherit) : null,
+ shareEntries:
+ contribution.rowKind === 'share'
+ ? [
+ {
+ rowId: contribution.rowId,
+ permissions: [...contributionPermissions],
+ includeDescendants: Boolean(contribution.includeDescendants),
+ },
+ ]
+ : [],
+ },
+ ],
+ }
+ }
+ const next = {
+ ...current,
+ permissions: [...new Set([...current.permissions, ...contributionPermissions])],
+ inheritedFrom: current.inheritedFrom.includes(folder.name)
+ ? [...current.inheritedFrom]
+ : [...current.inheritedFrom, folder.name],
+ sources: current.sources.map(source => ({
+ ...source,
+ shareIds: [...source.shareIds],
+ shareEntries: source.shareEntries.map(entry => ({ ...entry })),
+ })),
+ }
+ const sameFolder = next.sources.find(source => source.resourceId === folder.resourceId)
+ if (sameFolder) {
+ sameFolder.permissions = [...new Set([...sameFolder.permissions, ...contributionPermissions])]
+ if (contribution.rowKind === 'grant') {
+ sameFolder.grantId = sameFolder.grantId ?? contribution.rowId
+ sameFolder.grantPermissions = [...contributionPermissions]
+ sameFolder.grantInherit = Boolean(contribution.inherit)
+ } else {
+ sameFolder.shareIds = [...new Set([...sameFolder.shareIds, contribution.rowId])]
+ sameFolder.shareEntries = [
+ ...sameFolder.shareEntries.filter(entry => entry.rowId !== contribution.rowId),
+ {
+ rowId: contribution.rowId,
+ permissions: [...contributionPermissions],
+ includeDescendants: Boolean(contribution.includeDescendants),
+ },
+ ]
+ }
+ } else {
+ next.sources.push({
+ resourceId: folder.resourceId,
+ name: folder.name,
+ permissions: [...contributionPermissions],
+ grantId: contribution.rowKind === 'grant' ? contribution.rowId : null,
+ shareIds: contribution.rowKind === 'share' ? [contribution.rowId] : [],
+ grantPermissions: contribution.rowKind === 'grant' ? [...contributionPermissions] : null,
+ grantInherit: contribution.rowKind === 'grant' ? Boolean(contribution.inherit) : null,
+ shareEntries:
+ contribution.rowKind === 'share'
+ ? [
+ {
+ rowId: contribution.rowId,
+ permissions: [...contributionPermissions],
+ includeDescendants: Boolean(contribution.includeDescendants),
+ },
+ ]
+ : [],
+ })
+ }
+ return next
+}
+
+/**
+ * Which ancestor-folder sources a confirmed role change to the target role
+ * must touch, split by what this release may edit:
+ * - `grantSources`: folder rows backed by a stored grant. A role edit rewrites
+ * exactly these rows, each preserving its own `grantInherit` scope flag.
+ * - `shareOnlySources`: folder rows whose only contribution is a URI share.
+ * Shares are view/remove-only in this release, so a downgrade cannot lower
+ * them; callers must disclose that residual access instead of deleting or
+ * rewriting the share.
+ * Plan semantics (R1-H1): downgrade = every editor-strength source above the
+ * target; upgrade = the single strongest source (nearest among equals); a
+ * no-op (target equals the effective role) touches nothing.
+ */
+function planGfsInheritedRoleChange(item, targetRoleIsEditor) {
+ const sources = item.sources ?? []
+ const effectiveIsEditor = isEditorGfsPermissions(item.permissions)
+ if (targetRoleIsEditor === effectiveIsEditor) {
+ return { grantSources: [], shareOnlySources: [] }
+ }
+ if (!targetRoleIsEditor) {
+ const editorSources = sources.filter(source => isEditorGfsPermissions(source.permissions))
+ return {
+ grantSources: editorSources.filter(source => source.grantId !== null),
+ shareOnlySources: editorSources.filter(source => source.grantId === null),
+ }
+ }
+ const strongest = strongestGfsInheritedSource(sources)
+ if (strongest === null) return { grantSources: [], shareOnlySources: [] }
+ if (strongest.grantId !== null) return { grantSources: [strongest], shareOnlySources: [] }
+ // The strongest contributor is a share this release cannot edit; raise the
+ // strongest grant-backed source instead and disclose the share residual.
+ const grantBacked = sources.filter(source => source.grantId !== null)
+ const strongestGrant = strongestGfsInheritedSource(grantBacked) ?? null
+ return {
+ grantSources: strongestGrant ? [strongestGrant] : [],
+ shareOnlySources: [strongest],
+ }
+}
+
+const GFS_COVERAGE_PRECEDENCE = [
+ 'error',
+ 'rate-limited',
+ 'retryable',
+ 'missing',
+ 'denied',
+ 'depth-cap',
+ 'complete',
+]
+
+/** Worst-first combination of walk-segment classifications for one status. */
+function worstGfsCoverageClass(classifications) {
+ let worst = 'complete'
+ for (const classification of classifications) {
+ if (GFS_COVERAGE_PRECEDENCE.indexOf(classification) < GFS_COVERAGE_PRECEDENCE.indexOf(worst)) {
+ worst = classification
+ }
+ }
+ return worst
+}
+
+module.exports = {
+ GFS_INHERITED_WALK_MAX_DEPTH,
+ GFS_RETRY_AFTER_MAX_SECONDS,
+ classifyGfsAclReadFailure,
+ gfsAncestorPathsOf,
+ gfsHttpStatusOf,
+ gfsRetryAfterSecondsOf,
+ gfsRoleRank,
+ gfsSubjectKeyOf,
+ isEditorGfsPermissions,
+ mergeGfsInheritedAccessItem,
+ planGfsInheritedRoleChange,
+ strongestGfsInheritedSource,
+ worstGfsCoverageClass,
+}
diff --git a/packages/gfs-interaction-policy/inheritedAccess.d.ts b/packages/gfs-interaction-policy/inheritedAccess.d.ts
new file mode 100644
index 000000000..e2dba43a4
--- /dev/null
+++ b/packages/gfs-interaction-policy/inheritedAccess.d.ts
@@ -0,0 +1,82 @@
+export type GfsAclReadFailureClass = 'denied' | 'missing' | 'rate-limited' | 'retryable' | 'error'
+
+export type GfsCoverageClass = GfsAclReadFailureClass | 'depth-cap' | 'complete'
+
+export interface GfsSubjectRef {
+ type: string
+ id?: string
+}
+
+/** One contributing ACL row (grant or share) as observed on an ancestor. */
+export interface GfsInheritedContribution {
+ subject: GfsSubjectRef
+ permissions: string[]
+ rowKind: 'grant' | 'share'
+ rowId: string
+ inherit?: boolean
+ includeDescendants?: boolean
+}
+
+export interface GfsInheritedSourceFolder {
+ resourceId: string
+ name: string
+}
+
+export interface GfsInheritedShareEntry {
+ rowId: string
+ permissions: string[]
+ includeDescendants: boolean
+}
+
+export interface GfsInheritedAccessSource {
+ resourceId: string
+ name: string
+ /** Union of this folder's contributing rows — display only, never written back. */
+ permissions: string[]
+ grantId: string | null
+ shareIds: string[]
+ /** Exact bits of this folder's grant row, when one contributes. */
+ grantPermissions: string[] | null
+ /** The grant row's own scope flag, preserved by every edit. */
+ grantInherit: boolean | null
+ shareEntries: GfsInheritedShareEntry[]
+}
+
+export interface GfsInheritedAccessItem {
+ subject: GfsSubjectRef
+ permissions: string[]
+ inheritedFrom: string[]
+ sources: GfsInheritedAccessSource[]
+}
+
+/** Result of `planGfsInheritedRoleChange` — see implementation contract. */
+export interface GfsInheritedRoleChangePlan {
+ grantSources: GfsInheritedAccessSource[]
+ shareOnlySources: GfsInheritedAccessSource[]
+}
+
+export declare const GFS_INHERITED_WALK_MAX_DEPTH: number
+export declare const GFS_RETRY_AFTER_MAX_SECONDS: number
+
+export declare function gfsSubjectKeyOf(subject: GfsSubjectRef): string
+export declare function gfsAncestorPathsOf(path: string): string[]
+export declare function gfsHttpStatusOf(error: unknown): number | null
+export declare function gfsRetryAfterSecondsOf(error: unknown): number | null
+export declare function classifyGfsAclReadFailure(error: unknown): GfsAclReadFailureClass
+export declare function isEditorGfsPermissions(permissions: string[]): boolean
+export declare function gfsRoleRank(permissions: string[]): number
+export declare function strongestGfsInheritedSource(
+ sources: GfsInheritedAccessSource[]
+): GfsInheritedAccessSource | null
+export declare function mergeGfsInheritedAccessItem(
+ current: GfsInheritedAccessItem | null,
+ contribution: GfsInheritedContribution,
+ folder: GfsInheritedSourceFolder
+): GfsInheritedAccessItem
+export declare function planGfsInheritedRoleChange(
+ item: Pick<GfsInheritedAccessItem, 'permissions' | 'sources'>,
+ targetRoleIsEditor: boolean
+): GfsInheritedRoleChangePlan
+export declare function worstGfsCoverageClass(
+ classifications: readonly GfsCoverageClass[]
+): GfsCoverageClass
diff --git a/packages/gfs-interaction-policy/inheritedAccess.test.cjs b/packages/gfs-interaction-policy/inheritedAccess.test.cjs
new file mode 100644
index 000000000..073976c3d
--- /dev/null
+++ b/packages/gfs-interaction-policy/inheritedAccess.test.cjs
@@ -0,0 +1,412 @@
+'use strict'
+
+const { describe, it } = require('node:test')
+const assert = require('node:assert/strict')
+
+const {
+ GFS_INHERITED_WALK_MAX_DEPTH,
+ classifyGfsAclReadFailure,
+ gfsAncestorPathsOf,
+ gfsHttpStatusOf,
+ gfsRetryAfterSecondsOf,
+ gfsRoleRank,
+ gfsSubjectKeyOf,
+ isEditorGfsPermissions,
+ mergeGfsInheritedAccessItem,
+ planGfsInheritedRoleChange,
+ strongestGfsInheritedSource,
+ worstGfsCoverageClass,
+} = require('./inheritedAccess.cjs')
+
+const folder = (resourceId, name) => ({ resourceId, name })
+const grantContribution = (subject, permissions, rowId, inherit = true) => ({
+ subject,
+ permissions,
+ rowKind: 'grant',
+ rowId,
+ inherit,
+})
+const shareContribution = (subject, permissions, rowId, includeDescendants = true) => ({
+ subject,
+ permissions,
+ rowKind: 'share',
+ rowId,
+ includeDescendants,
+})
+const userA = { type: 'user', id: 'user-a' }
+const userB = { type: 'user', id: 'user-b' }
+
+describe('gfsSubjectKeyOf', () => {
+ it('operator carries no id segment', () => {
+ assert.equal(gfsSubjectKeyOf({ type: 'operator' }), 'operator:')
+ })
+ it('team and user keys are distinct even for the same human', () => {
+ assert.notEqual(
+ gfsSubjectKeyOf({ type: 'user', id: 'x' }),
+ gfsSubjectKeyOf({ type: 'team', id: 'x' })
+ )
+ })
+})
+
+describe('gfsAncestorPathsOf', () => {
+ it('nearest ancestor first ending at the drive root', () => {
+ assert.deepEqual(gfsAncestorPathsOf('/docs/report.md'), ['/docs', '/'])
+ })
+ it('a root-level resource has exactly the root folder as its ancestor', () => {
+ // The Control UI anchor pushes the drive root unconditionally: a file at
+ // /report.md is covered by the root folder's inheriting grants.
+ assert.deepEqual(gfsAncestorPathsOf('/report.md'), ['/'])
+ })
+ it('the root folder itself has no ancestors', () => {
+ assert.deepEqual(gfsAncestorPathsOf('/'), [])
+ })
+ it('depth is capped at the walk bound, keeping the NEAREST ancestors', () => {
+ // 100 directories + leaf = 101 segments → 101 ancestors before the cap;
+ // the first 64 kept are counts 100..37, so the last kept path has the
+ // first 37 segments (d0..d36).
+ const deep = `/${Array.from({ length: 100 }, (_, i) => `d${i}`).join('/')}/leaf.md`
+ const ancestors = gfsAncestorPathsOf(deep)
+ assert.equal(ancestors.length, GFS_INHERITED_WALK_MAX_DEPTH)
+ assert.equal(ancestors.at(-1), `/${Array.from({ length: 37 }, (_, i) => `d${i}`).join('/')}`)
+ })
+})
+
+describe('gfsHttpStatusOf / gfsRetryAfterSecondsOf', () => {
+ it('structured status wins over message text', () => {
+ assert.equal(gfsHttpStatusOf({ status: 403 }), 403)
+ assert.equal(gfsHttpStatusOf({ response: { status: 429 } }), 429)
+ })
+ it('reads the vetted main-process markers and leading status lines', () => {
+ assert.equal(gfsHttpStatusOf(new Error('Forbidden httpStatus=403')), 403)
+ assert.equal(gfsHttpStatusOf(new Error('429 Too Many Requests: slow down')), 429)
+ assert.equal(gfsHttpStatusOf(new Error('no status here')), null)
+ })
+ it('retry window is read from the trailing marker and clamped', () => {
+ assert.equal(gfsRetryAfterSecondsOf(new Error('rate limited retryAfterSeconds=7')), 7)
+ assert.equal(gfsRetryAfterSecondsOf(new Error('retryAfterSeconds=9000')), 300)
+ assert.equal(gfsRetryAfterSecondsOf(new Error('no window')), null)
+ })
+})
+
+describe('classifyGfsAclReadFailure', () => {
+ it('401/403 are denied privacy boundaries, not session failures', () => {
+ assert.equal(classifyGfsAclReadFailure({ status: 403 }), 'denied')
+ assert.equal(classifyGfsAclReadFailure(new Error('401 Unauthorized')), 'denied')
+ })
+ it('404/410 are missing, 429 rate-limited, 5xx/transport retryable', () => {
+ assert.equal(classifyGfsAclReadFailure({ status: 404 }), 'missing')
+ assert.equal(classifyGfsAclReadFailure({ status: 410 }), 'missing')
+ assert.equal(classifyGfsAclReadFailure({ status: 429 }), 'rate-limited')
+ assert.equal(classifyGfsAclReadFailure({ status: 503 }), 'retryable')
+ assert.equal(classifyGfsAclReadFailure(new TypeError('fetch failed')), 'retryable')
+ assert.equal(classifyGfsAclReadFailure(new Error('socket hang up')), 'retryable')
+ })
+ it('unexpected shapes stay errors', () => {
+ assert.equal(classifyGfsAclReadFailure(new Error('boom')), 'error')
+ assert.equal(classifyGfsAclReadFailure({ status: 400 }), 'error')
+ })
+})
+
+describe('mergeGfsInheritedAccessItem', () => {
+ it('creates the subject on first sight with exact row provenance', () => {
+ const item = mergeGfsInheritedAccessItem(
+ null,
+ grantContribution(userA, ['read', 'write'], 'g1', true),
+ folder('f1', 'Projects')
+ )
+ assert.equal(item.subject, userA)
+ assert.deepEqual(item.permissions, ['read', 'write'])
+ assert.equal(item.sources[0].grantId, 'g1')
+ assert.equal(item.sources[0].grantInherit, true)
+ assert.deepEqual(item.sources[0].grantPermissions, ['read', 'write'])
+ assert.deepEqual(item.sources[0].shareEntries, [])
+ })
+
+ it('same folder grant + share consolidate, keeping each row separately addressable', () => {
+ let item = mergeGfsInheritedAccessItem(
+ null,
+ grantContribution(userA, ['read', 'write'], 'g1', true),
+ folder('f1', 'Projects')
+ )
+ item = mergeGfsInheritedAccessItem(
+ item,
+ shareContribution(userA, ['read'], 's1', true),
+ folder('f1', 'Projects')
+ )
+ assert.equal(item.sources.length, 1)
+ assert.equal(item.sources[0].grantId, 'g1')
+ assert.deepEqual(item.sources[0].shareIds, ['s1'])
+ assert.deepEqual(item.sources[0].permissions, ['read', 'write'])
+ assert.deepEqual(item.sources[0].shareEntries, [
+ { rowId: 's1', permissions: ['read'], includeDescendants: true },
+ ])
+ })
+
+ it('every contributing folder survives: idempotent, no source dropped, inputs untouched', () => {
+ const first = mergeGfsInheritedAccessItem(
+ null,
+ grantContribution(userA, ['read'], 'g1', true),
+ folder('f1', 'Projects')
+ )
+ const second = mergeGfsInheritedAccessItem(
+ first,
+ grantContribution(userA, ['read', 'manage_acl'], 'g2', false),
+ folder('f2', 'Archive')
+ )
+ const again = mergeGfsInheritedAccessItem(
+ second,
+ grantContribution(userA, ['read'], 'g1', true),
+ folder('f1', 'Projects')
+ )
+ assert.equal(again.sources.length, 2)
+ assert.deepEqual(
+ again.sources.map(source => source.resourceId),
+ ['f1', 'f2']
+ )
+ assert.equal(again.sources[0].grantId, 'g1')
+ assert.equal(again.sources[0].grantInherit, true)
+ assert.equal(again.sources[1].grantId, 'g2')
+ assert.equal(again.sources[1].grantInherit, false)
+ assert.deepEqual(first.permissions, ['read'])
+ assert.equal(first.sources.length, 1)
+ })
+
+ it('subjects never merge across keys', () => {
+ let items = mergeGfsInheritedAccessItem(
+ null,
+ grantContribution(userA, ['read'], 'g1', true),
+ folder('f1', 'Projects')
+ )
+ items = mergeGfsInheritedAccessItem(
+ items,
+ grantContribution(userB, ['read'], 'g2', true),
+ folder('f1', 'Projects')
+ )
+ assert.equal(items.subject, userA)
+ assert.equal(items.sources.length, 1)
+ assert.equal(gfsSubjectKeyOf(items.subject), gfsSubjectKeyOf(userA))
+ })
+
+ it('property: folding is idempotent and the union only grows', () => {
+ // Wire-faithful input: the server's UNIQUE (drive, resource, subject)
+ // constraint allows at most ONE grant per subject+folder, so a folder's
+ // contributions for one subject are one grant plus any number of shares.
+ const contributions = [
+ grantContribution(userA, ['read'], 'g1', true),
+ shareContribution(userA, ['read', 'share'], 's1', false),
+ shareContribution(userA, ['read', 'write'], 's2', true),
+ ]
+ let folded = null
+ for (let round = 0; round < 3; round += 1) {
+ for (const contribution of contributions) {
+ folded = mergeGfsInheritedAccessItem(folded, contribution, folder('f1', 'Projects'))
+ }
+ }
+ assert.equal(folded.sources.length, 1)
+ assert.equal(folded.sources[0].grantId, 'g1')
+ assert.deepEqual(folded.sources[0].shareIds.sort(), ['s1', 's2'])
+ assert.equal(folded.sources[0].grantInherit, true)
+ assert.equal(folded.sources[0].shareEntries.length, 2)
+ for (const permission of ['read', 'write', 'share']) {
+ assert.ok(folded.permissions.includes(permission))
+ }
+ })
+})
+
+describe('planGfsInheritedRoleChange', () => {
+ it('no-op when the target equals the effective role', () => {
+ const item = { permissions: ['read', 'write'], sources: [] }
+ assert.deepEqual(planGfsInheritedRoleChange(item, true), {
+ grantSources: [],
+ shareOnlySources: [],
+ })
+ })
+
+ it('downgrade plans every editor grant source and discloses share-only editors', () => {
+ const item = {
+ permissions: ['read', 'write'],
+ sources: [
+ {
+ resourceId: 'f1',
+ name: 'A',
+ permissions: ['read', 'write'],
+ grantId: 'g1',
+ shareIds: [],
+ grantPermissions: ['read', 'write'],
+ grantInherit: true,
+ shareEntries: [],
+ },
+ {
+ resourceId: 'f2',
+ name: 'B',
+ permissions: ['read'],
+ grantId: 'g2',
+ shareIds: [],
+ grantPermissions: ['read'],
+ grantInherit: true,
+ shareEntries: [],
+ },
+ {
+ resourceId: 'f3',
+ name: 'C',
+ permissions: ['read', 'write'],
+ grantId: null,
+ shareIds: ['s1'],
+ grantPermissions: null,
+ grantInherit: null,
+ shareEntries: [{ rowId: 's1', permissions: ['read', 'write'], includeDescendants: true }],
+ },
+ ],
+ }
+ const plan = planGfsInheritedRoleChange(item, false)
+ assert.deepEqual(
+ plan.grantSources.map(source => source.resourceId),
+ ['f1']
+ )
+ assert.deepEqual(
+ plan.shareOnlySources.map(source => source.resourceId),
+ ['f3']
+ )
+ })
+
+ it('upgrade raises the strongest source, preferring an editable grant when the strongest is a share', () => {
+ // Effective role is Read (both sources read-strength), so an upgrade
+ // plans. The nearest/strongest source (tie broken nearest-first) is the
+ // share, which this release cannot edit — the plan raises the strongest
+ // grant-backed source instead and discloses the share residual.
+ const sources = [
+ {
+ resourceId: 'f2',
+ name: 'B',
+ permissions: ['read'],
+ grantId: null,
+ shareIds: ['s1'],
+ grantPermissions: null,
+ grantInherit: null,
+ shareEntries: [{ rowId: 's1', permissions: ['read'], includeDescendants: true }],
+ },
+ {
+ resourceId: 'f1',
+ name: 'A',
+ permissions: ['read'],
+ grantId: 'g1',
+ shareIds: [],
+ grantPermissions: ['read'],
+ grantInherit: false,
+ shareEntries: [],
+ },
+ ]
+ const plan = planGfsInheritedRoleChange({ permissions: ['read'], sources }, true)
+ assert.deepEqual(
+ plan.grantSources.map(source => source.resourceId),
+ ['f1']
+ )
+ assert.deepEqual(
+ plan.shareOnlySources.map(source => source.resourceId),
+ ['f2']
+ )
+ })
+
+ it('an editor-strength share already makes the effective role editor, so an editor upgrade is a no-op', () => {
+ const sources = [
+ {
+ resourceId: 'f1',
+ name: 'A',
+ permissions: ['read'],
+ grantId: 'g1',
+ shareIds: [],
+ grantPermissions: ['read'],
+ grantInherit: false,
+ shareEntries: [],
+ },
+ {
+ resourceId: 'f2',
+ name: 'B',
+ permissions: ['read', 'write'],
+ grantId: null,
+ shareIds: ['s1'],
+ grantPermissions: null,
+ grantInherit: null,
+ shareEntries: [{ rowId: 's1', permissions: ['read', 'write'], includeDescendants: true }],
+ },
+ ]
+ assert.deepEqual(
+ planGfsInheritedRoleChange({ permissions: ['read', 'write'], sources }, true),
+ {
+ grantSources: [],
+ shareOnlySources: [],
+ }
+ )
+ })
+
+ it('strongest grant-backed source wins the upgrade when several are editable', () => {
+ const sources = [
+ {
+ resourceId: 'f1',
+ name: 'A',
+ permissions: ['read'],
+ grantId: 'g1',
+ shareIds: [],
+ grantPermissions: ['read'],
+ grantInherit: true,
+ shareEntries: [],
+ },
+ {
+ resourceId: 'f2',
+ name: 'B',
+ permissions: ['read', 'write'],
+ grantId: 'g2',
+ shareIds: [],
+ grantPermissions: ['read', 'write'],
+ grantInherit: true,
+ shareEntries: [],
+ },
+ ]
+ const plan = planGfsInheritedRoleChange({ permissions: ['read'], sources }, true)
+ assert.deepEqual(
+ plan.grantSources.map(source => source.resourceId),
+ ['f2']
+ )
+ })
+})
+
+describe('role helpers and coverage ordering', () => {
+ it('editor detection covers write/delete/manage_acl only', () => {
+ assert.equal(isEditorGfsPermissions(['read', 'share']), false)
+ assert.equal(isEditorGfsPermissions(['read', 'delete']), true)
+ assert.equal(gfsRoleRank(['read']), 0)
+ assert.equal(gfsRoleRank(['manage_acl']), 1)
+ })
+ it('strongest source: editor beats read, nearest among equals', () => {
+ const sources = [
+ {
+ resourceId: 'f1',
+ name: 'A',
+ permissions: ['read', 'write'],
+ grantId: 'g1',
+ shareIds: [],
+ grantPermissions: null,
+ grantInherit: null,
+ shareEntries: [],
+ },
+ {
+ resourceId: 'f2',
+ name: 'B',
+ permissions: ['read'],
+ grantId: 'g2',
+ shareIds: [],
+ grantPermissions: null,
+ grantInherit: null,
+ shareEntries: [],
+ },
+ ]
+ assert.equal(strongestGfsInheritedSource(sources).resourceId, 'f1')
+ assert.equal(strongestGfsInheritedSource([]), null)
+ })
+ it('worst-first coverage combination', () => {
+ assert.equal(worstGfsCoverageClass(['complete', 'denied', 'complete']), 'denied')
+ assert.equal(worstGfsCoverageClass(['rate-limited', 'denied']), 'rate-limited')
+ assert.equal(worstGfsCoverageClass(['complete']), 'complete')
+ assert.equal(worstGfsCoverageClass([]), 'complete')
+ })
+})
diff --git a/packages/gfs-interaction-policy/package.json b/packages/gfs-interaction-policy/package.json
index a828a401b..a23c57959 100644
--- a/packages/gfs-interaction-policy/package.json
+++ b/packages/gfs-interaction-policy/package.json
@@ -12,6 +12,8 @@
"dragPolicy.d.ts",
"fileClassifier.cjs",
"fileClassifier.d.ts",
+ "inheritedAccess.cjs",
+ "inheritedAccess.d.ts",
"fileReference.cjs",
"fileReference.d.ts"
],
@@ -23,8 +25,8 @@
}
},
"scripts": {
- "build": "node --check index.cjs && node --check dragPolicy.cjs && node --check fileClassifier.cjs && node --check fileReference.cjs",
- "test": "node --test index.test.cjs dragPolicy.test.cjs fileReference.test.cjs fileClassifier.test.cjs"
+ "build": "node --check index.cjs && node --check dragPolicy.cjs && node --check fileClassifier.cjs && node --check fileReference.cjs && node --check inheritedAccess.cjs",
+ "test": "node --test index.test.cjs dragPolicy.test.cjs fileReference.test.cjs fileClassifier.test.cjs inheritedAccess.test.cjs"
},
"license": "MIT"
}