Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop): revalidate focused preview per-resource access and drop denied bytes (R1-H6)
Diego Zacarias4b9482c692b3
diff --git a/desktop-app/ui/src/gfs/__fixtures__/gfsProducerFixtures.ts b/desktop-app/ui/src/gfs/__fixtures__/gfsProducerFixtures.tsindex 28c4ba74f..20a7fbc9a 100644--- a/desktop-app/ui/src/gfs/__fixtures__/gfsProducerFixtures.ts+++ b/desktop-app/ui/src/gfs/__fixtures__/gfsProducerFixtures.ts@@ -35,6 +35,7 @@* H8 (fail-closed tests) reuses these builders — do not inline gfs wire shapes* in a new tree/preview test.*/+import { createServer } from 'node:http'import {type GfsAccessibleResource,type GfsChildView,@@ -42,6 +43,7 @@ import {type GfsTransport,type ResolvedGfsResource,} from '../../../../src/gfs/uriHandler.js'+import { requestJson } from '../../../../src/httpClient.js'// listChildren/listAccessible bind cleanly to the renderer boundary types (the// `.d.ts` the tree consumes), so a drift between the producer's emitted page and@@ -178,6 +180,54 @@ export async function openGfsResourcePayload(})}+/**+ * The Error message `window.clerum.gfs.resolve` rejects with when a per-resource+ * read is denied (the file was unshared) — derived, not hand-written (T1).+ *+ * Unlike the success builders above, a denial cannot go through `stubTransport`:+ * that stub returns its body and lets `GfsClient.unwrap` throw a `GfsUriError`,+ * but that envelope branch is UNREACHABLE for a resolve denial in production. The+ * server returns an HTTP 403 (gfsc `envelope.ts` `toResponse` → `{ ok:false,+ * error:{ code:'forbidden', … } }`, forwarded verbatim through control-api and+ * external-rest-api since 403 ∈ its PROPAGATED set), and the desktop's REAL+ * `httpClient.requestJson` — the exact transport `appService.ts` constructs+ * `GfsClient` with — mints an `ApiError` from that non-2xx BEFORE `unwrap` ever+ * runs. Only that `ApiError.message` survives the Electron IPC boundary to the+ * renderer. So the faithful producer is the real client + real transport run+ * against a temp 403 endpoint; the only hand-modeled part is the gfsc error body,+ * the cross-service HTTP boundary this module already treats as the honest seam.+ */+export async function resolveDeniedMessage(+ gfsUri = 'gfs://main/secret',+ errorBody: { code: string; message: string } = {+ code: 'forbidden',+ message: 'not authorized to read this resource',+ },+ status = 403+): Promise<string> {+ const server = createServer((_req, res) => {+ res.writeHead(status, { 'content-type': 'application/json' })+ res.end(JSON.stringify({ ok: false, error: errorBody }))+ })+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', () => resolve()))+ try {+ const address = server.address()+ const port = typeof address === 'object' && address ? address.port : 0+ const client = new GfsClient({+ baseUrl: `http://127.0.0.1:${port}`,+ requestJson,+ fetchBytes: async () => new ArrayBuffer(0),+ })+ await client.resolveUri(gfsUri, SESSION_TOKEN)+ throw new Error(`expected resolve to reject with a ${status} denial`)+ } catch (error) {+ if (!(error instanceof Error)) return String(error)+ return error.message+ } finally {+ await new Promise<void>(resolve => server.close(() => resolve()))+ }+}+/** A `ResolvedGfsResource` for a downloadable file, for `downloadResult`. */export function resolvedFile(resourceId: string,diff --git a/desktop-app/ui/src/pages/FilePreviewPage.tsx b/desktop-app/ui/src/pages/FilePreviewPage.tsxindex 27772f7ff..d5c2bc1e1 100644--- a/desktop-app/ui/src/pages/FilePreviewPage.tsx+++ b/desktop-app/ui/src/pages/FilePreviewPage.tsx@@ -1,10 +1,29 @@import { useCallback, useEffect, useState } from 'react'+import { EmptyState } from '@components/Common'import { GfsImagePreviewBody } from '@components/GfsImagePreview'import { GfsMarkdownPreviewBody } from '@components/GfsMarkdownPreview'import { GfsVideoPreviewBody } from '@components/GfsVideoPreview'import { useGfsBrowserController } from '@hooks/domain/useGfsBrowserController'import type { FilePreviewPageProps } from './FilePreviewPage.types'+function toMessage(error: unknown): string {+ return error instanceof Error ? error.message : String(error)+}++/**+ * A PER-RESOURCE read denial: the previewed file was unshared, so `gfs.resolve`+ * (and any download) now 403s for THIS resource while the session stays valid.+ * It is an operation-policy verdict — distinct from a session-authority failure+ * (401 / typed lifecycle code) which `handleAuthorityFailure` routes to the+ * shared session revoke. Keyed on the status the server emits (403 / forbidden)+ * so a transient network or 5xx failure never drops an otherwise-authorized+ * preview.+ */+function isPerResourceAccessDenial(message: string): boolean {+ const normalized = message.toLowerCase()+ return /(^|\D)403(\D|$)/.test(normalized) || normalized.includes('forbidden')+}+/*** A previewed GFS file living in its own workspace tab (spec 18 §3.B.3). Thin by* design: it mounts the `Gfs*PreviewBody` matching the tab's `fileKind` (each@@ -19,6 +38,17 @@ import type { FilePreviewPageProps } from './FilePreviewPage.types'* renders the reason (no stale content survives a revoke). The body's download* error is also routed back through the same controller so a revoke discovered* at fetch time fails the session closed exactly as the modal era did.+ *+ * Per-resource revalidation (R1-H6): a persistent preview tab outlives the grant+ * that opened it. The session-authority path above handles a 401, but a+ * per-RESOURCE unshare leaves the session valid, so nothing re-checked THIS file+ * while the tab stayed focused and its bytes (plus Copy) survived. On window+ * focus — the trigger the controller's own queries revalidate on — read authority+ * is re-checked with the cheap `gfs.resolve` primitive (gfsc authorizes `read`+ * before revealing any metadata, so an unshared resource 403s WITHOUT downloading+ * its bytes). A per-resource 403 unmounts the body (its cleanup revokes the object+ * URL) and renders the denial reason; a session-authority failure still routes to+ * the shared revoke, never to this local `denied` state.*/export function FilePreviewPage({gfsUri,@@ -29,8 +59,14 @@ export function FilePreviewPage({}: FilePreviewPageProps) {const ctrl = useGfsBrowserController()const [reloadToken, setReloadToken] = useState(0)+ const [denied, setDenied] = useState<string | null>(null)const accessRevoked = ctrl.accessState === 'revoked'+ // Each previewed resource starts from a clean per-resource verdict.+ useEffect(() => {+ setDenied(null)+ }, [gfsUri])+// R-4: when the authority controller detects a revocation while this tab is// mounted, bump the reload token so the body re-fetches and fails closed// instead of leaving already-rendered bytes on screen.@@ -40,14 +76,33 @@ export function FilePreviewPage({const handleDownloadError = useCallback((error: unknown) => {- ctrl.handleAuthorityFailure(- error instanceof Error ? error.message : String(error),- 'operation'- )+ ctrl.handleAuthorityFailure(toMessage(error), 'operation')},[ctrl])+ const revalidateAccess = useCallback(async () => {+ if (denied || accessRevoked) return+ try {+ await window.clerum.gfs.resolve(gfsUri)+ } catch (error) {+ const message = toMessage(error)+ // A session-authority failure revokes the shared session (H2 path); the+ // body then remounts and fails closed. A per-resource 403 is local to this+ // preview — drop its bytes here without touching the session.+ if (ctrl.handleAuthorityFailure(message, 'operation')) return+ if (isPerResourceAccessDenial(message)) setDenied(message)+ }+ }, [accessRevoked, ctrl, denied, gfsUri])++ useEffect(() => {+ const onFocus = () => {+ void revalidateAccess()+ }+ window.addEventListener('focus', onFocus)+ return () => window.removeEventListener('focus', onFocus)+ }, [revalidateAccess])+// Remounting the body on a reload bump discards any stale bytes and re-runs the// fetch from scratch — the simplest correct "re-dispatch the fetch" (§3.B.3).const bodyKey = `${gfsUri}:${reloadToken}`@@ -55,38 +110,44 @@ export function FilePreviewPage({return (<section className="page"><div className="da-gfs-preview-page">- {fileKind === 'image' ? (- <GfsImagePreviewBody- key={bodyKey}- byteLength={byteLength}- fileName={fileName}- gfsUri={gfsUri}- mimeType={mimeType ?? ''}- onDownloadError={handleDownloadError}- headingLevel={2}- />- ) : null}- {fileKind === 'markdown' ? (- <GfsMarkdownPreviewBody- key={bodyKey}- byteLength={byteLength}- fileName={fileName}- gfsUri={gfsUri}- onDownloadError={handleDownloadError}- headingLevel={2}- />- ) : null}- {fileKind === 'video' ? (- <GfsVideoPreviewBody- key={bodyKey}- byteLength={byteLength}- fileName={fileName}- gfsUri={gfsUri}- mimeType={mimeType ?? ''}- onDownloadError={handleDownloadError}- headingLevel={2}- />- ) : null}+ {denied ? (+ <EmptyState title="You no longer have access to this file" body={denied} />+ ) : (+ <>+ {fileKind === 'image' ? (+ <GfsImagePreviewBody+ key={bodyKey}+ byteLength={byteLength}+ fileName={fileName}+ gfsUri={gfsUri}+ mimeType={mimeType ?? ''}+ onDownloadError={handleDownloadError}+ headingLevel={2}+ />+ ) : null}+ {fileKind === 'markdown' ? (+ <GfsMarkdownPreviewBody+ key={bodyKey}+ byteLength={byteLength}+ fileName={fileName}+ gfsUri={gfsUri}+ onDownloadError={handleDownloadError}+ headingLevel={2}+ />+ ) : null}+ {fileKind === 'video' ? (+ <GfsVideoPreviewBody+ key={bodyKey}+ byteLength={byteLength}+ fileName={fileName}+ gfsUri={gfsUri}+ mimeType={mimeType ?? ''}+ onDownloadError={handleDownloadError}+ headingLevel={2}+ />+ ) : null}+ </>+ )}</div></section>)diff --git a/desktop-app/ui/src/pages/__tests__/FilePreviewPage.test.tsx b/desktop-app/ui/src/pages/__tests__/FilePreviewPage.test.tsxindex c01f04e77..a9df975fb 100644--- a/desktop-app/ui/src/pages/__tests__/FilePreviewPage.test.tsx+++ b/desktop-app/ui/src/pages/__tests__/FilePreviewPage.test.tsx@@ -1,6 +1,7 @@// @vitest-environment jsdomimport { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { cleanup, render, screen, waitFor } from '@testing-library/react'+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { resolveDeniedMessage } from '@/gfs/__fixtures__/gfsProducerFixtures'import { FilePreviewPage } from '../FilePreviewPage'const hookMock = vi.hoisted(() => ({@@ -9,10 +10,14 @@ const hookMock = vi.hoisted(() => ({vi.mock('@hooks/domain/useGfsBrowserController', () => hookMock)-function controller(accessState: 'active' | 'revoked' = 'active') {+function controller(+ accessState: 'active' | 'revoked' = 'active',+ handleAuthorityFailure: (message: string, surface?: 'discovery' | 'operation') => boolean = () =>+ false+) {return {accessState,- handleAuthorityFailure: vi.fn(() => false),+ handleAuthorityFailure: vi.fn(handleAuthorityFailure),}}@@ -26,6 +31,21 @@ function stubDownload(impl: () => Promise<{ bytes: ArrayBuffer }>) {return downloadPreview}+// Preview + the per-resource re-check primitive (`gfs.resolve`) the focus+// revalidation calls. `resolve` rejects to model an unshared resource.+function stubGfs(opts: {+ downloadPreview: () => Promise<{ bytes: ArrayBuffer }>+ resolve: () => Promise<unknown>+}) {+ const downloadPreview = vi.fn(opts.downloadPreview)+ const resolve = vi.fn(opts.resolve)+ Object.defineProperty(window, 'clerum', {+ configurable: true,+ value: { gfs: { downloadPreview, resolve } },+ })+ return { downloadPreview, resolve }+}+describe('FilePreviewPage', () => {beforeEach(() => {Object.defineProperty(URL, 'createObjectURL', {@@ -133,4 +153,97 @@ describe('FilePreviewPage', () => {expect(screen.getByRole('heading', { name: 'secret.png', level: 2 })).toBeTruthy()expect(downloadPreview).toHaveBeenCalledTimes(2)})++ // R1-H6: a persistent preview tab outlives the grant that opened it. A+ // per-RESOURCE unshare (gfs.read now 403s for THIS file, session still valid)+ // must drop the rendered bytes and the Copy affordance on window focus WITHOUT+ // a tab switch/remount — otherwise the image stays on screen and Copy keeps+ // writing the PNG. This is distinct from the session-401 path (H2) above.+ it('drops the previewed bytes and Copy on focus when the resource is unshared (R1-H6)', async () => {+ // Producer-derived denial: the exact ApiError message resolve rejects with+ // for a per-resource 403 (T1 — not a hand-written string).+ const deniedMessage = await resolveDeniedMessage('gfs://main/secret')++ const controllerState = controller('active')+ hookMock.useGfsBrowserController.mockReturnValue(controllerState)+ const { resolve } = stubGfs({+ downloadPreview: async () => ({ bytes: new Uint8Array([1, 2, 3]).buffer }),+ resolve: async () => {+ throw new Error(deniedMessage)+ },+ })++ render(+ <FilePreviewPage+ gfsUri="gfs://main/secret"+ fileName="secret.png"+ fileKind="image"+ mimeType="image/png"+ byteLength={3}+ />+ )++ // The bytes load and Copy is enabled.+ expect(await screen.findByAltText('Preview of secret.png')).toBeTruthy()+ const copyBefore = screen.getByRole('button', { name: 'Copy image to clipboard' })+ expect((copyBefore as HTMLButtonElement).disabled).toBe(false)++ // The file is unshared out-of-band → the next focus re-check 403s.+ fireEvent.focus(window)++ // The image AND the Copy affordance are gone (observable UI — T4), the+ // denial reason renders, and the tab was never remounted.+ await waitFor(() => expect(screen.queryByAltText('Preview of secret.png')).toBeNull())+ expect(screen.queryByRole('button', { name: 'Copy image to clipboard' })).toBeNull()+ expect(screen.getByText(deniedMessage)).toBeTruthy()+ expect(resolve).toHaveBeenCalledWith('gfs://main/secret')+ // A per-resource 403 is NOT a session-authority failure: it was routed+ // through handleAuthorityFailure (which declined) and did not revoke.+ expect(controllerState.handleAuthorityFailure).toHaveReturnedWith(false)+ })++ // H2 no-regress: a SESSION-authority failure discovered by the focus re-check+ // must route to the shared session revoke, NOT to the local per-resource+ // denied state (the two cases stay distinct).+ it('routes a session-authority failure on focus to the shared revoke, not local denial', async () => {+ const sessionMessage = await resolveDeniedMessage(+ 'gfs://main/secret',+ { code: 'unauthorized', message: 'not authenticated' },+ 401+ )++ // The controller classifies this as a session-authority failure (revokes).+ const controllerState = controller('active', () => true)+ hookMock.useGfsBrowserController.mockReturnValue(controllerState)+ stubGfs({+ downloadPreview: async () => ({ bytes: new Uint8Array([1, 2, 3]).buffer }),+ resolve: async () => {+ throw new Error(sessionMessage)+ },+ })++ render(+ <FilePreviewPage+ gfsUri="gfs://main/secret"+ fileName="secret.png"+ fileKind="image"+ mimeType="image/png"+ byteLength={3}+ />+ )++ expect(await screen.findByAltText('Preview of secret.png')).toBeTruthy()++ fireEvent.focus(window)++ await waitFor(() =>+ expect(controllerState.handleAuthorityFailure).toHaveBeenCalledWith(+ sessionMessage,+ 'operation'+ )+ )+ // The session path handled it; the local per-resource denial did NOT fire.+ expect(controllerState.handleAuthorityFailure).toHaveReturnedWith(true)+ expect(screen.queryByText('You no longer have access to this file')).toBeNull()+ })})