Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop): r1-h3 clear session state on inherited authority loss
M8c87fd212f88
diff --git a/desktop-app/ui/src/gfs/inheritedAccess.ts b/desktop-app/ui/src/gfs/inheritedAccess.tsindex baf25b991..7622189ce 100644--- a/desktop-app/ui/src/gfs/inheritedAccess.ts+++ b/desktop-app/ui/src/gfs/inheritedAccess.ts@@ -1,7 +1,7 @@import { classifyGfsAclReadFailure, worstGfsCoverageClass } from '@clerum/gfs-interaction-policy'import type { GfsCoverageClass } from '@clerum/gfs-interaction-policy'import { GFS_BREADCRUMB_MAX_DEPTH } from '@constants/gfsBrowser'-import { parseHttpStatus } from '@lib/gfsGrantErrors'+import { isGfsSessionAuthorityFailure } from '@lib/gfsGrantErrors'import type { GfsInheritedAccessItem, GfsInheritedAccessResult } from './delegation.types'import { inheritedSubjectKey, mergeInheritedAccessItem } from './inheritedAccessMerge'@@ -27,7 +27,7 @@ export { planInheritedRoleChange, strongestInheritedSource } from './inheritedAc* family's rows and the walk continues (`acl-limited`) — the readable* ancestor's parent id is already known from its resolve. Any other failure* (404/410, 429, transport, cycle, depth cap) stops the walk with the folded- * rows and `unavailable`. HTTP 401 from any family is rethrown RAW: a session+ * rows and `unavailable`. A session-authority failure (401 or typed lifecycle 403) is rethrown RAW: a session* death is never classified as a quiet boundary and keeps traveling the* controller's existing fail-closed error path.*/@@ -61,17 +61,21 @@ export async function deriveGfsInheritedAccess(let aclDenied = falselet stopped = false- /** Vetted status marker from the main-process client; null when none. */- const statusOf = (error: unknown): number | null =>- parseHttpStatus(error instanceof Error ? error.message : String(error ?? ''))+ // Match the existing session boundary before classifying an ordinary+ // folder/ACL denial. Typed lifecycle 403s are session failures too.+ const isAuthorityFailure = (error: unknown): boolean =>+ isGfsSessionAuthorityFailure(+ error instanceof Error ? error.message : String(error ?? ''),+ 'operation'+ )- /** Classify a resolve failure; a session 401 rethrows the original error. */+ /** Classify a resolve failure; session authority rethrows the original error. */const resolveFailureClass = (error: unknown): GfsCoverageClass => {- if (statusOf(error) === 401) throw error+ if (isAuthorityFailure(error)) throw errorreturn classifyGfsAclReadFailure(error)}- /** Classify an ACL-list failure (same 401 rule as resolve). */+ /** Classify an ACL-list failure (same authority rule as resolve). */const aclFailureClass = resolveFailureClasslet targetParentId: string | null@@ -123,9 +127,9 @@ export async function deriveGfsInheritedAccess(window.clerum.gfs.listGrants(parent.resourceId, drive),window.clerum.gfs.listShares(parent.resourceId, drive),])- // A session 401 from EITHER family rethrows before anything is folded.+ // A session-authority failure from EITHER family rethrows before rows fold.for (const outcome of settled) {- if (outcome.status === 'rejected' && statusOf(outcome.reason) === 401) throw outcome.reason+ if (outcome.status === 'rejected' && isAuthorityFailure(outcome.reason)) throw outcome.reason}const grants = settled[0].status === 'fulfilled' ? settled[0].value : nullconst shares = settled[1].status === 'fulfilled' ? settled[1].value : nulldiff --git a/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsxindex 79ec58caa..9ae0150d9 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx@@ -11,11 +11,19 @@ import {import { act, cleanup, render, screen, waitFor } from '@testing-library/react'import { desktopQueryDefaults } from '@lib/queryClient'import {+ affordancesResult,childView,+ grantsListPage,+ heldAffordances,+ listAccessiblePage,listChildrenPage,+ listGrantsFailureMessage,+ listSharesFailureMessage,resolveDeniedMessage,resolveResource,resolvedDirectory,+ resolvedFile,+ sharesListPage,} from '@/gfs/__fixtures__/gfsProducerFixtures'import { shouldRevalidateGfsQuery } from '@/lib/gfsEntityChangeState'import { desktopQueryKeys } from '../queryKeys'@@ -2713,6 +2721,9 @@ function ManageProbe() {<div data-testid="shares-count">{ctrl.shares.length}</div><div data-testid="inherited-error">{ctrl.inheritedAccessError ?? 'none'}</div><div data-testid="inherited-coverage">{ctrl.inheritedCoverage ?? 'none'}</div>+ <div data-testid="access-state">{ctrl.accessState}</div>+ <div data-testid="crumbs">{ctrl.crumbs.map(crumb => crumb.name).join(' / ')}</div>+ <div data-testid="held-permissions">{ctrl.affordances?.held.join(',') ?? 'none'}</div><button type="button" onClick={() => swallow(ctrl.openUri('gfs://main/root'))}>open root</button>@@ -3198,53 +3209,130 @@ describe('useGfsBrowserController — grants list / revoke / inherit (#826)', ()expect(screen.getByTestId('inherited-error').textContent).toBe('none')})- it('still surfaces the raw inheritedAccessError for a session 401', async () => {- let resolveCalls = 0- Object.defineProperty(window, 'clerum', {- configurable: true,- value: {- gfs: {- listAccessible: vi.fn(async () => ({ items: [], nextCursor: null })),- resolve: vi.fn(async () => {- resolveCalls += 1- if (resolveCalls > 1) throw new Error('Error: 401 Unauthorized httpStatus=401')- return {- resourceId: 'file-1',- parentResourceId: 'folder-1',- gfsUri: 'gfs://main/file-1',- name: 'report.txt',- kind: 'file',- version: 1,- }- }),- listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),- affordances: vi.fn(async () => ({- held: ['read', 'manage_acl'],+ // Every response and rejection crosses the real client/HTTP fixture seam.+ // The observable contract is session state and protected metadata, not a+ // briefly presented error string before the authority boundary clears it.+ for (const route of ['resolve', 'grants', 'shares'] as const) {+ for (const [status, code] of [+ [401, 'unauthorized'],+ [403, 'desktop_user_retired'],+ [403, 'gfs_operator_link_invalid'],+ [403, 'manage_acl_required'],+ ] as const) {+ it(`handles inherited ${route} ${code} through the correct authority boundary`, async () => {+ const targetId = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'+ const parentId = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'+ const target = await resolveResource(+ resolvedFile(targetId, 'report.txt', {+ parentResourceId: parentId,+ })+ )+ const parent = await resolveResource(resolvedDirectory(parentId, 'team-docs'))+ const body = { code, message: code }+ const failure =+ route === 'resolve'+ ? await resolveDeniedMessage(target.gfsUri, body, status)+ : route === 'grants'+ ? await listGrantsFailureMessage(status, body)+ : await listSharesFailureMessage(status, body)+ expect(failure).toContain(`httpStatus=${status}`)+ expect(failure).toContain(code)+ const directGrants = await grantsListPage([+ {+ id: 'direct-grant',+ drive: 'main',+ resourceId: targetId,+ subject: { type: 'user', id: 'bob' },+ permissions: ['read'],+ inherit: false,+ },+ ])+ const directShares = await sharesListPage([+ {+ id: 'direct-share',+ drive: 'main',+ resourceId: targetId,+ subject: { type: 'user', id: 'carol' },+ permissions: ['read'],+ includeDescendants: false,+ },+ ])+ const emptyGrants = await grantsListPage([])+ const emptyShares = await sharesListPage([])+ const accessible = await listAccessiblePage([])+ const children = await listChildrenPage([])+ const affordances = await affordancesResult(+ heldAffordances(['read', 'manage_acl'], {canDelegate: true,grantableBits: ['read'],canCreateShare: false,- })),- listGrants: vi.fn(async () => []),- listShares: vi.fn(async () => []),- },- },- })-- render(<ManageProbe />, { wrapper: Harness })-- await act(async () => {- screen.getByRole('button', { name: 'open root' }).click()- })- await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('file-1'))- await act(async () => {- screen.getByRole('button', { name: 'open manage' }).click()- })-- await waitFor(() =>- expect(screen.getByTestId('inherited-error').textContent).toBe(- 'Error: 401 Unauthorized httpStatus=401'- )- )- expect(screen.getByTestId('inherited-coverage').textContent).toBe('none')- })+ })+ )+ let manageReadStarted = false+ Object.defineProperty(window, 'clerum', {+ configurable: true,+ value: {+ gfs: {+ listAccessible: vi.fn(async () => accessible),+ resolve: vi.fn(async (uri: string) => {+ if (uri.endsWith(parentId.replace(/-/g, '')) || uri.endsWith(parentId))+ return parent+ if (manageReadStarted && route === 'resolve') throw new Error(failure)+ return target+ }),+ listChildren: vi.fn(async () => children),+ affordances: vi.fn(async () => affordances),+ listGrants: vi.fn(async (resourceId: string) => {+ if (resourceId === targetId) return directGrants+ if (route === 'grants') throw new Error(failure)+ return emptyGrants+ }),+ listShares: vi.fn(async (resourceId: string) => {+ if (resourceId === targetId) return directShares+ if (route === 'shares') throw new Error(failure)+ return emptyShares+ }),+ },+ },+ })+ render(<ManageProbe />, { wrapper: Harness })+ await act(async () => screen.getByRole('button', { name: 'open root' }).click())+ await waitFor(() => expect(screen.getByTestId('current').textContent).toBe(targetId))+ const client = lastHarnessQueryClient!+ const scope = ':user-a:team-a'+ const grantsKey = desktopQueryKeys.gfsGrants(scope, targetId, 'main')+ const sharesKey = desktopQueryKeys.gfsShares(scope, targetId, 'main')+ await act(async () => {+ client.setQueryData(grantsKey, directGrants)+ client.setQueryData(sharesKey, directShares)+ })+ expect(client.getQueryData(grantsKey)).toEqual(directGrants)+ expect(client.getQueryData(sharesKey)).toEqual(directShares)+ manageReadStarted = true+ await act(async () => screen.getByRole('button', { name: 'open manage' }).click())+ if (code === 'manage_acl_required') {+ await waitFor(() =>+ expect(screen.getByTestId('inherited-coverage').textContent).toBe(+ route === 'resolve' ? 'read-boundary' : 'acl-limited'+ )+ )+ expect(screen.getByTestId('access-state').textContent).toBe('active')+ expect(screen.getByTestId('current').textContent).toBe(targetId)+ expect(screen.getByTestId('grants-count').textContent).toBe('1')+ expect(screen.getByTestId('shares-count').textContent).toBe('1')+ } else {+ await waitFor(() =>+ expect(screen.getByTestId('access-state').textContent).toBe('revoked')+ )+ expect(screen.getByTestId('current').textContent).toBe('none')+ expect(screen.getByTestId('crumbs').textContent).toBe('')+ expect(screen.getByTestId('held-permissions').textContent).toBe('none')+ expect(screen.getByTestId('grants-count').textContent).toBe('0')+ expect(screen.getByTestId('shares-count').textContent).toBe('0')+ expect(client.getQueryData(grantsKey)).toBeUndefined()+ expect(client.getQueryData(sharesKey)).toBeUndefined()+ }+ })+ }+ }})diff --git a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.tsindex 2063937d0..86adde4ab 100644--- a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts+++ b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts@@ -12,6 +12,7 @@ import { GFS_BREADCRUMB_MAX_DEPTH } from '@constants/gfsBrowser'import { applyMoveConvergence } from '@lib/gfsEntityChangeState'import {describeGfsReadError,+ isGfsSessionAuthorityFailure,isRateLimited,parseHttpStatus,parseRetryAfterSeconds,@@ -258,45 +259,7 @@ function classifyDiscoveryFailure(message: string): GfsDiscoveryFailureKind {*/const UNKNOWN_RATE_LIMIT_PAUSE_MS = 60_000-const SESSION_AUTHORITY_ERROR_CODES = [- 'desktop_user_retired',- 'operator_link_inactive',- 'operator_link_invalid',- 'gfs_operator_link_invalid',-] as const--/**- * Only a session/authorization failure may invalidate the browser's- * session-local access state. Per-resource policy verdicts such as- * `manage_acl_required`, `escalation_rejected`, and `foreign_agent_forbidden`- * are expected 403s and must remain local to the attempted operation.- *- * - `discovery` (listAccessible): the shared-with-me listing is- * permission-derived session state, so a 401/403 there is an authority- * verdict and fails closed.- * - `operation` (children/affordances/grants/shares/resolve): a generic 403- * is usually a resource-policy denial and must NOT clear the session; only- * a bare 401 or a typed lifecycle code does.- */-export function isGfsSessionAuthorityFailure(- message: string,- surface: 'discovery' | 'operation' = 'operation'-): boolean {- const normalized = message.toLowerCase()- if (SESSION_AUTHORITY_ERROR_CODES.some(code => normalized.includes(code))) return true- if (surface !== 'discovery') {- return (- /(^|\D)401(\D|$)/.test(normalized) ||- normalized.includes('not authenticated') ||- normalized.includes('unauthenticated')- )- }- return (- /(^|\D)(401|403)(\D|$)/.test(normalized) ||- normalized.includes('unauthorized') ||- normalized.includes('forbidden')- )-}+export { isGfsSessionAuthorityFailure } from '@lib/gfsGrantErrors'export function useGfsBrowserController(options: GfsBrowserControllerOptions = {}) {const { grantsListEnabled = false } = options@@ -843,6 +806,9 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {sharesQuery.error? { message: toMessage(sharesQuery.error), surface: 'operation' as const }: null,+ inheritedAccessQuery.error+ ? { message: toMessage(inheritedAccessQuery.error), surface: 'operation' as const }+ : null,].filter((entry): entry is { message: string; surface: 'discovery' | 'operation' } => entry !== nulldiff --git a/desktop-app/ui/src/lib/gfsGrantErrors.ts b/desktop-app/ui/src/lib/gfsGrantErrors.tsindex ff602a9e1..cdc50385d 100644--- a/desktop-app/ui/src/lib/gfsGrantErrors.ts+++ b/desktop-app/ui/src/lib/gfsGrantErrors.ts@@ -268,3 +268,43 @@ export function describeGfsGrantError(error: unknown): GfsGrantErrorPresentationseverity: 'error',}}++const SESSION_AUTHORITY_ERROR_CODES = [+ 'desktop_user_retired',+ 'operator_link_inactive',+ 'operator_link_invalid',+ 'gfs_operator_link_invalid',+] as const++/**+ * Only a session/authorization failure may invalidate the browser's+ * session-local access state. Per-resource policy verdicts such as+ * `manage_acl_required`, `escalation_rejected`, and `foreign_agent_forbidden`+ * are expected 403s and must remain local to the attempted operation.+ *+ * - `discovery` (listAccessible): the shared-with-me listing is+ * permission-derived session state, so a 401/403 there is an authority+ * verdict and fails closed.+ * - `operation` (children/affordances/grants/shares/resolve): a generic 403+ * is usually a resource-policy denial and must NOT clear the session; only+ * a bare 401 or a typed lifecycle code does.+ */+export function isGfsSessionAuthorityFailure(+ message: string,+ surface: 'discovery' | 'operation' = 'operation'+): boolean {+ const normalized = message.toLowerCase()+ if (SESSION_AUTHORITY_ERROR_CODES.some(code => normalized.includes(code))) return true+ if (surface !== 'discovery') {+ return (+ /(^|\D)401(\D|$)/.test(normalized) ||+ normalized.includes('not authenticated') ||+ normalized.includes('unauthenticated')+ )+ }+ return (+ /(^|\D)(401|403)(\D|$)/.test(normalized) ||+ normalized.includes('unauthorized') ||+ normalized.includes('forbidden')+ )+}