Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(gfs): add self-hosted desktop operator parity
Alfredo Lopez6bb4f8517047
diff --git a/control-api/src/auth/gfsToken.ts b/control-api/src/auth/gfsToken.tsindex c7e1ad962..24bdb6d18 100644--- a/control-api/src/auth/gfsToken.ts+++ b/control-api/src/auth/gfsToken.ts@@ -46,6 +46,14 @@ export interface GfsTokenClaims extends jwt.JwtPayload {drive: stringscopes: GfsScope[]pathBindings: GfsPathBinding[]+ brokeredAuthority?: GfsBrokeredAuthority+ principalType?: 'user' | 'control-admin'+}++export interface GfsBrokeredAuthority {+ desktopUserId: string+ controlAdminId: string+ authoritySource: 'linked-admin'}/**@@ -81,12 +89,16 @@ export function signGfsToken(input: {drive: stringscopes: readonly GfsScope[]pathBindings?: readonly GfsPathBinding[]+ brokeredAuthority?: GfsBrokeredAuthority+ principalType?: 'user' | 'control-admin'}): { token: string; expiresInSeconds: number } {const claims: Omit<GfsTokenClaims, 'iat' | 'exp'> = {sub: input.subject,drive: input.drive,scopes: [...input.scopes],pathBindings: input.pathBindings ? input.pathBindings.map(b => ({ ...b })) : [],+ ...(input.brokeredAuthority ? { brokeredAuthority: { ...input.brokeredAuthority } } : {}),+ ...(input.principalType ? { principalType: input.principalType } : {}),}const token = jwt.sign(claims, config.rpcJwtPrivateKey, {algorithm: 'RS256',diff --git a/control-api/src/config.ts b/control-api/src/config.tsindex 033cb2afe..d78421ad4 100644--- a/control-api/src/config.ts+++ b/control-api/src/config.ts@@ -28,6 +28,7 @@ type Config = {desktopRpcProxyBaseUrl: stringdesktopProfileUiBaseUrl: stringdesktopAppName: string+ desktopGfsOperatorLinkingEnabled: booleancontrolUiBaseUrl: stringcontrolUiAppName: stringsessionJwtPrivateKey: string@@ -339,6 +340,13 @@ function parseRegistryConnectionMode(): 'managed' | 'self-hosted' {throw new Error(`REGISTRY_CONNECTION_MODE must be 'managed' or 'self-hosted' (got '${raw}')`)}+function failClosedBooleanFromEnv(name: string): boolean {+ const raw = process.env[name]+ if (raw === undefined || raw === '' || raw === 'false') return false+ if (raw === 'true') return true+ throw new Error(`${name} must be 'true' or 'false' (got '${raw}')`)+}+function publicKeyFromPrivateKey(privateKey: string): string {return createPublicKey(privateKey).export({ type: 'spki', format: 'pem' }).toString()}@@ -549,6 +557,11 @@ export const config: Config = {desktopProfileUiBaseUrl:process.env.CONTROL_API_DESKTOP_PROFILE_UI_BASE_URL || 'http://127.0.0.1:3001',desktopAppName: process.env.CONTROL_API_DESKTOP_APP_NAME || 'Evenfire',+ // Narrow, explicit elevation switch. Missing/false is intentionally OFF;+ // this must not inherit registry, password-seeding, or generic deploy mode.+ desktopGfsOperatorLinkingEnabled: failClosedBooleanFromEnv(+ 'CONTROL_API_DESKTOP_GFS_OPERATOR_LINKING_ENABLED'+ ),controlUiBaseUrl: process.env.CONTROL_API_CONTROL_UI_BASE_URL || 'http://127.0.0.1:3000',controlUiAppName: process.env.CONTROL_API_CONTROL_UI_APP_NAME || 'Evenfire',sessionJwtPrivateKey: normalizePem(diff --git a/control-api/src/db.ts b/control-api/src/db.tsindex cd7a8f2a1..cfd65cd70 100644--- a/control-api/src/db.ts+++ b/control-api/src/db.ts@@ -2601,6 +2601,52 @@ async function reconcilePluginWorkloadSdkRuntimeContracts(db: DbClient): Promise`)}+async function applyGfsDesktopOperatorLinksSchema(db: DbClient): Promise<void> {+ await db.query(`+ -- Current-state, one-to-one identity link. Revocation is represented by+ -- deleting this row only after its governed lifecycle event is appended.+ -- Deliberately no email backfill: link creation always requires both exact+ -- server-known UUIDs.+ CREATE TABLE IF NOT EXISTS gfs_desktop_operator_links (+ user_id UUID PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,+ control_admin_id UUID NOT NULL UNIQUE REFERENCES control_admin_users(id) ON DELETE CASCADE,+ source TEXT NOT NULL CHECK (source IN ('initial_setup')),+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()+ );++ REVOKE ALL ON TABLE gfs_desktop_operator_links FROM PUBLIC;+ GRANT SELECT, INSERT, DELETE ON TABLE gfs_desktop_operator_links TO control_api_runtime;+ `)+}++async function applyGfsAuditActorCorrelationSchema(db: DbClient): Promise<void> {+ await db.query(`+ ALTER TABLE gfs_audit+ ADD COLUMN IF NOT EXISTS desktop_user_id UUID NULL,+ ADD COLUMN IF NOT EXISTS authority_source TEXT NULL;++ DO $$ BEGIN+ ALTER TABLE gfs_audit+ ADD CONSTRAINT gfs_audit_actor_correlation_valid+ CHECK (+ (desktop_user_id IS NULL AND authority_source IS NULL)+ OR+ (desktop_user_id IS NOT NULL+ AND authority_source = 'user-session'+ AND actor_on_behalf_of IS NULL)+ OR+ (desktop_user_id IS NOT NULL+ AND authority_source = 'linked-admin'+ AND actor_on_behalf_of IS NOT NULL)+ );+ EXCEPTION WHEN duplicate_object THEN NULL;+ END $$;++ CREATE INDEX IF NOT EXISTS gfs_audit_desktop_user_time_idx+ ON gfs_audit (desktop_user_id, event_time);+ `)+}+// Exported (read-only) so the migration-order invariant test can assert the// array is monotonic by version-string. Applied strictly in array order and// tracked by full version-string in `schema_migrations`, so a non-monotonic@@ -5463,6 +5509,14 @@ export const CONTROL_API_MIGRATIONS: DbMigration[] = [version: '0090_plugin_workload_sdk_runtime_contract_reconciliation',apply: reconcilePluginWorkloadSdkRuntimeContracts,},+ {+ version: '0091_gfs_desktop_operator_links',+ apply: applyGfsDesktopOperatorLinksSchema,+ },+ {+ version: '0092_gfs_audit_actor_correlation',+ apply: applyGfsAuditActorCorrelationSchema,+ },]async function consolidateWorkflowAllowedUsersToTriggers(db: DbClient): Promise<void> {diff --git a/control-api/src/gfs/externalAuthority.ts b/control-api/src/gfs/externalAuthority.tsnew file mode 100644index 000000000..60a19ef47--- /dev/null+++ b/control-api/src/gfs/externalAuthority.ts@@ -0,0 +1,111 @@+import type { NextFunction, Request, Response } from 'express'+import { config } from '../config.js'+import {+ type GfsDesktopOperatorLink,+ GfsDesktopOperatorLinkError,+ gfsDesktopOperatorLinkService,+} from '../services/gfsDesktopOperatorLinkService.js'++export type ExternalGfsUserAuthority = {+ kind: 'user-session'+ desktopUserId: string+ tokenSubject: string+}++export type ExternalGfsLinkedAdminAuthority = {+ kind: 'linked-admin'+ desktopUserId: string+ controlAdminId: string+ tokenSubject: string+ authoritySource: 'linked-admin'+}++export type ExternalGfsAuthority = ExternalGfsUserAuthority | ExternalGfsLinkedAdminAuthority++export class ExternalGfsAuthorityError extends Error {+ constructor(+ readonly status: 403 | 503,+ readonly code: 'gfs_operator_link_invalid' | 'gfs_authority_unavailable',+ options?: { cause?: unknown }+ ) {+ super(code, options?.cause === undefined ? undefined : { cause: options.cause })+ this.name = 'ExternalGfsAuthorityError'+ }+}++type AuthorityDependencies = {+ linkingEnabled: boolean+ resolveActiveLink(desktopUserId: string): Promise<GfsDesktopOperatorLink | null>+}++function userAuthority(desktopUserId: string): ExternalGfsUserAuthority {+ return { kind: 'user-session', desktopUserId, tokenSubject: desktopUserId }+}++/**+ * Resolve the effective GFS authority for one authenticated Desktop user.+ *+ * The feature flag is checked before the persisted link is read. A disabled or+ * missing flag therefore cannot elevate a request. An absent row means an+ * ordinary user session, while any malformed, conflicting, missing-admin, or+ * inactive-admin row fails closed instead of falling back to user authority.+ */+export async function resolveExternalGfsAuthority(+ desktopUserId: string,+ dependencies: AuthorityDependencies = {+ linkingEnabled: config.desktopGfsOperatorLinkingEnabled === true,+ resolveActiveLink: id => gfsDesktopOperatorLinkService.resolveActiveLink(id),+ }+): Promise<ExternalGfsAuthority> {+ if (dependencies.linkingEnabled !== true) return userAuthority(desktopUserId)++ let link: GfsDesktopOperatorLink | null+ try {+ link = await dependencies.resolveActiveLink(desktopUserId)+ } catch (error) {+ if (error instanceof GfsDesktopOperatorLinkError && error.code !== 'resolution_failed') {+ throw new ExternalGfsAuthorityError(403, 'gfs_operator_link_invalid', { cause: error })+ }+ throw new ExternalGfsAuthorityError(503, 'gfs_authority_unavailable', { cause: error })+ }+ if (!link) return userAuthority(desktopUserId)++ if (link.desktopUserId !== desktopUserId || link.source !== 'initial_setup') {+ throw new ExternalGfsAuthorityError(403, 'gfs_operator_link_invalid')+ }+ return {+ kind: 'linked-admin',+ desktopUserId,+ controlAdminId: link.controlAdminId,+ tokenSubject: link.controlAdminId,+ authoritySource: 'linked-admin',+ }+}++export type RequestWithExternalGfsAuthority = Request & {+ gfsAuthority?: ExternalGfsAuthority+}++export async function attachExternalGfsAuthority(+ req: Request,+ res: Response,+ next: NextFunction+): Promise<void> {+ const desktopUserId = (req as Request & { externalAuth?: { userId?: string } }).externalAuth+ ?.userId+ if (!desktopUserId) {+ res.status(401).json({ error: 'unauthenticated' })+ return+ }+ try {+ ;(req as RequestWithExternalGfsAuthority).gfsAuthority =+ await resolveExternalGfsAuthority(desktopUserId)+ next()+ } catch (error) {+ if (error instanceof ExternalGfsAuthorityError) {+ res.status(error.status).json({ error: error.code })+ return+ }+ next(error)+ }+}diff --git a/control-api/src/routes/admin/auth.ts b/control-api/src/routes/admin/auth.tsindex e379623e6..9685106d2 100644--- a/control-api/src/routes/admin/auth.ts+++ b/control-api/src/routes/admin/auth.ts@@ -173,12 +173,14 @@ export function createAdminAuthRouter(): Router {// already created.try {await provisionAdminDesktopWorkspace({+ controlAdminId: created.id,email,displayName: username,passwordHash,agentNames: config.adminDefaultAgentNames,contextIds: config.adminDefaultContextIds,seedPassword: seedDesktopPassword,+ linkDesktopOperator: config.desktopGfsOperatorLinkingEnabled,})} catch (err) {// Intentionally logs only err + email — never passwordHash.diff --git a/control-api/src/routes/admin/controlAdmins.ts b/control-api/src/routes/admin/controlAdmins.tsindex bee5ab8d9..211e2e9cf 100644--- a/control-api/src/routes/admin/controlAdmins.ts+++ b/control-api/src/routes/admin/controlAdmins.ts@@ -28,6 +28,10 @@ import {revokePendingInvitation,} from '../../services/directory/index.js'import { normalizeTeamRoleInput } from '../../services/directory/types.js'+import {+ GfsDesktopOperatorLinkError,+ gfsDesktopOperatorLinkService,+} from '../../services/gfsDesktopOperatorLinkService.js'function readString(value: unknown): string {return String(value || '').trim()@@ -377,6 +381,72 @@ export function createAdminControlAdminsRouter(): Router {}})+ router.delete(+ '/admin/control-admins/:adminId/gfs-operator-link',+ async (req: UiAuthedRequest, res, next) => {+ try {+ const operatorSub = req.adminAuth?.sub+ if (!operatorSub) {+ res.status(401).json({ error: 'Unauthorized' })+ return+ }++ const adminId = readString(req.params.adminId)+ if (!adminId) {+ res.status(400).json({ error: 'adminId is required' })+ return+ }++ const targetAdmin = await findAdminById(adminId)+ if (!targetAdmin) {+ res.status(404).json({ error: 'not_found' })+ return+ }++ // Resolve the exact persisted pair server-side. The caller cannot+ // choose a Desktop user or ask the endpoint to create/reassign one.+ const link = await gfsDesktopOperatorLinkService.getLinkForControlAdmin(adminId)+ if (!link) {+ res.status(200).json({+ revoked: false,+ gfsOperatorLinkStatus: 'revoked',+ controlAdminId: adminId,+ desktopUserId: null,+ })+ return+ }++ const result = await gfsDesktopOperatorLinkService.unlink({+ desktopUserId: link.desktopUserId,+ controlAdminId: link.controlAdminId,+ operatorSub,+ })+ res.status(200).json({+ revoked: result.unlinked,+ gfsOperatorLinkStatus: 'revoked',+ controlAdminId: adminId,+ desktopUserId: link.desktopUserId,+ })+ } catch (error) {+ if (error instanceof GfsDesktopOperatorLinkError) {+ if (error.code === 'invalid_input') {+ res.status(400).json({ error: error.code })+ return+ }+ if (error.code === 'control_admin_not_found') {+ res.status(404).json({ error: error.code })+ return+ }+ if (error.code === 'link_conflict' || error.code === 'malformed_link') {+ res.status(409).json({ error: error.code })+ return+ }+ }+ next(error)+ }+ }+ )+router.post('/admin/control-admins/:adminId/member', async (req: UiAuthedRequest, res, next) => {try {const currentAdminId = req.adminAuth?.subdiff --git a/control-api/src/routes/external/gfs.ts b/control-api/src/routes/external/gfs.tsindex 95c5263e0..1dea0cc4e 100644--- a/control-api/src/routes/external/gfs.ts+++ b/control-api/src/routes/external/gfs.ts@@ -1,4 +1,5 @@import { type NextFunction, Router } from 'express'+import { randomUUID } from 'node:crypto'import {GFS_DELETE_SCOPE,GFS_READ_SCOPE,@@ -7,8 +8,21 @@ import {} from '../../auth/gfsToken.js'import { config } from '../../config.js'import { pool } from '../../db.js'+import {+ type ExternalGfsAuthority,+ type RequestWithExternalGfsAuthority,+ attachExternalGfsAuthority,+} from '../../gfs/externalAuthority.js'import { isValidHostSubjectId, makeHostSubjectId } from '../../gfs/hostSubject.js'-import { GfsTreeError, clampLimit, decodeCursor, encodeCursor } from '../../gfs/tree.js'+import { DbResolveStore } from '../../gfs/resolve.js'+import {+ DbChildrenStore,+ GfsTreeError,+ clampLimit,+ decodeCursor,+ encodeCursor,+ listChildrenPaged,+} from '../../gfs/tree.js'import { asyncHandler } from '../../http/asyncHandler.js'import {type ExternalAuthedRequest,@@ -29,7 +43,7 @@ import {sendGfsGrantError,} from '../gfs/grants.js'import { handlePatch } from '../gfs/resources.js'-import { handleShareDelete, handleShareWrite } from '../gfs/shares.js'+import { handleShareDelete, handleShareListForCaller, handleShareWrite } from '../gfs/shares.js'import { GFS_DEFAULT_DRIVE, parseRequestedGfsScopes } from '../gfs/token.js'// A gfs:// URI is `gfs://<drive>/<path-or-rid>`; cap it so an oversized value is@@ -39,6 +53,31 @@ const ACCESSIBLE_RESOURCE_DEFAULT_LIMIT = 100type ExternalGfsRequest = ExternalAuthedRequest & {gfsSubjectKeys?: string[]+ gfsRequestId?: string+ gfsAuthority?: ExternalGfsAuthority+}++const UUID_ANY_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i++function attachExternalGfsRequestId(+ req: import('express').Request,+ res: import('express').Response,+ next: NextFunction+): void {+ const raw = req.header('x-request-id')?.trim()+ const requestId =+ raw && UUID_ANY_RE.test(raw)+ ? raw.toLowerCase()+ : ((req as { correlationId?: string }).correlationId ?? randomUUID())+ ;(req as ExternalGfsRequest).gfsRequestId = requestId+ res.setHeader('x-request-id', requestId)+ next()+}++function authorityOf(req: ExternalGfsRequest): ExternalGfsAuthority {+ const authority = req.gfsAuthority+ if (!authority) throw new GfsGrantError(401, 'unauthenticated')+ return authority}function ridOf(resourceId: string): string {@@ -58,6 +97,8 @@ function subjectColumns(subjects: Set<string>): { types: string[]; ids: string[]}async function externalCallerSubjects(req: ExternalAuthedRequest): Promise<Set<string>> {+ const authority = authorityOf(req as ExternalGfsRequest)+ if (authority.kind === 'linked-admin') return new Set(['operator:'])const claims = req.externalAuth!const subjects = new Set<string>([`user:${claims.userId}`])if (claims.teamId) subjects.add(`team:${claims.teamId}`)@@ -119,6 +160,10 @@ async function assertHostTargetsWithinCallerAgents(next: NextFunction): Promise<void> {const externalReq = req as ExternalGfsRequest+ if (authorityOf(externalReq).kind === 'linked-admin') {+ next()+ return+ }const body = (externalReq.body ?? {}) as Record<string, unknown>const plural = Array.isArray(body.subjects)const values = plural@@ -173,6 +218,7 @@ export function createExternalGfsRouter(): Router {// Every gfs user route is on the Session-JWT plane: the user session token// (x-user-session-token, forwarded by external-rest-api) is required.router.use('/external/gfs', requireValidExternalSessionToken)+ router.use('/external/gfs', attachExternalGfsRequestId)// Per-user token bucket on the DELEGATION plane only (grants + shares),// mirroring the admin plane's grantsRateLimit but in a DISTINCT bucket so the@@ -187,8 +233,14 @@ export function createExternalGfsRouter(): Router {bucketType: 'gfs_grants_external',maxPerMinute: 30,getBucketKey: req => {- const userId = (req as ExternalAuthedRequest).externalAuth?.userId- return userId ? `gfsgrants-ext:${userId}` : 'gfsgrants-ext:__no_user__'+ const authority = (req as RequestWithExternalGfsAuthority).gfsAuthority+ if (authority?.kind === 'linked-admin') {+ return `gfsgrants-ext:linked-admin:${authority.controlAdminId}`+ }+ if (authority?.kind === 'user-session') {+ return `gfsgrants-ext:user:${authority.desktopUserId}`+ }+ return 'gfsgrants-ext:__no_authority__'},})@@ -212,11 +264,16 @@ export function createExternalGfsRouter(): Router {drive,scopes,pathBindings: [],+ principalType: 'user',})res.status(200).json({ token, expiresInSeconds })}))+ // Public token mint above is deliberately user-only. Effective linked-admin+ // authority is resolved only for the internal broker routes below.+ router.use('/external/gfs', asyncHandler(attachExternalGfsAuthority))+// ── delegation: reuse the EXISTING grant/share handlers (caller-agnostic) ──// resolveCaller(req) reads req.externalAuth → user:<id> plus all active team// memberships resolved here; assertMayGrant enforces no-escalation (a user may@@ -249,6 +306,12 @@ export function createExternalGfsRouter(): Router {asyncHandler(attachExternalGfsCallerSubjects),asyncHandler(handleShareWrite))+ router.get(+ '/external/gfs/shares',+ externalGrantsRateLimit,+ asyncHandler(attachExternalGfsCallerSubjects),+ asyncHandler(handleShareListForCaller)+ )router.delete('/external/gfs/shares/:id',externalGrantsRateLimit,@@ -343,6 +406,34 @@ export function createExternalGfsRouter(): Router {'/external/gfs/resources',asyncHandler(async (req: ExternalAuthedRequest, res) => {const drive = driveOf(req.query.drive)+ const authority = authorityOf(req as ExternalGfsRequest)+ if (authority.kind === 'linked-admin') {+ const root = await new DbResolveStore(pool).getByPath(drive, '/')+ if (!root) {+ res.status(404).json({+ ok: false,+ error: { code: 'drive_not_seeded', message: 'drive root is not seeded' },+ })+ return+ }+ try {+ const page = await listChildrenPaged(new DbChildrenStore(pool), drive, root.resourceId, {+ limit: req.query.limit,+ cursor: typeof req.query.cursor === 'string' ? req.query.cursor : undefined,+ })+ res.status(200).json({+ ok: true,+ data: { ...page, rootResourceId: root.resourceId, view: 'operator' },+ })+ } catch (error) {+ if (error instanceof GfsTreeError) {+ res.status(400).json({ ok: false, error: { code: error.code, message: error.message } })+ return+ }+ throw error+ }+ return+ }const subjects = await externalCallerSubjects(req)const { types, ids } = subjectColumns(subjects)if (types.length === 0) {@@ -520,11 +611,21 @@ async function proxyReadToGfsc(drive: string,gfscPath: string): Promise<void> {- const claims = req.externalAuth!+ const authority = authorityOf(req as ExternalGfsRequest)const { token } = signGfsToken({- subject: claims.userId,+ subject: authority.tokenSubject,drive,scopes: [GFS_READ_SCOPE],+ principalType: authority.kind === 'linked-admin' ? 'control-admin' : 'user',+ ...(authority.kind === 'linked-admin'+ ? {+ brokeredAuthority: {+ desktopUserId: authority.desktopUserId,+ controlAdminId: authority.controlAdminId,+ authoritySource: authority.authoritySource,+ },+ }+ : {}),})const target = `${config.gfscBaseUrl.replace(/\/+$/, '')}${gfscPath}`let upstream: Response@@ -536,7 +637,10 @@ async function proxyReadToGfsc(try {upstream = await fetch(target, {method: 'GET',- headers: { authorization: `Bearer ${token}` },+ headers: {+ authorization: `Bearer ${token}`,+ 'x-request-id': (req as ExternalGfsRequest).gfsRequestId!,+ },signal: readDeadline.signal,})} catch (err) {@@ -604,15 +708,26 @@ async function proxyMutationToGfsc(gfscPath: string,scope: typeof GFS_WRITE_SCOPE | typeof GFS_DELETE_SCOPE): Promise<void> {- const claims = req.externalAuth!+ const authority = authorityOf(req as ExternalGfsRequest)const { token } = signGfsToken({- subject: claims.userId,+ subject: authority.tokenSubject,drive,scopes: [scope],+ principalType: authority.kind === 'linked-admin' ? 'control-admin' : 'user',+ ...(authority.kind === 'linked-admin'+ ? {+ brokeredAuthority: {+ desktopUserId: authority.desktopUserId,+ controlAdminId: authority.controlAdminId,+ authoritySource: authority.authoritySource,+ },+ }+ : {}),})const target = `${config.gfscWriteBaseUrl.replace(/\/+$/, '')}${gfscPath}`const headers: Record<string, string> = { 'content-type': 'application/json' }headers['author' + 'ization'] = ['Bearer', token].join(' ')+ headers['x-request-id'] = (req as ExternalGfsRequest).gfsRequestId!let upstream: Response// A TOTAL deadline (not the header-only one the streaming read proxies use):// a mutation response is a small JSON body, so bounding the whole fetch+readdiff --git a/control-api/src/routes/gfs/grants.ts b/control-api/src/routes/gfs/grants.tsindex f745aaf17..a745cc9ab 100644--- a/control-api/src/routes/gfs/grants.ts+++ b/control-api/src/routes/gfs/grants.ts@@ -1,6 +1,7 @@import type { Request, Router } from 'express'import { createHash } from 'node:crypto'import { type DbClient, pool, withTransaction } from '../../db.js'+import type { ExternalGfsAuthority } from '../../gfs/externalAuthority.js'import { isValidHostSubjectId } from '../../gfs/hostSubject.js'import { asyncHandler } from '../../http/asyncHandler.js'import { requireAuthForControlUI } from '../../middleware/controlUIAuth.js'@@ -70,6 +71,26 @@ export interface GfsCaller {subjects: Set<string>/** Audit actor key (`operator:` or `user:<uuid>`). */actorKey: string+ /** Effective admin for a linked Desktop operator; never the Desktop actor. */+ effectiveControlAdminId?: string+ /** Authenticated Desktop actor for brokered external requests. */+ desktopUserId?: string+ /** Broker authority attribution; independent of authorization_source evidence. */+ authoritySource?: 'user-session' | 'linked-admin'+ /** Persisted legacy/effective actor_on_behalf_of value. */+ actorOnBehalfOf?: string | null+}++export function callerAuditFields(caller: GfsCaller): {+ actorOnBehalfOf: string | null+ desktopUserId?: string+ authoritySource?: 'user-session' | 'linked-admin'+} {+ return {+ actorOnBehalfOf: caller.actorOnBehalfOf ?? null,+ ...(caller.desktopUserId ? { desktopUserId: caller.desktopUserId } : {}),+ ...(caller.authoritySource ? { authoritySource: caller.authoritySource } : {}),+ }}type RequestWithResolvedGfsSubjects = Request & {@@ -86,7 +107,24 @@ type RequestWithResolvedGfsSubjects = Request & {export function resolveCaller(req: Request): GfsCaller {const admin = (req as { adminAuth?: { sub?: string } }).adminAuthif (admin?.sub) {- return { isOperator: true, subjects: new Set(['operator:']), actorKey: 'operator:' }+ return {+ isOperator: true,+ subjects: new Set(['operator:']),+ actorKey: 'operator:',+ actorOnBehalfOf: 'operator:',+ }+ }+ const authority = (req as { gfsAuthority?: ExternalGfsAuthority }).gfsAuthority+ if (authority?.kind === 'linked-admin') {+ return {+ isOperator: true,+ subjects: new Set(['operator:']),+ actorKey: 'operator:',+ effectiveControlAdminId: authority.controlAdminId,+ desktopUserId: authority.desktopUserId,+ authoritySource: 'linked-admin',+ actorOnBehalfOf: authority.controlAdminId,+ }}const external = (req as { externalAuth?: { userId?: string; teamId?: string | null } }).externalAuth@@ -96,7 +134,14 @@ export function resolveCaller(req: Request): GfsCaller {const subjects = new Set(preResolved && preResolved.length > 0 ? preResolved : [key])subjects.add(key)if (external.teamId) subjects.add(`team:${external.teamId}`)- return { isOperator: false, subjects, actorKey: key }+ return {+ isOperator: false,+ subjects,+ actorKey: key,+ desktopUserId: external.userId,+ authoritySource: 'user-session',+ actorOnBehalfOf: null,+ }}throw new GfsGrantError(401, 'unauthenticated')}@@ -497,6 +542,9 @@ export async function auditMutation(outcome: 'allowed' | 'denied'requestId?: stringsourceIp?: string+ actorOnBehalfOf?: string | null+ desktopUserId?: string+ authoritySource?: 'user-session' | 'linked-admin'}): Promise<string | null> {const gfsUri = `gfs://${params.drive}/${params.resourceId}`@@ -507,24 +555,30 @@ export async function auditMutation(params.op,gfsUri,params.outcome,- params.actorKey,+ params.actorOnBehalfOf === undefined ? params.actorKey : (params.actorOnBehalfOf ?? ''),+ params.desktopUserId ?? '',+ params.authoritySource ?? '',params.requestId ?? '',].join(' ')).digest('hex')const result = await db.query(- `INSERT INTO gfs_audit (subject, actor_on_behalf_of, op, gfs_uri, outcome, source_ip, request_id, row_hash)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8)+ `INSERT INTO gfs_audit+ (subject, actor_on_behalf_of, op, gfs_uri, outcome, source_ip, request_id,+ row_hash, desktop_user_id, authority_source)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::uuid, $10)RETURNING sequence_no::text AS id`,[params.targetKey,- params.actorKey,+ params.actorOnBehalfOf === undefined ? params.actorKey : params.actorOnBehalfOf,params.op,gfsUri,params.outcome,params.sourceIp ?? null,params.requestId ?? null,rowHash,+ params.desktopUserId ?? null,+ params.authoritySource ?? null,])const row = result.rows[0] as { id?: unknown } | undefined@@ -642,7 +696,9 @@ export function permissionReadFilter(req: Request): { drive: string; resourceId:}export function requestIdOf(req: Request): string | undefined {- const id = (req as { correlationId?: string }).correlationId+ const id =+ (req as { gfsRequestId?: string; correlationId?: string }).gfsRequestId ??+ (req as { correlationId?: string }).correlationIdreturn typeof id === 'string' && id.length > 0 ? id : undefined}@@ -652,6 +708,9 @@ type GfsPermissionEventOperator = {}function permissionEventOperator(req: Request, caller: GfsCaller): GfsPermissionEventOperator {+ if (caller.effectiveControlAdminId) {+ return { kind: 'control_admin', sub: caller.effectiveControlAdminId }+ }const adminSub = (req as { adminAuth?: { sub?: string } }).adminAuth?.subif (adminSub) return { kind: 'control_admin', sub: adminSub }const userId = (req as { externalAuth?: { userId?: string } }).externalAuth?.userId@@ -798,6 +857,7 @@ export async function writeGfsGrantBatchInTransaction(auditIds.push(await auditMutation(db, {actorKey: params.caller.actorKey,+ ...callerAuditFields(params.caller),targetKey: subjectKey(subject),op: `grant.put[${params.permissions.join(',')}]`,drive: params.drive,@@ -994,7 +1054,9 @@ export async function handleGrantDelete(FOR UPDATE`,[id])- if (existing.rows.length === 0) return { kind: 'not_found' as const }+ if (existing.rows.length === 0) {+ return caller.isOperator ? { kind: 'not_found' as const } : { kind: 'hidden' as const }+ }const row = existing.rows[0] as {drive: stringresource_id: string@@ -1022,6 +1084,7 @@ export async function handleGrantDelete(if (!(error instanceof GfsGrantError)) throw errorconst auditId = await auditMutation(db, {actorKey: caller.actorKey,+ ...callerAuditFields(caller),targetKey: subjectKey(subject),op: 'grant.delete',drive: row.drive,@@ -1047,6 +1110,7 @@ export async function handleGrantDelete(await db.query(`DELETE FROM gfs_grants WHERE id = $1::uuid`, [id])const auditId = await auditMutation(db, {actorKey: caller.actorKey,+ ...callerAuditFields(caller),targetKey: subjectKey(subject),op: 'grant.delete',drive: row.drive,@@ -1073,6 +1137,10 @@ export async function handleGrantDelete(res.status(404).json({ error: 'grant_not_found' })return}+ if (result.kind === 'hidden') {+ res.status(403).json({ error: 'forbidden' })+ return+ }if (result.kind === 'denied') {res.status(result.error.status).json({ error: result.error.code })returndiff --git a/control-api/src/routes/gfs/proxy.ts b/control-api/src/routes/gfs/proxy.tsindex 62bc54d35..d4bd6888c 100644--- a/control-api/src/routes/gfs/proxy.ts+++ b/control-api/src/routes/gfs/proxy.ts@@ -52,7 +52,12 @@ export function registerGfsProxyRoute(router: Router): void {const subPath = req.url === '/' ? '' : req.urlconst target = `${gfscBaseUrlFor(req.method).replace(/\/+$/, '')}${subPath}`- const { token } = signGfsToken({ subject, drive: DEFAULT_DRIVE, scopes: [scope] })+ const { token } = signGfsToken({+ subject,+ drive: DEFAULT_DRIVE,+ scopes: [scope],+ principalType: 'control-admin',+ })const headers: Record<string, string> = {}headers['author' + 'ization'] = ['Bearer', token].join(' ')if (req.method !== 'GET' && req.method !== 'HEAD') {diff --git a/control-api/src/routes/gfs/resources.ts b/control-api/src/routes/gfs/resources.tsindex 012ad7fa4..7e98337f4 100644--- a/control-api/src/routes/gfs/resources.ts+++ b/control-api/src/routes/gfs/resources.ts@@ -370,7 +370,16 @@ export async function handlePatch(req: Request, res: Response): Promise<void> {const patched = await withTransaction(async db => {try {return await applyResourcePatch(db, caller, drive, id, body, async params => {- await auditMutation(db, { ...params, requestId, sourceIp })+ await auditMutation(db, {+ ...params,+ ...(Object.prototype.hasOwnProperty.call(caller, 'actorOnBehalfOf')+ ? { actorOnBehalfOf: caller.actorOnBehalfOf ?? null }+ : {}),+ ...(caller.desktopUserId ? { desktopUserId: caller.desktopUserId } : {}),+ ...(caller.authoritySource ? { authoritySource: caller.authoritySource } : {}),+ requestId,+ sourceIp,+ })})} catch (err) {if (err instanceof ResourcePatchError && err.status === 403) {diff --git a/control-api/src/routes/gfs/shares.ts b/control-api/src/routes/gfs/shares.tsindex 66890c290..5036e3ed7 100644--- a/control-api/src/routes/gfs/shares.ts+++ b/control-api/src/routes/gfs/shares.ts@@ -15,7 +15,9 @@ import {assertMayGrantBatch,assertMutationSubjectTransport,auditMutation,+ callerAuditFields,driveOf,+ heldPermissions,normalizeMutationSubjects,parsePermissions,permissionReadFilter,@@ -62,29 +64,7 @@ export function registerGfsShareRoutes(router: Router): void {export async function handleShareRead(req: Request, res: Response): Promise<void> {try {const { drive, resourceId } = permissionReadFilter(req)- const result = await pool.query(- `SELECT id, drive, resource_id, subject_type, subject_id, permissions, include_descendants- FROM gfs_shares- WHERE drive = $1 AND resource_id = $2::uuid- ORDER BY created_at ASC, id ASC`,- [drive, resourceId]- )- res.status(200).json({- items: (result.rows as Record<string, unknown>[]).map(row => {- const subjectId = String(row.subject_id ?? '')- return {- id: String(row.id),- drive: String(row.drive),- resourceId: String(row.resource_id),- subject: {- type: String(row.subject_type),- ...(subjectId ? { id: subjectId } : {}),- },- permissions: Array.isArray(row.permissions) ? row.permissions.map(String) : [],- includeDescendants: Boolean(row.include_descendants),- }- }),- })+ res.status(200).json({ items: await queryShareItems(drive, resourceId) })} catch (err) {if (err instanceof GfsGrantError) {sendGfsGrantError(res, err)@@ -94,6 +74,55 @@ export async function handleShareRead(req: Request, res: Response): Promise<void}}+async function queryShareItems(+ drive: string,+ resourceId: string+): Promise<Record<string, unknown>[]> {+ const result = await pool.query(+ `SELECT id, drive, resource_id, subject_type, subject_id, permissions, include_descendants+ FROM gfs_shares+ WHERE drive = $1 AND resource_id = $2::uuid+ ORDER BY created_at ASC, id ASC`,+ [drive, resourceId]+ )+ return (result.rows as Record<string, unknown>[]).map(row => {+ const subjectId = String(row.subject_id ?? '')+ return {+ id: String(row.id),+ drive: String(row.drive),+ resourceId: String(row.resource_id),+ subject: {+ type: String(row.subject_type),+ ...(subjectId ? { id: subjectId } : {}),+ },+ permissions: Array.isArray(row.permissions) ? row.permissions.map(String) : [],+ includeDescendants: Boolean(row.include_descendants),+ }+ })+}++/** External list parity with grants: ACL metadata requires manage_acl, and a+ * missing resource is indistinguishable from an inaccessible one. */+export async function handleShareListForCaller(req: Request, res: Response): Promise<void> {+ try {+ const caller = resolveCaller(req)+ const { drive, resourceId } = permissionReadFilter(req)+ if (!caller.isOperator) {+ const held = await heldPermissions(pool, caller, drive, resourceId)+ if (!held.includes('manage_acl')) {+ throw new GfsGrantError(403, 'manage_acl_required')+ }+ }+ res.status(200).json({ items: await queryShareItems(drive, resourceId) })+ } catch (error) {+ if (error instanceof GfsGrantError) {+ sendGfsGrantError(res, error)+ return+ }+ throw error+ }+}+export async function writeGfsShareBatchInTransaction(db: import('../../db.js').DbClient,params: {@@ -153,6 +182,7 @@ export async function writeGfsShareBatchInTransaction(auditIds.push(await auditMutation(db, {actorKey: params.caller.actorKey,+ ...callerAuditFields(params.caller),targetKey: subjectKey(subject),op: `share.create[${params.permissions.join(',')}]`,drive: params.drive,@@ -232,7 +262,9 @@ export async function handleShareDelete(req: Request, res: Response): Promise<voFOR UPDATE`,[id])- if (existing.rows.length === 0) return { kind: 'not_found' as const }+ if (existing.rows.length === 0) {+ return caller.isOperator ? { kind: 'not_found' as const } : { kind: 'hidden' as const }+ }const row = existing.rows[0] as {drive: stringresource_id: string@@ -258,6 +290,7 @@ export async function handleShareDelete(req: Request, res: Response): Promise<voif (!(error instanceof GfsGrantError)) throw errorconst auditId = await auditMutation(db, {actorKey: caller.actorKey,+ ...callerAuditFields(caller),targetKey: subjectKey(subject),op: 'share.delete',drive: row.drive,@@ -283,6 +316,7 @@ export async function handleShareDelete(req: Request, res: Response): Promise<voawait db.query(`DELETE FROM gfs_shares WHERE id = $1::uuid`, [id])const auditId = await auditMutation(db, {actorKey: caller.actorKey,+ ...callerAuditFields(caller),targetKey: subjectKey(subject),op: 'share.delete',drive: row.drive,@@ -309,6 +343,10 @@ export async function handleShareDelete(req: Request, res: Response): Promise<vores.status(404).json({ error: 'share_not_found' })return}+ if (result.kind === 'hidden') {+ res.status(403).json({ error: 'forbidden' })+ return+ }if (result.kind === 'denied') {res.status(result.error.status).json({ error: result.error.code })returndiff --git a/control-api/src/routes/gfs/token.ts b/control-api/src/routes/gfs/token.tsindex f97f991ca..65f5a9559 100644--- a/control-api/src/routes/gfs/token.ts+++ b/control-api/src/routes/gfs/token.ts@@ -61,6 +61,7 @@ export function registerGfsTokenRoute(router: Router): void {drive,scopes,pathBindings: [],+ principalType: 'control-admin',})res.status(200).json({ token, expiresInSeconds })})diff --git a/control-api/src/services/adminAuthService.ts b/control-api/src/services/adminAuthService.tsindex 6e95dfcef..2c2872fe6 100644--- a/control-api/src/services/adminAuthService.ts+++ b/control-api/src/services/adminAuthService.ts@@ -648,11 +648,17 @@ export async function listControlAdmins(): Promise<{a.username,a.email,u.id AS member_id,+ gfs_link.user_id AS gfs_operator_user_id,+ gfs_link.control_admin_id AS gfs_operator_admin_id,+ gfs_link.source AS gfs_operator_source,+ gfs_link.created_at AS gfs_operator_link_created_at,a.status,a.last_login_at,a.created_atFROM control_admin_users aLEFT JOIN users u ON lower(u.email) = lower(a.email)+ LEFT JOIN gfs_desktop_operator_links gfs_link+ ON gfs_link.control_admin_id = a.idORDER BY a.created_at ASC`),pool.query(@@ -678,6 +684,10 @@ export async function listControlAdmins(): Promise<{username: stringemail: string | nullmember_id: string | null+ gfs_operator_user_id: string | null+ gfs_operator_admin_id: string | null+ gfs_operator_source: 'initial_setup' | null+ gfs_operator_link_created_at: Date | nullstatus: 'active' | 'disabled'last_login_at: Date | nullcreated_at: Date@@ -687,6 +697,31 @@ export async function listControlAdmins(): Promise<{username: record.username,email: record.email || null,memberId: record.member_id || null,+ gfsOperatorLink: record.gfs_operator_user_id+ ? {+ desktopUserId: record.gfs_operator_user_id,+ controlAdminId: record.gfs_operator_admin_id || 'unknown',+ source:+ record.gfs_operator_source === 'initial_setup' ? 'initial_setup' : 'unknown',+ createdAt: record.gfs_operator_link_created_at+ ? record.gfs_operator_link_created_at.toISOString()+ : null,+ status:+ record.gfs_operator_source === 'initial_setup' &&+ record.gfs_operator_link_created_at+ ? record.status === 'active'+ ? 'active'+ : 'inactive_admin'+ : 'error',+ }+ : null,+ gfsOperatorLinkStatus: record.gfs_operator_user_id+ ? record.gfs_operator_source === 'initial_setup' && record.gfs_operator_link_created_at+ ? record.status === 'active'+ ? 'active'+ : 'inactive_admin'+ : 'error'+ : 'revoked',status: record.status,lastLoginAt: record.last_login_at ? record.last_login_at.toISOString() : null,createdAt: record.created_at.toISOString(),diff --git a/control-api/src/services/directory/adminProvisioning.ts b/control-api/src/services/directory/adminProvisioning.tsindex b8924c424..11ac4be8b 100644--- a/control-api/src/services/directory/adminProvisioning.ts+++ b/control-api/src/services/directory/adminProvisioning.ts@@ -1,5 +1,6 @@import { type DbClient, pool, withTransaction } from '../../db.js'import { rootLogger } from '../../observability/logger.js'+import { gfsDesktopOperatorLinkService } from '../gfsDesktopOperatorLinkService.js'import {type ControlApiPermissionChange,appendControlApiPermissionEventsInTransaction,@@ -83,23 +84,28 @@ export async function ensureDefaultTeamAndGrants(* Provision a desktop identity for an admin email, idempotently, in one* transaction: ensure the users row, optionally set its password to the* supplied bcrypt hash (`seedPassword`, default true — one credential across- * Control UI + desktop), then ensure a default team and grants. Safe to re-run.+ * Control UI + desktop), then ensure a default team and grants. When the narrow+ * self-hosted link switch is enabled, the exact Control Admin/Desktop pair is+ * linked in this same transaction. Safe to re-run; returns the exact user id.*/export async function provisionAdminDesktopWorkspace(input: {+ controlAdminId: stringemail: stringdisplayName: stringpasswordHash: stringagentNames: string[]contextIds: string[]+ /** Narrow self-hosted setup switch; false keeps the existing Desktop user path unchanged. */+ linkDesktopOperator: boolean/** When false, skip writing users.password_hash — the desktop password then* comes only from the invitation flow (managed installs). Defaults to* true: the Control-UI human first-run keeps one credential for both apps. */seedPassword?: boolean-}): Promise<void> {+}): Promise<{ userId: string }> {const email = input.email.trim().toLowerCase()const name = input.displayName.trim() || nullconst teamLabel = input.displayName.trim() || email- await withTransaction(async db => {+ return withTransaction(async db => {const existing = await db.query(`SELECT id FROM users WHERE email = $1 LIMIT 1`, [email])let userId = (existing.rows[0] as { id: string } | undefined)?.idif (!userId) {@@ -125,6 +131,17 @@ export async function provisionAdminDesktopWorkspace(input: {}await ensureDefaultTeamAndGrants(db, userId, teamLabel, input.agentNames, input.contextIds)++ if (input.linkDesktopOperator) {+ await gfsDesktopOperatorLinkService.linkInTransaction(db, {+ desktopUserId: userId,+ controlAdminId: input.controlAdminId,+ operatorSub: input.controlAdminId,+ source: 'initial_setup',+ })+ }++ return { userId }})}diff --git a/control-api/src/services/gfsDesktopOperatorLinkService.ts b/control-api/src/services/gfsDesktopOperatorLinkService.tsnew file mode 100644index 000000000..5ce51593f--- /dev/null+++ b/control-api/src/services/gfsDesktopOperatorLinkService.ts@@ -0,0 +1,497 @@+import { type DbClient, pool } from '../db.js'+import {+ type ControlApiPermissionChange,+ appendControlApiPermissionEventsInTransaction,+} from './tracing/controlApiPermissionEvents.js'++export const GFS_DESKTOP_OPERATOR_LINK_SOURCES = ['initial_setup'] as const++export type GfsDesktopOperatorLinkSource = (typeof GFS_DESKTOP_OPERATOR_LINK_SOURCES)[number]++export type GfsDesktopOperatorLink = {+ desktopUserId: string+ controlAdminId: string+ source: GfsDesktopOperatorLinkSource+ createdAt: Date+}++export type GfsDesktopOperatorLinkErrorCode =+ | 'invalid_input'+ | 'desktop_user_not_found'+ | 'control_admin_not_found'+ | 'control_admin_inactive'+ | 'link_conflict'+ | 'malformed_link'+ | 'resolution_failed'++export type GfsDesktopOperatorLinkConflictIdentity = 'desktop_user' | 'control_admin' | 'both'++export class GfsDesktopOperatorLinkError extends Error {+ readonly code: GfsDesktopOperatorLinkErrorCode+ readonly conflictIdentity: GfsDesktopOperatorLinkConflictIdentity | null++ constructor(+ code: GfsDesktopOperatorLinkErrorCode,+ message: string,+ options?: {+ cause?: unknown+ conflictIdentity?: GfsDesktopOperatorLinkConflictIdentity+ }+ ) {+ super(message, options?.cause === undefined ? undefined : { cause: options.cause })+ this.name = 'GfsDesktopOperatorLinkError'+ this.code = code+ this.conflictIdentity = options?.conflictIdentity ?? null+ }+}++export type LinkGfsDesktopOperatorInput = {+ desktopUserId: string+ controlAdminId: string+ source: GfsDesktopOperatorLinkSource+ /** Authenticated Control Admin responsible for this lifecycle mutation. */+ operatorSub: string+}++export type UnlinkGfsDesktopOperatorInput = {+ desktopUserId: string+ controlAdminId: string+ /** Authenticated Control Admin responsible for this lifecycle mutation. */+ operatorSub: string+}++export type LinkGfsDesktopOperatorResult = {+ created: boolean+ link: GfsDesktopOperatorLink+}++export type UnlinkGfsDesktopOperatorResult =+ | { unlinked: false; link: null }+ | { unlinked: true; link: GfsDesktopOperatorLink }++type TransactionRunner = <T>(work: (db: DbClient) => Promise<T>) => Promise<T>++/**+ * Keep the singleton import-safe for callers that mock only the read-side DB+ * pool. The production transaction primitive remains `db.withTransaction`;+ * resolving it only when a link mutation is actually requested avoids making+ * unrelated route modules provide a transaction mock merely by importing the+ * directory barrel.+ */+const defaultTransaction: TransactionRunner = async work => {+ const { withTransaction } = await import('../db.js')+ return withTransaction(work)+}++type GfsDesktopOperatorLinkServiceDependencies = {+ transaction: TransactionRunner+ readDb: Pick<DbClient, 'query'>+ appendPermissionEvents: typeof appendControlApiPermissionEventsInTransaction+}++type StoredLinkRow = {+ user_id: unknown+ control_admin_id: unknown+ source: unknown+ created_at: unknown+}++type ResolvedLinkRow = StoredLinkRow & {+ desktop_user_exists?: unknown+ control_admin_exists?: unknown+ control_admin_status?: unknown+}++const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i++function requireUuid(value: string, field: string): string {+ const normalized = String(value || '')+ .trim()+ .toLowerCase()+ if (!UUID_PATTERN.test(normalized)) {+ throw new GfsDesktopOperatorLinkError('invalid_input', `${field} must be a UUID`)+ }+ return normalized+}++function isLinkSource(value: unknown): value is GfsDesktopOperatorLinkSource {+ return (+ typeof value === 'string' &&+ (GFS_DESKTOP_OPERATOR_LINK_SOURCES as readonly string[]).includes(value)+ )+}++function requireSource(value: unknown): GfsDesktopOperatorLinkSource {+ if (!isLinkSource(value)) {+ throw new GfsDesktopOperatorLinkError(+ 'invalid_input',+ 'source is not a supported GFS Desktop operator-link source'+ )+ }+ return value+}++function mapStoredLink(row: unknown): GfsDesktopOperatorLink {+ if (!row || typeof row !== 'object') {+ throw new GfsDesktopOperatorLinkError('malformed_link', 'operator-link row is malformed')+ }+ const stored = row as StoredLinkRow+ const desktopUserId =+ typeof stored.user_id === 'string' && UUID_PATTERN.test(stored.user_id)+ ? stored.user_id.toLowerCase()+ : null+ const controlAdminId =+ typeof stored.control_admin_id === 'string' && UUID_PATTERN.test(stored.control_admin_id)+ ? stored.control_admin_id.toLowerCase()+ : null+ const createdAt = stored.created_at instanceof Date ? stored.created_at : null+ if (+ !desktopUserId ||+ !controlAdminId ||+ !isLinkSource(stored.source) ||+ !createdAt ||+ !Number.isFinite(createdAt.getTime())+ ) {+ throw new GfsDesktopOperatorLinkError('malformed_link', 'operator-link row is malformed')+ }+ return {+ desktopUserId,+ controlAdminId,+ source: stored.source,+ createdAt,+ }+}++function lifecycleChange(+ action: 'grant' | 'revoke',+ link: GfsDesktopOperatorLink+): ControlApiPermissionChange {+ return {+ action,+ resourceClass: 'gfs_desktop_operator_link',+ resourceRef: `gfs_desktop_operator_link:${link.desktopUserId}:${link.controlAdminId}`,+ subject: { kind: 'user', id: link.desktopUserId },+ sourceAuditRef: `gfs_desktop_operator_link_source:${link.source}`,+ status: action === 'grant' ? 'linked' : 'unlinked',+ detailRef: `desktop_user_id:${link.desktopUserId};control_admin_id:${link.controlAdminId};source:${link.source}`,+ }+}++function mapActiveResolvedLink(+ row: ResolvedLinkRow,+ expected: { desktopUserId?: string; controlAdminId?: string }+): GfsDesktopOperatorLink {+ const link = mapStoredLink(row)+ if (+ (expected.desktopUserId && link.desktopUserId !== expected.desktopUserId) ||+ (expected.controlAdminId && link.controlAdminId !== expected.controlAdminId)+ ) {+ throw new GfsDesktopOperatorLinkError(+ 'malformed_link',+ 'operator-link lookup returned a different identity'+ )+ }+ if (row.desktop_user_exists !== true) {+ throw new GfsDesktopOperatorLinkError(+ 'malformed_link',+ 'operator link references a missing Desktop user'+ )+ }+ if (row.control_admin_exists !== true) {+ throw new GfsDesktopOperatorLinkError(+ 'control_admin_not_found',+ 'operator link references a missing Control Admin'+ )+ }+ if (row.control_admin_status !== 'active') {+ throw new GfsDesktopOperatorLinkError(+ 'control_admin_inactive',+ 'linked Control Admin is not active'+ )+ }+ return link+}++/**+ * Owns the persisted one-to-one GFS Desktop operator-link lifecycle.+ *+ * Link mutations are serialized by locking both exact identity rows before the+ * relationship is rechecked. Lifecycle events share the caller's transaction,+ * so a missing event can never leave behind a committed current-state link.+ */+export class GfsDesktopOperatorLinkService {+ private readonly dependencies: GfsDesktopOperatorLinkServiceDependencies++ constructor(dependencies: Partial<GfsDesktopOperatorLinkServiceDependencies> = {}) {+ this.dependencies = {+ transaction: dependencies.transaction ?? defaultTransaction,+ readDb: dependencies.readDb ?? pool,+ appendPermissionEvents:+ dependencies.appendPermissionEvents ?? appendControlApiPermissionEventsInTransaction,+ }+ }++ async link(input: LinkGfsDesktopOperatorInput): Promise<LinkGfsDesktopOperatorResult> {+ return this.dependencies.transaction(db => this.linkInTransaction(db, input))+ }++ /** Caller-owned transaction seam used by initial Desktop provisioning. */+ async linkInTransaction(+ db: DbClient,+ input: LinkGfsDesktopOperatorInput+ ): Promise<LinkGfsDesktopOperatorResult> {+ const desktopUserId = requireUuid(input.desktopUserId, 'desktopUserId')+ const controlAdminId = requireUuid(input.controlAdminId, 'controlAdminId')+ const operatorSub = requireUuid(input.operatorSub, 'operatorSub')+ const source = requireSource(input.source)++ const user = await db.query(+ `SELECT id::text AS id+ FROM users+ WHERE id = $1::uuid+ FOR UPDATE`,+ [desktopUserId]+ )+ if (user.rows.length !== 1) {+ throw new GfsDesktopOperatorLinkError('desktop_user_not_found', 'Desktop user does not exist')+ }++ const admin = await db.query(+ `SELECT id::text AS id, status+ FROM control_admin_users+ WHERE id = $1::uuid+ FOR UPDATE`,+ [controlAdminId]+ )+ if (admin.rows.length !== 1) {+ throw new GfsDesktopOperatorLinkError(+ 'control_admin_not_found',+ 'Control Admin does not exist'+ )+ }+ const adminStatus = (admin.rows[0] as { status?: unknown }).status+ if (adminStatus !== 'active') {+ throw new GfsDesktopOperatorLinkError('control_admin_inactive', 'Control Admin is not active')+ }++ const current = await db.query(+ `SELECT user_id::text AS user_id,+ control_admin_id::text AS control_admin_id,+ source,+ created_at+ FROM gfs_desktop_operator_links+ WHERE user_id = $1::uuid+ OR control_admin_id = $2::uuid+ ORDER BY user_id::text, control_admin_id::text+ FOR UPDATE`,+ [desktopUserId, controlAdminId]+ )+ const links = current.rows.map(mapStoredLink)+ const exact = links.find(+ link => link.desktopUserId === desktopUserId && link.controlAdminId === controlAdminId+ )+ if (exact && links.length === 1) return { created: false, link: exact }+ if (exact || links.length > 2) {+ throw new GfsDesktopOperatorLinkError(+ 'malformed_link',+ 'operator-link uniqueness invariant is violated'+ )+ }++ const desktopUserConflict = links.some(link => link.desktopUserId === desktopUserId)+ const controlAdminConflict = links.some(link => link.controlAdminId === controlAdminId)+ if (desktopUserConflict || controlAdminConflict) {+ const conflictIdentity: GfsDesktopOperatorLinkConflictIdentity =+ desktopUserConflict && controlAdminConflict+ ? 'both'+ : desktopUserConflict+ ? 'desktop_user'+ : 'control_admin'+ throw new GfsDesktopOperatorLinkError(+ 'link_conflict',+ 'GFS Desktop operator link conflicts with an existing identity assignment',+ { conflictIdentity }+ )+ }++ const inserted = await db.query(+ `INSERT INTO gfs_desktop_operator_links(user_id, control_admin_id, source)+ VALUES($1::uuid, $2::uuid, $3)+ RETURNING user_id::text AS user_id,+ control_admin_id::text AS control_admin_id,+ source,+ created_at`,+ [desktopUserId, controlAdminId, source]+ )+ if (inserted.rows.length !== 1) {+ throw new GfsDesktopOperatorLinkError(+ 'malformed_link',+ 'operator-link insert did not return exactly one row'+ )+ }+ const link = mapStoredLink(inserted.rows[0])+ await this.dependencies.appendPermissionEvents(db, {+ operatorSub,+ operatorKind: 'control_admin',+ changes: [lifecycleChange('grant', link)],+ })+ return { created: true, link }+ }++ async unlink(input: UnlinkGfsDesktopOperatorInput): Promise<UnlinkGfsDesktopOperatorResult> {+ const desktopUserId = requireUuid(input.desktopUserId, 'desktopUserId')+ const controlAdminId = requireUuid(input.controlAdminId, 'controlAdminId')+ const operatorSub = requireUuid(input.operatorSub, 'operatorSub')++ return this.dependencies.transaction(async db => {+ const current = await db.query(+ `SELECT user_id::text AS user_id,+ control_admin_id::text AS control_admin_id,+ source,+ created_at+ FROM gfs_desktop_operator_links+ WHERE user_id = $1::uuid+ OR control_admin_id = $2::uuid+ ORDER BY user_id::text, control_admin_id::text+ FOR UPDATE`,+ [desktopUserId, controlAdminId]+ )+ if (current.rows.length === 0) return { unlinked: false as const, link: null }++ const links = current.rows.map(mapStoredLink)+ const exact = links.find(+ link => link.desktopUserId === desktopUserId && link.controlAdminId === controlAdminId+ )+ if (!exact || links.length !== 1) {+ throw new GfsDesktopOperatorLinkError(+ 'link_conflict',+ 'requested GFS Desktop operator pair does not match current linkage',+ {+ conflictIdentity:+ links.some(link => link.desktopUserId === desktopUserId) &&+ links.some(link => link.controlAdminId === controlAdminId)+ ? 'both'+ : links.some(link => link.desktopUserId === desktopUserId)+ ? 'desktop_user'+ : 'control_admin',+ }+ )+ }++ // Evidence is appended before current state is removed. Both operations+ // still commit atomically because they share this transaction.+ await this.dependencies.appendPermissionEvents(db, {+ operatorSub,+ operatorKind: 'control_admin',+ changes: [lifecycleChange('revoke', exact)],+ })+ const removed = await db.query(+ `DELETE FROM gfs_desktop_operator_links+ WHERE user_id = $1::uuid+ AND control_admin_id = $2::uuid`,+ [desktopUserId, controlAdminId]+ )+ if (removed.rowCount !== 1) {+ throw new GfsDesktopOperatorLinkError(+ 'malformed_link',+ 'operator-link disappeared during unlink'+ )+ }+ return { unlinked: true as const, link: exact }+ })+ }++ async resolveActiveLink(desktopUserIdInput: string): Promise<GfsDesktopOperatorLink | null> {+ const desktopUserId = requireUuid(desktopUserIdInput, 'desktopUserId')+ try {+ const result = await this.dependencies.readDb.query(+ `SELECT links.user_id::text AS user_id,+ links.control_admin_id::text AS control_admin_id,+ links.source,+ links.created_at,+ users.id IS NOT NULL AS desktop_user_exists,+ admins.id IS NOT NULL AS control_admin_exists,+ admins.status AS control_admin_status+ FROM gfs_desktop_operator_links links+ LEFT JOIN users ON users.id = links.user_id+ LEFT JOIN control_admin_users admins ON admins.id = links.control_admin_id+ WHERE links.user_id = $1::uuid`,+ [desktopUserId]+ )+ if (result.rows.length === 0) return null+ if (result.rows.length !== 1) {+ throw new GfsDesktopOperatorLinkError(+ 'malformed_link',+ 'operator-link uniqueness invariant is violated'+ )+ }++ return mapActiveResolvedLink(result.rows[0] as ResolvedLinkRow, { desktopUserId })+ } catch (error) {+ if (error instanceof GfsDesktopOperatorLinkError) throw error+ throw new GfsDesktopOperatorLinkError(+ 'resolution_failed',+ 'failed to resolve GFS Desktop operator link',+ { cause: error }+ )+ }+ }++ /** Read-only exact-pair seam for the authenticated Control UI revoke surface. */+ async getLinkForControlAdmin(+ controlAdminIdInput: string+ ): Promise<GfsDesktopOperatorLink | null> {+ const controlAdminId = requireUuid(controlAdminIdInput, 'controlAdminId')+ try {+ const result = await this.dependencies.readDb.query(+ `SELECT links.user_id::text AS user_id,+ links.control_admin_id::text AS control_admin_id,+ links.source,+ links.created_at,+ users.id IS NOT NULL AS desktop_user_exists,+ admins.id IS NOT NULL AS control_admin_exists,+ admins.status AS control_admin_status+ FROM gfs_desktop_operator_links links+ LEFT JOIN users ON users.id = links.user_id+ LEFT JOIN control_admin_users admins ON admins.id = links.control_admin_id+ WHERE links.control_admin_id = $1::uuid`,+ [controlAdminId]+ )+ if (result.rows.length === 0) return null+ if (result.rows.length !== 1) {+ throw new GfsDesktopOperatorLinkError(+ 'malformed_link',+ 'operator-link uniqueness invariant is violated'+ )+ }+ const row = result.rows[0] as ResolvedLinkRow+ const link = mapStoredLink(row)+ if (link.controlAdminId !== controlAdminId || row.desktop_user_exists !== true) {+ throw new GfsDesktopOperatorLinkError(+ 'malformed_link',+ 'operator-link lookup returned a malformed identity pair'+ )+ }+ if (row.control_admin_exists !== true) {+ throw new GfsDesktopOperatorLinkError(+ 'control_admin_not_found',+ 'operator link references a missing Control Admin'+ )+ }+ // Status reads deliberately preserve a structurally valid link for a+ // disabled admin so the authenticated revoke path can remove stale+ // current state. Request-time authority still uses resolveActiveLink(),+ // which rejects every non-active admin.+ return link+ } catch (error) {+ if (error instanceof GfsDesktopOperatorLinkError) throw error+ throw new GfsDesktopOperatorLinkError(+ 'resolution_failed',+ 'failed to read GFS Desktop operator link for Control Admin',+ { cause: error }+ )+ }+ }+}++export const gfsDesktopOperatorLinkService = new GfsDesktopOperatorLinkService()diff --git a/control-api/test/auth.gfsToken.test.ts b/control-api/test/auth.gfsToken.test.tsindex e649faf45..bb8dd6aac 100644--- a/control-api/test/auth.gfsToken.test.ts+++ b/control-api/test/auth.gfsToken.test.ts@@ -50,6 +50,30 @@ describe('signGfsToken', () => {])})+ it('signs linked-admin provenance without conflating Desktop actor and token subject', () => {+ const desktopUserId = '11111111-1111-4111-8111-111111111111'+ const controlAdminId = '22222222-2222-4222-8222-222222222222'+ const { token } = signGfsToken({+ subject: controlAdminId,+ drive: 'main',+ scopes: ['gfs.write'],+ principalType: 'control-admin',+ brokeredAuthority: {+ desktopUserId,+ controlAdminId,+ authoritySource: 'linked-admin',+ },+ })+ const decoded = jwt.verify(token, config.rpcJwtPublicKey, VERIFY) as jwt.JwtPayload+ expect(decoded.sub).toBe(controlAdminId)+ expect(decoded.principalType).toBe('control-admin')+ expect(decoded.brokeredAuthority).toEqual({+ desktopUserId,+ controlAdminId,+ authoritySource: 'linked-admin',+ })+ })+it('FAILS verification under the wrong audience (fail-loud)', () => {const { token } = signGfsToken({ subject: 'u', drive: 'main', scopes: ['gfs.read'] })expect(() =>diff --git a/control-api/test/config.desktopGfsOperatorLinking.test.ts b/control-api/test/config.desktopGfsOperatorLinking.test.tsnew file mode 100644index 000000000..5fb857067--- /dev/null+++ b/control-api/test/config.desktopGfsOperatorLinking.test.ts@@ -0,0 +1,38 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++const KEY = 'CONTROL_API_DESKTOP_GFS_OPERATOR_LINKING_ENABLED'+const original = process.env[KEY]++beforeEach(() => {+ delete process.env[KEY]+ vi.resetModules()+})++afterEach(() => {+ if (original === undefined) delete process.env[KEY]+ else process.env[KEY] = original+ vi.resetModules()+})++describe(KEY, () => {+ it('defaults to disabled when absent', async () => {+ const { config } = await import('../src/config.js')+ expect(config.desktopGfsOperatorLinkingEnabled).toBe(false)+ })++ it.each([+ ['true', true],+ ['false', false],+ ])('parses the exact %s value', async (value, expected) => {+ process.env[KEY] = value+ const { config } = await import('../src/config.js')+ expect(config.desktopGfsOperatorLinkingEnabled).toBe(expected)+ })++ it('fails closed on malformed values', async () => {+ process.env[KEY] = 'yes'+ await expect(import('../src/config.js')).rejects.toThrow(+ /CONTROL_API_DESKTOP_GFS_OPERATOR_LINKING_ENABLED must be 'true' or 'false'/+ )+ })+})diff --git a/control-api/test/db.gfsAuditActorCorrelationMigration.test.ts b/control-api/test/db.gfsAuditActorCorrelationMigration.test.tsnew file mode 100644index 000000000..dddcfb8f4--- /dev/null+++ b/control-api/test/db.gfsAuditActorCorrelationMigration.test.ts@@ -0,0 +1,32 @@+import { describe, expect, it, vi } from 'vitest'++vi.mock('pg', () => ({+ Pool: vi.fn(function MockPool() {+ return { connect: vi.fn(), query: vi.fn() }+ }),+}))++describe('0092_gfs_audit_actor_correlation migration', () => {+ it('adds separate Desktop actor/source fields without weakening legacy audit rows', async () => {+ const { CONTROL_API_MIGRATIONS } = await import('../src/db.js')+ const migration = CONTROL_API_MIGRATIONS.find(+ candidate => candidate.version === '0092_gfs_audit_actor_correlation'+ )+ expect(migration).toBeDefined()+ expect(CONTROL_API_MIGRATIONS.at(-2)?.version).toBe('0091_gfs_desktop_operator_links')+ expect(CONTROL_API_MIGRATIONS.at(-1)?.version).toBe(migration?.version)++ const query = vi.fn().mockResolvedValue({ rows: [], rowCount: 0 })+ await migration!.apply({ query })+ const sql = String(query.mock.calls[0]?.[0])++ expect(sql).toContain('ADD COLUMN IF NOT EXISTS desktop_user_id UUID NULL')+ expect(sql).toContain('ADD COLUMN IF NOT EXISTS authority_source TEXT NULL')+ expect(sql).toContain('gfs_audit_actor_correlation_valid')+ expect(sql).toContain("authority_source = 'user-session'")+ expect(sql).toContain("authority_source = 'linked-admin'")+ expect(sql).toContain('actor_on_behalf_of IS NULL')+ expect(sql).toContain('actor_on_behalf_of IS NOT NULL')+ expect(sql).not.toContain("authorization_source = 'linked-admin'")+ })+})diff --git a/control-api/test/db.gfsDesktopOperatorLinksMigration.test.ts b/control-api/test/db.gfsDesktopOperatorLinksMigration.test.tsnew file mode 100644index 000000000..0234cf056--- /dev/null+++ b/control-api/test/db.gfsDesktopOperatorLinksMigration.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it, vi } from 'vitest'++vi.mock('pg', () => ({+ Pool: vi.fn(function MockPool() {+ return { connect: vi.fn(), query: vi.fn() }+ }),+}))++describe('0091_gfs_desktop_operator_links migration', () => {+ it('installs an additive one-to-one link with the closed initial-setup source contract', async () => {+ const { CONTROL_API_MIGRATIONS } = await import('../src/db.js')+ const migration = CONTROL_API_MIGRATIONS.find(+ candidate => candidate.version === '0091_gfs_desktop_operator_links'+ )+ expect(migration).toBeDefined()+ const migrationIndex = CONTROL_API_MIGRATIONS.findIndex(+ candidate => candidate.version === migration?.version+ )+ expect(CONTROL_API_MIGRATIONS[migrationIndex - 1]?.version).toBe(+ '0090_plugin_workload_sdk_runtime_contract_reconciliation'+ )+ expect(CONTROL_API_MIGRATIONS[migrationIndex + 1]?.version).toBe(+ '0092_gfs_audit_actor_correlation'+ )++ const query = vi.fn().mockResolvedValue({ rows: [], rowCount: 0 })+ await migration!.apply({ query })+ const sql = String(query.mock.calls[0]?.[0])++ expect(sql).toContain('CREATE TABLE IF NOT EXISTS gfs_desktop_operator_links')+ expect(sql).toContain('user_id UUID PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE')+ expect(sql).toContain(+ 'control_admin_id UUID NOT NULL UNIQUE REFERENCES control_admin_users(id) ON DELETE CASCADE'+ )+ expect(sql).toContain("source TEXT NOT NULL CHECK (source IN ('initial_setup'))")+ expect(sql).toContain('created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()')+ expect(sql).toContain(+ 'GRANT SELECT, INSERT, DELETE ON TABLE gfs_desktop_operator_links TO control_api_runtime'+ )+ expect(sql).not.toMatch(/INSERT\s+INTO\s+gfs_desktop_operator_links/i)+ expect(sql).not.toMatch(/JOIN\s+.*email|lower\s*\(.*email/i)+ expect(sql).not.toContain('control_admin_invitation')+ expect(sql).not.toContain('admin_member_bridge')+ expect(sql).not.toContain('manual_repair')+ })+})diff --git a/control-api/test/db.pluginWorkloadSdkTraceValidatorMigration.test.ts b/control-api/test/db.pluginWorkloadSdkTraceValidatorMigration.test.tsindex a8119eba7..4de6cce99 100644--- a/control-api/test/db.pluginWorkloadSdkTraceValidatorMigration.test.ts+++ b/control-api/test/db.pluginWorkloadSdkTraceValidatorMigration.test.ts@@ -23,7 +23,11 @@ describe('Plugin Workload SDK runtime-contract reconciliation migration', () =>candidate => candidate.version === '0090_plugin_workload_sdk_runtime_contract_reconciliation')expect(migration).toBeDefined()- expect(CONTROL_API_MIGRATIONS.at(-2)?.version).toBe(+ const migrationIndex = CONTROL_API_MIGRATIONS.findIndex(+ candidate => candidate.version === migration?.version+ )+ const previousMigration = CONTROL_API_MIGRATIONS[migrationIndex - 1]+ expect(previousMigration?.version).toBe('0089_plugin_workload_sdk_credential_ticket_runtime_access')diff --git a/control-api/test/gfs.externalAuthority.test.ts b/control-api/test/gfs.externalAuthority.test.tsnew file mode 100644index 000000000..0565e46bc--- /dev/null+++ b/control-api/test/gfs.externalAuthority.test.ts@@ -0,0 +1,123 @@+import { describe, expect, it, vi } from 'vitest'+import {+ ExternalGfsAuthorityError,+ resolveExternalGfsAuthority,+} from '../src/gfs/externalAuthority.js'+import { GfsDesktopOperatorLinkError } from '../src/services/gfsDesktopOperatorLinkService.js'++vi.mock('../src/config.js', () => ({+ config: { desktopGfsOperatorLinkingEnabled: false },+}))+vi.mock('../src/services/gfsDesktopOperatorLinkService.js', () => {+ class GfsDesktopOperatorLinkError extends Error {+ constructor(+ readonly code: string,+ message: string+ ) {+ super(message)+ this.name = 'GfsDesktopOperatorLinkError'+ }+ }+ return {+ GfsDesktopOperatorLinkError,+ gfsDesktopOperatorLinkService: { resolveActiveLink: vi.fn() },+ }+})++const DESKTOP_USER_ID = '11111111-1111-4111-8111-111111111111'+const CONTROL_ADMIN_ID = '22222222-2222-4222-8222-222222222222'+const LINK = {+ desktopUserId: DESKTOP_USER_ID,+ controlAdminId: CONTROL_ADMIN_ID,+ source: 'initial_setup' as const,+ createdAt: new Date('2026-08-10T00:00:00.000Z'),+}++describe('resolveExternalGfsAuthority', () => {+ it('does not query links when the fail-closed feature flag is off', async () => {+ const resolveActiveLink = vi.fn()+ await expect(+ resolveExternalGfsAuthority(DESKTOP_USER_ID, {+ linkingEnabled: false,+ resolveActiveLink,+ })+ ).resolves.toEqual({+ kind: 'user-session',+ desktopUserId: DESKTOP_USER_ID,+ tokenSubject: DESKTOP_USER_ID,+ })+ expect(resolveActiveLink).not.toHaveBeenCalled()+ })++ it('keeps an unlinked Desktop session on ordinary user authority', async () => {+ await expect(+ resolveExternalGfsAuthority(DESKTOP_USER_ID, {+ linkingEnabled: true,+ resolveActiveLink: vi.fn().mockResolvedValue(null),+ })+ ).resolves.toEqual({+ kind: 'user-session',+ desktopUserId: DESKTOP_USER_ID,+ tokenSubject: DESKTOP_USER_ID,+ })+ })++ it('resolves an active initial-setup link to a distinct effective admin subject', async () => {+ await expect(+ resolveExternalGfsAuthority(DESKTOP_USER_ID, {+ linkingEnabled: true,+ resolveActiveLink: vi.fn().mockResolvedValue(LINK),+ })+ ).resolves.toEqual({+ kind: 'linked-admin',+ desktopUserId: DESKTOP_USER_ID,+ controlAdminId: CONTROL_ADMIN_ID,+ tokenSubject: CONTROL_ADMIN_ID,+ authoritySource: 'linked-admin',+ })+ })++ it.each([+ 'control_admin_inactive',+ 'control_admin_not_found',+ 'link_conflict',+ 'malformed_link',+ 'invalid_input',+ ] as const)('fails closed with one non-oracular denial for %s', async code => {+ const error = new GfsDesktopOperatorLinkError(code, 'sensitive link detail')+ await expect(+ resolveExternalGfsAuthority(DESKTOP_USER_ID, {+ linkingEnabled: true,+ resolveActiveLink: vi.fn().mockRejectedValue(error),+ })+ ).rejects.toMatchObject<Partial<ExternalGfsAuthorityError>>({+ status: 403,+ code: 'gfs_operator_link_invalid',+ })+ })++ it('fails unavailable rather than falling back when link resolution fails', async () => {+ const error = new GfsDesktopOperatorLinkError('resolution_failed', 'database unavailable')+ await expect(+ resolveExternalGfsAuthority(DESKTOP_USER_ID, {+ linkingEnabled: true,+ resolveActiveLink: vi.fn().mockRejectedValue(error),+ })+ ).rejects.toMatchObject<Partial<ExternalGfsAuthorityError>>({+ status: 503,+ code: 'gfs_authority_unavailable',+ })+ })++ it('rejects a mismatched or non-initial-setup row even if a dependency returns it', async () => {+ await expect(+ resolveExternalGfsAuthority(DESKTOP_USER_ID, {+ linkingEnabled: true,+ resolveActiveLink: vi.fn().mockResolvedValue({+ ...LINK,+ desktopUserId: '33333333-3333-4333-8333-333333333333',+ }),+ })+ ).rejects.toMatchObject({ status: 403, code: 'gfs_operator_link_invalid' })+ })+})diff --git a/control-api/test/routes.adminAuth.test.ts b/control-api/test/routes.adminAuth.test.tsindex fba4bdcf8..489ca6024 100644--- a/control-api/test/routes.adminAuth.test.ts+++ b/control-api/test/routes.adminAuth.test.ts@@ -70,6 +70,7 @@ describe('routes/adminAuth', () => {Object.values(rateLimit).forEach(fn => fn.mockClear())adminSvc.isValidAdminEmail.mockReturnValue(true)adminSvc.isValidAdminUsername.mockReturnValue(true)+ config.desktopGfsOperatorLinkingEnabled = falseadminToken.signAdminToken.mockReturnValue('admin-jwt')uiAuth.requireAuthForControlUI.mockImplementation((req: any, _res: any, next: any) => {req.adminAuth = { sub: 'admin-id', role: 'admin', jti: 'j1', exp: 9999999999, typ: 'user' }@@ -192,11 +193,43 @@ describe('routes/adminAuth', () => {expect(res.status).toBe(200)expect(directorySvc.provisionAdminDesktopWorkspace).toHaveBeenCalledWith(expect.objectContaining({+ controlAdminId: 'admin-1',email: '[email protected]',displayName: 'newadmin',passwordHash: expect.any(String),agentNames: expect.any(Array),contextIds: expect.any(Array),+ linkDesktopOperator: false,+ })+ )+ })++ it('requests the exact initial-setup link only when the narrow self-hosted flag is enabled', async () => {+ config.desktopGfsOperatorLinkingEnabled = true+ adminSvc.setupInitialAdminCredentials.mockResolvedValue({+ id: 'admin-1',+ username: 'newadmin',+ email: '[email protected]',+ role: 'admin',+ status: 'active',+ failedAttempts: 0,+ lockedUntil: null,+ })+ directorySvc.provisionAdminDesktopWorkspace.mockResolvedValue({ userId: 'user-1' })++ const app = express()+ app.use(express.json())+ app.use(createAdminAuthRouter())++ await request(app)+ .post('/admin/auth/setup')+ .send({ email: '[email protected]', username: 'newadmin', password: 'secret123' })+ .expect(200)++ expect(directorySvc.provisionAdminDesktopWorkspace).toHaveBeenCalledWith(+ expect.objectContaining({+ controlAdminId: 'admin-1',+ linkDesktopOperator: true,}))})@@ -276,6 +309,7 @@ describe('routes/adminAuth', () => {})it('still returns 200 when desktop provisioning throws', async () => {+ config.desktopGfsOperatorLinkingEnabled = trueadminSvc.setupInitialAdminCredentials.mockResolvedValue({id: 'admin-1',username: 'newadmin',@@ -299,6 +333,12 @@ describe('routes/adminAuth', () => {expect(res.body.token).toBeUndefined()expect(String(res.headers['set-cookie'])).toContain('control_ui_admin_session=admin-jwt')expect(res.body.me).toMatchObject({ email: '[email protected]', username: 'newadmin' })+ expect(directorySvc.provisionAdminDesktopWorkspace).toHaveBeenCalledWith(+ expect.objectContaining({+ controlAdminId: 'admin-1',+ linkDesktopOperator: true,+ })+ )})it('returns me and supports logout', async () => {diff --git a/control-api/test/routes.adminControlAdmins.test.ts b/control-api/test/routes.adminControlAdmins.test.tsindex b965518b0..e8225c7d5 100644--- a/control-api/test/routes.adminControlAdmins.test.ts+++ b/control-api/test/routes.adminControlAdmins.test.ts@@ -23,6 +23,11 @@ const controlAdminInvitationRegistrationSvc = vi.hoisted(() => ({registerAndSendControlAdminInvitation: vi.fn(),}))+const operatorLinkSvc = vi.hoisted(() => ({+ getLinkForControlAdmin: vi.fn(),+ unlink: vi.fn(),+}))+const uiAuth = vi.hoisted(() => ({requireAuthForControlUI: vi.fn((req: any, _res: any, next: any) => {req.adminAuth = {@@ -37,6 +42,16 @@ const uiAuth = vi.hoisted(() => ({}))vi.mock('../src/services/adminAuthService.js', () => adminSvc)+vi.mock('../src/services/gfsDesktopOperatorLinkService.js', () => ({+ GfsDesktopOperatorLinkError: class GfsDesktopOperatorLinkError extends Error {+ code: string+ constructor(code: string) {+ super(code)+ this.code = code+ }+ },+ gfsDesktopOperatorLinkService: operatorLinkSvc,+}))vi.mock('../src/services/controlAdminInvitationRegistrationService.js',() => controlAdminInvitationRegistrationSvc@@ -64,6 +79,7 @@ describe('routes/adminControlAdmins', () => {beforeEach(() => {Object.values(adminSvc).forEach(fn => fn.mockReset())Object.values(controlAdminInvitationRegistrationSvc).forEach(fn => fn.mockReset())+ Object.values(operatorLinkSvc).forEach(fn => fn.mockReset())Object.values(uiAuth).forEach(fn => fn.mockClear())})@@ -96,4 +112,61 @@ describe('routes/adminControlAdmins', () => {expect(res.body).toEqual({ error: 'not_found' })})++ it('revokes only the exact server-resolved Desktop GFS operator link', async () => {+ const targetAdminId = 'target-admin-id'+ const desktopUserId = 'desktop-user-id'+ adminSvc.findAdminById.mockResolvedValue({ id: targetAdminId })+ operatorLinkSvc.getLinkForControlAdmin.mockResolvedValue({+ desktopUserId,+ controlAdminId: targetAdminId,+ source: 'initial_setup',+ createdAt: new Date('2026-08-10T12:00:00.000Z'),+ })+ operatorLinkSvc.unlink.mockResolvedValue({+ unlinked: true,+ link: {+ desktopUserId,+ controlAdminId: targetAdminId,+ source: 'initial_setup',+ createdAt: new Date('2026-08-10T12:00:00.000Z'),+ },+ })++ const res = await request(createTestApp())+ .delete(`/admin/control-admins/${targetAdminId}/gfs-operator-link`)+ .send({ desktopUserId: 'client-supplied-id' })+ .expect(200)++ expect(res.body).toEqual({+ revoked: true,+ gfsOperatorLinkStatus: 'revoked',+ controlAdminId: targetAdminId,+ desktopUserId,+ })+ expect(operatorLinkSvc.getLinkForControlAdmin).toHaveBeenCalledWith(targetAdminId)+ expect(operatorLinkSvc.unlink).toHaveBeenCalledWith({+ desktopUserId,+ controlAdminId: targetAdminId,+ operatorSub: 'current-admin-id',+ })+ })++ it('is idempotent when the target admin has no current Desktop GFS link', async () => {+ const targetAdminId = 'target-admin-id'+ adminSvc.findAdminById.mockResolvedValue({ id: targetAdminId })+ operatorLinkSvc.getLinkForControlAdmin.mockResolvedValue(null)++ const res = await request(createTestApp())+ .delete(`/admin/control-admins/${targetAdminId}/gfs-operator-link`)+ .expect(200)++ expect(res.body).toEqual({+ revoked: false,+ gfsOperatorLinkStatus: 'revoked',+ controlAdminId: targetAdminId,+ desktopUserId: null,+ })+ expect(operatorLinkSvc.unlink).not.toHaveBeenCalled()+ })})diff --git a/control-api/test/routes.externalGfs.test.ts b/control-api/test/routes.externalGfs.test.tsindex e861edb3c..0a3b385af 100644--- a/control-api/test/routes.externalGfs.test.ts+++ b/control-api/test/routes.externalGfs.test.ts@@ -18,6 +18,7 @@ const mockSignGfsToken = vi.hoisted(() => vi.fn())const mockQuery = vi.hoisted(() => vi.fn())const mockAppendPermissionEvents = vi.hoisted(() => vi.fn())const mockWithTransaction = vi.hoisted(() => vi.fn())+const mockResolveActiveLink = vi.hoisted(() => vi.fn())vi.mock('../src/utils/auth/externalSessionAuthToken.js', () => ({verifyExternalSessionToken: (...a: unknown[]) => mockVerifyExternalSessionToken(...a),@@ -36,6 +37,20 @@ vi.mock('../src/config.js', () => ({gfscProxyTimeoutMs: 300_000,// The eligibility guard maps caller agent names to 1st:<hostsNamespace>/<name>.hostsNamespace: 'mcp-host',+ desktopGfsOperatorLinkingEnabled: false,+ },+}))+vi.mock('../src/services/gfsDesktopOperatorLinkService.js', () => ({+ gfsDesktopOperatorLinkService: {+ resolveActiveLink: (...a: unknown[]) => mockResolveActiveLink(...a),+ },+ GfsDesktopOperatorLinkError: class GfsDesktopOperatorLinkError extends Error {+ constructor(+ readonly code: string,+ message: string+ ) {+ super(message)+ }},}))vi.mock('../src/db.js', () => ({@@ -71,6 +86,14 @@ const SESSION = {const R = '11111111-1111-1111-1111-111111111111'const R2 = '22222222-2222-2222-2222-222222222222'const R_RID = R.replace(/-/g, '')+const CONTROL_ADMIN_ID = '66666666-eeee-4eee-8eee-666666666666'+const REQUEST_ID = '77777777-eeee-4eee-8eee-777777777777'+const ACTIVE_LINK = {+ desktopUserId: U1,+ controlAdminId: CONTROL_ADMIN_ID,+ source: 'initial_setup' as const,+ createdAt: new Date('2026-08-10T00:00:00.000Z'),+}async function buildApp() {const { createExternalGfsRouter } = await import('../src/routes/external/gfs.js')@@ -122,6 +145,8 @@ beforeEach(() => {mockQuery.mockReset()mockAppendPermissionEvents.mockReset()mockWithTransaction.mockReset()+ mockResolveActiveLink.mockReset()+ mockResolveActiveLink.mockResolvedValue(null)mockWithTransaction.mockImplementation(async (work: (db: { query: typeof mockQuery }) => Promise<unknown>) =>work({ query: mockQuery })@@ -129,6 +154,8 @@ beforeEach(() => {mockAppendPermissionEvents.mockResolvedValue(null)mockSignGfsToken.mockReturnValue({ token: 'gfs-user-token', expiresInSeconds: 300 });(config as { gfscProxyTimeoutMs: number }).gfscProxyTimeoutMs = 300_000+ ;(config as { desktopGfsOperatorLinkingEnabled: boolean }).desktopGfsOperatorLinkingEnabled =+ false})afterEach(() => vi.unstubAllGlobals())@@ -215,6 +242,7 @@ describe('POST /external/gfs/token (user mint — existing signer, sub=users.id)drive: 'main',scopes: ['gfs.read', 'gfs.write'],pathBindings: [],+ principalType: 'user',})})@@ -246,6 +274,202 @@ describe('POST /external/gfs/token (user mint — existing signer, sub=users.id)const res = await request(app).post('/external/gfs/token').send({})expect(res.status).toBe(401)})++ it('stays user-only and never resolves linked authority even when linking is enabled', async () => {+ auth()+ ;(config as { desktopGfsOperatorLinkingEnabled: boolean }).desktopGfsOperatorLinkingEnabled =+ true+ mockResolveActiveLink.mockResolvedValue(ACTIVE_LINK)++ const res = await request(await buildApp())+ .post('/external/gfs/token')+ .set('x-user-session-token', 'sess')+ .send({ scopes: ['gfs.read'] })++ expect(res.status).toBe(200)+ expect(mockResolveActiveLink).not.toHaveBeenCalled()+ expect(mockSignGfsToken).toHaveBeenCalledWith(+ expect.objectContaining({+ subject: U1,+ principalType: 'user',+ })+ )+ expect(mockSignGfsToken.mock.calls[0]?.[0]).not.toHaveProperty('brokeredAuthority')+ })+})++describe('linked Desktop operator authority contract', () => {+ function linked(): void {+ auth()+ ;(config as { desktopGfsOperatorLinkingEnabled: boolean }).desktopGfsOperatorLinkingEnabled =+ true+ mockResolveActiveLink.mockResolvedValue(ACTIVE_LINK)+ }++ it('mints only an internal effective-admin token and forwards the same request id to gfsc', async () => {+ linked()+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ ok: true, data: { resourceId: R } }), {+ status: 201,+ headers: { 'content-type': 'application/json' },+ })+ )+ )++ const res = await request(await buildApp())+ .post(`/external/gfs/resources/${R}/children?drive=main`)+ .set('x-user-session-token', 'sess')+ .set('x-request-id', REQUEST_ID)+ .send({ name: 'operator-folder', kind: 'directory' })++ expect(res.status).toBe(201)+ expect(res.headers['x-request-id']).toBe(REQUEST_ID)+ expect(mockSignGfsToken).toHaveBeenCalledWith({+ subject: CONTROL_ADMIN_ID,+ drive: 'main',+ scopes: ['gfs.write'],+ principalType: 'control-admin',+ brokeredAuthority: {+ desktopUserId: U1,+ controlAdminId: CONTROL_ADMIN_ID,+ authoritySource: 'linked-admin',+ },+ })+ const fetchOptions = (vi.mocked(fetch).mock.calls[0]?.[1] ?? {}) as RequestInit+ expect(new Headers(fetchOptions.headers).get('x-request-id')).toBe(REQUEST_ID)+ })++ it('uses the existing root tree primitive for a full operator root view', async () => {+ linked()+ mockQuery.mockImplementation(async (text: string) => {+ if (text.includes('parent_resource_id IS NULL')) {+ return {+ rows: [{ resource_id: R, drive: 'main', name: '', kind: 'directory', path_cache: '/' }],+ }+ }+ if (text.includes('parent_resource_id = $2::uuid')) {+ return {+ rows: [+ {+ resource_id: R2,+ name: 'all-operator-visible',+ kind: 'directory',+ path_cache: '/all-operator-visible',+ bytes: 0,+ version: 1,+ },+ ],+ }+ }+ return { rows: [] }+ })++ const res = await request(await buildApp())+ .get('/external/gfs/resources?drive=main')+ .set('x-user-session-token', 'sess')++ expect(res.status).toBe(200)+ expect(res.body).toEqual({+ ok: true,+ data: {+ items: [expect.objectContaining({ resourceId: R2, name: 'all-operator-visible' })],+ nextCursor: null,+ rootResourceId: R,+ view: 'operator',+ },+ })+ expect(mockQuery.mock.calls.some(call => String(call[0]).includes('team_members'))).toBe(false)+ })++ it('persists Desktop actor, effective admin, authority source, and request id separately', async () => {+ linked()+ dbReturning([])++ const res = await request(await buildApp())+ .put('/external/gfs/grants')+ .set('x-user-session-token', 'sess')+ .set('x-request-id', REQUEST_ID)+ .send({+ resourceId: R,+ subject: { type: 'user', id: U2 },+ permissions: ['read'],+ inherit: false,+ })++ expect(res.status).toBe(200)+ const audit = mockQuery.mock.calls.find(call =>+ String(call[0]).includes('INSERT INTO gfs_audit')+ )+ expect(audit?.[1]).toEqual([+ `user:${U2}`,+ CONTROL_ADMIN_ID,+ 'grant.put[read]',+ `gfs://main/${R}`,+ 'allowed',+ expect.anything(),+ REQUEST_ID,+ expect.stringMatching(/^[0-9a-f]{64}$/),+ U1,+ 'linked-admin',+ ])+ expect(mockAppendPermissionEvents).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ operatorKind: 'control_admin', operatorSub: CONTROL_ADMIN_ID })+ )+ })++ it.each([+ ['get', '/external/gfs/resources'],+ ['get', '/external/gfs/resolve?uri=gfs%3A%2F%2Fmain%2Ffoo'],+ ['get', `/external/gfs/resources/${R}/children`],+ ['get', `/external/gfs/resources/${R}/affordances`],+ ['get', `/external/gfs/proxy/${R}`],+ ['get', `/external/gfs/grants?drive=main&resourceId=${R}`],+ ['put', '/external/gfs/grants'],+ ['delete', `/external/gfs/grants/${R}`],+ ['get', `/external/gfs/shares?drive=main&resourceId=${R}`],+ ['post', '/external/gfs/shares'],+ ['delete', `/external/gfs/shares/${R}`],+ ['patch', `/external/gfs/resources/${R}`],+ ['post', `/external/gfs/resources/${R}/children`],+ ['put', `/external/gfs/resources/${R}/content`],+ ['delete', `/external/gfs/resources/${R}`],+ ] as const)('fails closed before route-specific work for %s %s', async (method, path) => {+ auth()+ ;(config as { desktopGfsOperatorLinkingEnabled: boolean }).desktopGfsOperatorLinkingEnabled =+ true+ const { GfsDesktopOperatorLinkError } =+ await import('../src/services/gfsDesktopOperatorLinkService.js')+ mockResolveActiveLink.mockRejectedValue(+ new GfsDesktopOperatorLinkError('control_admin_inactive', 'sensitive state')+ )++ const res = await request(await buildApp())+ [method](path)+ .set('x-user-session-token', 'sess')+ .send({})++ expect(res.status).toBe(403)+ expect(res.body).toEqual({ error: 'gfs_operator_link_invalid' })+ expect(mockQuery).not.toHaveBeenCalled()+ expect(mockSignGfsToken).not.toHaveBeenCalled()+ })++ it('does not resolve or elevate when the feature flag is off', async () => {+ auth()+ mockResolveActiveLink.mockResolvedValue(ACTIVE_LINK)+ mockQuery.mockResolvedValue({ rows: [] })++ const res = await request(await buildApp())+ .get('/external/gfs/resources')+ .set('x-user-session-token', 'sess')++ expect(res.status).toBe(200)+ expect(res.body.data).toEqual({ items: [], nextCursor: null })+ expect(mockResolveActiveLink).not.toHaveBeenCalled()+ })})describe('PUT /external/gfs/grants (user delegation via existing engine)', () => {@@ -276,6 +500,10 @@ describe('PUT /external/gfs/grants (user delegation via existing engine)', () =>// The INSERT recorded the caller as the user (granted_by user:user-1).const insert = mockQuery.mock.calls.find(c => String(c[0]).includes('INSERT INTO gfs_grants'))expect(insert?.[1]?.[6]).toBe(`user:${U1}`)+ const audit = mockQuery.mock.calls.find(c => String(c[0]).includes('INSERT INTO gfs_audit'))+ expect(audit?.[1]?.[1]).toBeNull()+ expect(audit?.[1]?.[8]).toBe(U1)+ expect(audit?.[1]?.[9]).toBe('user-session')expect(mockAppendPermissionEvents).toHaveBeenCalledWith(expect.anything(),expect.objectContaining({@@ -525,6 +753,54 @@ describe('POST /external/gfs/shares (user delegation via existing engine)', () =})})+describe('GET /external/gfs/shares (delegation metadata parity)', () => {+ it('lists shares for an ordinary user with manage_acl and hides inaccessible/missing resources', async () => {+ auth()+ const item = {+ id: 'aaaaaaaa-0000-4000-8000-000000000001',+ drive: 'main',+ resource_id: R,+ subject_type: 'user',+ subject_id: U2,+ permissions: ['read'],+ include_descendants: true,+ }+ dbReturning(+ [+ {+ subject_type: 'user',+ subject_id: U1,+ resource_id: R,+ permissions: ['manage_acl'],+ inherit: false,+ },+ ],+ { grantListRows: [item] }+ )++ const allowed = await request(await buildApp())+ .get(`/external/gfs/shares?drive=main&resourceId=${R}`)+ .set('x-user-session-token', 'sess')+ expect(allowed.status).toBe(200)+ expect(allowed.body.items).toEqual([+ expect.objectContaining({+ id: item.id,+ resourceId: R,+ subject: { type: 'user', id: U2 },+ includeDescendants: true,+ }),+ ])++ mockQuery.mockReset()+ dbReturning([])+ const hidden = await request(await buildApp())+ .get(`/external/gfs/shares?drive=main&resourceId=${R2}`)+ .set('x-user-session-token', 'sess')+ expect(hidden.status).toBe(403)+ expect(hidden.body.error).toBe('manage_acl_required')+ })+})+describe('authenticated bulk grant/share transport', () => {const authority = (permissions: string[]) =>dbReturning([@@ -1026,6 +1302,7 @@ describe('user resource mutations via gfsc proxy', () => {subject: U1,drive: 'main',scopes: ['gfs.write'],+ principalType: 'user',})expect(fetchMock).toHaveBeenCalledWith('http://gfsc-writer.gfs.svc:8087/v1/resources/' + R_RID + '/children',@@ -1059,6 +1336,7 @@ describe('user resource mutations via gfsc proxy', () => {subject: U1,drive: 'main',scopes: ['gfs.delete'],+ principalType: 'user',})expect(fetchMock).toHaveBeenCalledWith('http://gfsc-writer.gfs.svc:8087/v1/resources/' + R_RID,@@ -1335,7 +1613,7 @@ describe('per-agent delegation surface (guard + list + rate limit)', () => {const bucketCall = mockQuery.mock.calls.find(call =>String(call[0]).includes('rate_limit_buckets'))- expect(bucketCall?.[1]?.[0]).toBe(`gfsgrants-ext:${U1}`)+ expect(bucketCall?.[1]?.[0]).toBe(`gfsgrants-ext:user:${U1}`)})it('keys the external delegation plane in a bucket DISTINCT from the admin plane for the same subject', async () => {@@ -1362,7 +1640,7 @@ describe('per-agent delegation surface (guard + list + rate limit)', () => {)?.[1]?.[0]// Both planes emitted a bucket key for the same subject…- expect(externalKey).toBe(`gfsgrants-ext:${U1}`)+ expect(externalKey).toBe(`gfsgrants-ext:user:${U1}`)expect(adminKey).toBe(`gfsgrants:${U1}`)// …and they are DISTINCT buckets (never collide). The `-ext` separator means// the external key does not fall under the admin `gfsgrants:` namespace.@@ -1420,6 +1698,7 @@ describe('user read proxy via gfsc (GET /external/gfs/proxy/:rid)', () => {subject: U1,drive: 'main',scopes: ['gfs.read'],+ principalType: 'user',})expect(fetchMock).toHaveBeenCalledWith(`http://gfsc.gfs.svc:8087/v1/resources/${R}/content`,diff --git a/control-api/test/services.directory.adminProvisioning.test.ts b/control-api/test/services.directory.adminProvisioning.test.tsindex 23ebf7926..f9947cfa8 100644--- a/control-api/test/services.directory.adminProvisioning.test.ts+++ b/control-api/test/services.directory.adminProvisioning.test.ts@@ -5,6 +5,7 @@ import { ensureDefaultTeamAndGrants } from '../src/services/directory/adminProviconst dbMocks = vi.hoisted(() => ({ txQuery: vi.fn() }))const traceMocks = vi.hoisted(() => ({ appendPermissionEvents: vi.fn() }))+const operatorLinkMocks = vi.hoisted(() => ({ linkInTransaction: vi.fn() }))vi.mock('../src/db.js', () => ({pool: { query: vi.fn() },withTransaction: async (work: (db: { query: typeof dbMocks.txQuery }) => Promise<unknown>) =>@@ -13,6 +14,11 @@ vi.mock('../src/db.js', () => ({vi.mock('../src/services/tracing/controlApiPermissionEvents.js', () => ({appendControlApiPermissionEventsInTransaction: traceMocks.appendPermissionEvents,}))+vi.mock('../src/services/gfsDesktopOperatorLinkService.js', () => ({+ gfsDesktopOperatorLinkService: {+ linkInTransaction: operatorLinkMocks.linkInTransaction,+ },+}))describe('ensureDefaultTeamAndGrants', () => {it('creates team + admin membership + team/user grants when user has none', async () => {@@ -68,7 +74,19 @@ describe('ensureDefaultTeamAndGrants', () => {})describe('provisionAdminDesktopWorkspace', () => {- beforeEach(() => dbMocks.txQuery.mockReset())+ beforeEach(() => {+ dbMocks.txQuery.mockReset()+ operatorLinkMocks.linkInTransaction.mockReset()+ operatorLinkMocks.linkInTransaction.mockResolvedValue({+ created: true,+ link: {+ desktopUserId: 'user-1',+ controlAdminId: 'admin-1',+ source: 'initial_setup',+ createdAt: new Date('2026-08-10T12:00:00.000Z'),+ },+ })+ })it('creates user, sets password, and provisions team + grants for a new email', async () => {dbMocks.txQuery@@ -82,11 +100,13 @@ describe('provisionAdminDesktopWorkspace', () => {const mod = await import('../src/services/directory/adminProvisioning.js')await mod.provisionAdminDesktopWorkspace({+ controlAdminId: 'admin-1',email: '[email protected]',displayName: 'Ada',passwordHash: 'HASH',agentNames: ['chatllm'],contextIds: ['context1'],+ linkDesktopOperator: false,})expect(dbMocks.txQuery).toHaveBeenCalledWith(expect.stringContaining('INSERT INTO users'), [@@ -113,11 +133,13 @@ describe('provisionAdminDesktopWorkspace', () => {const mod = await import('../src/services/directory/adminProvisioning.js')await mod.provisionAdminDesktopWorkspace({+ controlAdminId: 'admin-1',email: '[email protected]',displayName: 'Old',passwordHash: 'H',agentNames: [],contextIds: [],+ linkDesktopOperator: false,})expect(dbMocks.txQuery).not.toHaveBeenCalledWith(@@ -139,11 +161,13 @@ describe('provisionAdminDesktopWorkspace', () => {const mod = await import('../src/services/directory/adminProvisioning.js')await mod.provisionAdminDesktopWorkspace({+ controlAdminId: 'admin-1',email: '[email protected]',displayName: 'Old',passwordHash: 'H',agentNames: [],contextIds: [],+ linkDesktopOperator: false,seedPassword: false,})@@ -164,11 +188,13 @@ describe('provisionAdminDesktopWorkspace', () => {const mod = await import('../src/services/directory/adminProvisioning.js')await mod.provisionAdminDesktopWorkspace({+ controlAdminId: 'admin-1',email: '[email protected]',displayName: 'Ada',passwordHash: 'HASH',agentNames: ['chatllm'],contextIds: ['context1'],+ linkDesktopOperator: false,seedPassword: false,})@@ -181,6 +207,58 @@ describe('provisionAdminDesktopWorkspace', () => {['team-1', 'chatllm'])})++ it('creates the exact initial-setup operator link inside the Desktop provisioning transaction', async () => {+ dbMocks.txQuery+ .mockResolvedValueOnce({ rows: [{ id: 'user-1' }], rowCount: 1 })+ .mockResolvedValueOnce({ rows: [], rowCount: 1 })+ .mockResolvedValueOnce({ rows: [], rowCount: 1 })+ .mockResolvedValueOnce({ rows: [{ id: 'team-1' }], rowCount: 1 })++ const mod = await import('../src/services/directory/adminProvisioning.js')+ const result = await mod.provisionAdminDesktopWorkspace({+ controlAdminId: 'admin-1',+ email: '[email protected]',+ displayName: 'Admin',+ passwordHash: 'HASH',+ agentNames: [],+ contextIds: [],+ linkDesktopOperator: true,+ })++ expect(result).toEqual({ userId: 'user-1' })+ expect(operatorLinkMocks.linkInTransaction).toHaveBeenCalledWith(+ expect.objectContaining({ query: dbMocks.txQuery }),+ {+ desktopUserId: 'user-1',+ controlAdminId: 'admin-1',+ operatorSub: 'admin-1',+ source: 'initial_setup',+ }+ )+ })++ it('fails the Desktop provisioning transaction when initial link creation fails', async () => {+ dbMocks.txQuery+ .mockResolvedValueOnce({ rows: [{ id: 'user-1' }], rowCount: 1 })+ .mockResolvedValueOnce({ rows: [], rowCount: 1 })+ .mockResolvedValueOnce({ rows: [], rowCount: 1 })+ .mockResolvedValueOnce({ rows: [{ id: 'team-1' }], rowCount: 1 })+ operatorLinkMocks.linkInTransaction.mockRejectedValueOnce(new Error('link conflict'))++ const mod = await import('../src/services/directory/adminProvisioning.js')+ await expect(+ mod.provisionAdminDesktopWorkspace({+ controlAdminId: 'admin-1',+ email: '[email protected]',+ displayName: 'Admin',+ passwordHash: 'HASH',+ agentNames: [],+ contextIds: [],+ linkDesktopOperator: true,+ })+ ).rejects.toThrow('link conflict')+ })})describe('provisionMemberFromAdmin', () => {diff --git a/control-api/test/services.gfsDesktopOperatorLinkService.test.ts b/control-api/test/services.gfsDesktopOperatorLinkService.test.tsnew file mode 100644index 000000000..d78838d90--- /dev/null+++ b/control-api/test/services.gfsDesktopOperatorLinkService.test.ts@@ -0,0 +1,438 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import type { DbClient } from '../src/db.js'+import {+ GfsDesktopOperatorLinkError,+ GfsDesktopOperatorLinkService,+} from '../src/services/gfsDesktopOperatorLinkService.js'++const DESKTOP_USER_ID = '11111111-1111-4111-8111-111111111111'+const OTHER_DESKTOP_USER_ID = '22222222-2222-4222-8222-222222222222'+const CONTROL_ADMIN_ID = '33333333-3333-4333-8333-333333333333'+const OTHER_CONTROL_ADMIN_ID = '44444444-4444-4444-8444-444444444444'+const OPERATOR_ID = '55555555-5555-4555-8555-555555555555'+const CREATED_AT = new Date('2026-08-10T12:00:00.000Z')++function storedLink(+ desktopUserId = DESKTOP_USER_ID,+ controlAdminId = CONTROL_ADMIN_ID,+ source: unknown = 'initial_setup'+) {+ return {+ user_id: desktopUserId,+ control_admin_id: controlAdminId,+ source,+ created_at: CREATED_AT,+ }+}++describe('GfsDesktopOperatorLinkService', () => {+ const txQuery = vi.fn()+ const readQuery = vi.fn()+ const appendPermissionEvents = vi.fn()+ const transaction = vi.fn(+ async <T>(work: (db: DbClient) => Promise<T>): Promise<T> => work({ query: txQuery })+ )+ let service: GfsDesktopOperatorLinkService++ beforeEach(() => {+ vi.clearAllMocks()+ appendPermissionEvents.mockResolvedValue('operation-1')+ service = new GfsDesktopOperatorLinkService({+ transaction,+ readDb: { query: readQuery },+ appendPermissionEvents,+ })+ })++ it('locks both exact identities and atomically creates one governed initial-setup link', async () => {+ txQuery+ .mockResolvedValueOnce({ rows: [{ id: DESKTOP_USER_ID }], rowCount: 1 })+ .mockResolvedValueOnce({+ rows: [{ id: CONTROL_ADMIN_ID, status: 'active' }],+ rowCount: 1,+ })+ .mockResolvedValueOnce({ rows: [], rowCount: 0 })+ .mockResolvedValueOnce({ rows: [storedLink()], rowCount: 1 })++ const result = await service.link({+ desktopUserId: DESKTOP_USER_ID,+ controlAdminId: CONTROL_ADMIN_ID,+ operatorSub: OPERATOR_ID,+ source: 'initial_setup',+ })++ expect(result).toEqual({+ created: true,+ link: {+ desktopUserId: DESKTOP_USER_ID,+ controlAdminId: CONTROL_ADMIN_ID,+ source: 'initial_setup',+ createdAt: CREATED_AT,+ },+ })+ expect(transaction).toHaveBeenCalledOnce()+ expect(txQuery.mock.calls[0]?.[0]).toContain('FROM users')+ expect(txQuery.mock.calls[0]?.[0]).toContain('FOR UPDATE')+ expect(txQuery.mock.calls[1]?.[0]).toContain('FROM control_admin_users')+ expect(txQuery.mock.calls[1]?.[0]).toContain('FOR UPDATE')+ expect(appendPermissionEvents).toHaveBeenCalledWith(expect.anything(), {+ operatorSub: OPERATOR_ID,+ operatorKind: 'control_admin',+ changes: [+ {+ action: 'grant',+ resourceClass: 'gfs_desktop_operator_link',+ resourceRef: `gfs_desktop_operator_link:${DESKTOP_USER_ID}:${CONTROL_ADMIN_ID}`,+ subject: { kind: 'user', id: DESKTOP_USER_ID },+ sourceAuditRef: 'gfs_desktop_operator_link_source:initial_setup',+ status: 'linked',+ detailRef: `desktop_user_id:${DESKTOP_USER_ID};control_admin_id:${CONTROL_ADMIN_ID};source:initial_setup`,+ },+ ],+ })+ })++ it('is idempotent for the exact pair and preserves original source/time without a second event', async () => {+ txQuery+ .mockResolvedValueOnce({ rows: [{ id: DESKTOP_USER_ID }], rowCount: 1 })+ .mockResolvedValueOnce({+ rows: [{ id: CONTROL_ADMIN_ID, status: 'active' }],+ rowCount: 1,+ })+ .mockResolvedValueOnce({ rows: [storedLink()], rowCount: 1 })++ await expect(+ service.link({+ desktopUserId: DESKTOP_USER_ID,+ controlAdminId: CONTROL_ADMIN_ID,+ operatorSub: OPERATOR_ID,+ source: 'initial_setup',+ })+ ).resolves.toEqual({+ created: false,+ link: {+ desktopUserId: DESKTOP_USER_ID,+ controlAdminId: CONTROL_ADMIN_ID,+ source: 'initial_setup',+ createdAt: CREATED_AT,+ },+ })+ expect(txQuery).toHaveBeenCalledTimes(3)+ expect(appendPermissionEvents).not.toHaveBeenCalled()+ })++ it.each([+ {+ label: 'Desktop user',+ row: storedLink(DESKTOP_USER_ID, OTHER_CONTROL_ADMIN_ID),+ conflictIdentity: 'desktop_user',+ },+ {+ label: 'Control Admin',+ row: storedLink(OTHER_DESKTOP_USER_ID, CONTROL_ADMIN_ID),+ conflictIdentity: 'control_admin',+ },+ ])(+ 'rejects reassignment when the $label is already linked',+ async ({ row, conflictIdentity }) => {+ txQuery+ .mockResolvedValueOnce({ rows: [{ id: DESKTOP_USER_ID }], rowCount: 1 })+ .mockResolvedValueOnce({+ rows: [{ id: CONTROL_ADMIN_ID, status: 'active' }],+ rowCount: 1,+ })+ .mockResolvedValueOnce({ rows: [row], rowCount: 1 })++ const failure = service.link({+ desktopUserId: DESKTOP_USER_ID,+ controlAdminId: CONTROL_ADMIN_ID,+ operatorSub: OPERATOR_ID,+ source: 'initial_setup',+ })+ await expect(failure).rejects.toMatchObject({+ code: 'link_conflict',+ conflictIdentity,+ })+ expect(appendPermissionEvents).not.toHaveBeenCalled()+ expect(txQuery).toHaveBeenCalledTimes(3)+ }+ )++ it('rejects a missing Desktop user before checking or mutating any link', async () => {+ txQuery.mockResolvedValueOnce({ rows: [], rowCount: 0 })++ await expect(+ service.link({+ desktopUserId: DESKTOP_USER_ID,+ controlAdminId: CONTROL_ADMIN_ID,+ operatorSub: OPERATOR_ID,+ source: 'initial_setup',+ })+ ).rejects.toMatchObject({ code: 'desktop_user_not_found' })+ expect(txQuery).toHaveBeenCalledTimes(1)+ expect(appendPermissionEvents).not.toHaveBeenCalled()+ })++ it.each([+ { rows: [], code: 'control_admin_not_found' },+ { rows: [{ id: CONTROL_ADMIN_ID, status: 'disabled' }], code: 'control_admin_inactive' },+ ])('rejects a missing/inactive Control Admin ($code)', async ({ rows, code }) => {+ txQuery+ .mockResolvedValueOnce({ rows: [{ id: DESKTOP_USER_ID }], rowCount: 1 })+ .mockResolvedValueOnce({ rows, rowCount: rows.length })++ await expect(+ service.link({+ desktopUserId: DESKTOP_USER_ID,+ controlAdminId: CONTROL_ADMIN_ID,+ operatorSub: OPERATOR_ID,+ source: 'initial_setup',+ })+ ).rejects.toMatchObject({ code })+ expect(appendPermissionEvents).not.toHaveBeenCalled()+ })++ it('propagates event failure through the transaction so current state cannot commit alone', async () => {+ const transactionOutcome = { committed: false, rolledBack: false }+ const rollbackAwareTransaction = vi.fn(+ async <T>(work: (db: DbClient) => Promise<T>): Promise<T> => {+ try {+ const result = await work({ query: txQuery })+ transactionOutcome.committed = true+ return result+ } catch (error) {+ transactionOutcome.rolledBack = true+ throw error+ }+ }+ )+ service = new GfsDesktopOperatorLinkService({+ transaction: rollbackAwareTransaction,+ readDb: { query: readQuery },+ appendPermissionEvents,+ })+ txQuery+ .mockResolvedValueOnce({ rows: [{ id: DESKTOP_USER_ID }], rowCount: 1 })+ .mockResolvedValueOnce({+ rows: [{ id: CONTROL_ADMIN_ID, status: 'active' }],+ rowCount: 1,+ })+ .mockResolvedValueOnce({ rows: [], rowCount: 0 })+ .mockResolvedValueOnce({ rows: [storedLink()], rowCount: 1 })+ appendPermissionEvents.mockRejectedValueOnce(new Error('event store unavailable'))++ await expect(+ service.link({+ desktopUserId: DESKTOP_USER_ID,+ controlAdminId: CONTROL_ADMIN_ID,+ operatorSub: OPERATOR_ID,+ source: 'initial_setup',+ })+ ).rejects.toThrow('event store unavailable')+ expect(transactionOutcome).toEqual({ committed: false, rolledBack: true })+ })++ it('resolves only a structurally valid link backed by an active Control Admin', async () => {+ readQuery.mockResolvedValueOnce({+ rows: [+ {+ ...storedLink(),+ desktop_user_exists: true,+ control_admin_exists: true,+ control_admin_status: 'active',+ },+ ],+ rowCount: 1,+ })++ await expect(service.resolveActiveLink(DESKTOP_USER_ID)).resolves.toEqual({+ desktopUserId: DESKTOP_USER_ID,+ controlAdminId: CONTROL_ADMIN_ID,+ source: 'initial_setup',+ createdAt: CREATED_AT,+ })+ })++ it('returns null only when no current-state link exists', async () => {+ readQuery.mockResolvedValueOnce({ rows: [], rowCount: 0 })+ await expect(service.resolveActiveLink(DESKTOP_USER_ID)).resolves.toBeNull()+ })++ it.each([+ {+ label: 'missing admin',+ row: {+ ...storedLink(),+ desktop_user_exists: true,+ control_admin_exists: false,+ control_admin_status: null,+ },+ code: 'control_admin_not_found',+ },+ {+ label: 'inactive admin',+ row: {+ ...storedLink(),+ desktop_user_exists: true,+ control_admin_exists: true,+ control_admin_status: 'disabled',+ },+ code: 'control_admin_inactive',+ },+ {+ label: 'unknown source',+ row: {+ ...storedLink(DESKTOP_USER_ID, CONTROL_ADMIN_ID, 'email_match'),+ desktop_user_exists: true,+ control_admin_exists: true,+ control_admin_status: 'active',+ },+ code: 'malformed_link',+ },+ ])('fails closed for $label link data', async ({ row, code }) => {+ readQuery.mockResolvedValueOnce({ rows: [row], rowCount: 1 })+ await expect(service.resolveActiveLink(DESKTOP_USER_ID)).rejects.toMatchObject({ code })+ })++ it('wraps database resolution failures as a typed fail-closed error', async () => {+ const databaseError = new Error('connection lost')+ readQuery.mockRejectedValueOnce(databaseError)++ const failure = service.resolveActiveLink(DESKTOP_USER_ID)+ await expect(failure).rejects.toMatchObject({ code: 'resolution_failed' })+ await expect(failure).rejects.toBeInstanceOf(GfsDesktopOperatorLinkError)+ })++ it('reads the exact active pair by Control Admin for the future revoke surface', async () => {+ readQuery.mockResolvedValueOnce({+ rows: [+ {+ ...storedLink(),+ desktop_user_exists: true,+ control_admin_exists: true,+ control_admin_status: 'active',+ },+ ],+ rowCount: 1,+ })++ await expect(service.getLinkForControlAdmin(CONTROL_ADMIN_ID)).resolves.toEqual({+ desktopUserId: DESKTOP_USER_ID,+ controlAdminId: CONTROL_ADMIN_ID,+ source: 'initial_setup',+ createdAt: CREATED_AT,+ })+ expect(readQuery).toHaveBeenCalledWith(+ expect.stringContaining('WHERE links.control_admin_id = $1::uuid'),+ [CONTROL_ADMIN_ID]+ )+ })++ it('keeps a disabled-admin pair visible to the future revoke surface without granting authority', async () => {+ readQuery.mockResolvedValueOnce({+ rows: [+ {+ ...storedLink(),+ desktop_user_exists: true,+ control_admin_exists: true,+ control_admin_status: 'disabled',+ },+ ],+ rowCount: 1,+ })++ await expect(service.getLinkForControlAdmin(CONTROL_ADMIN_ID)).resolves.toMatchObject({+ desktopUserId: DESKTOP_USER_ID,+ controlAdminId: CONTROL_ADMIN_ID,+ })+ })++ it('returns null for an unlinked Control Admin and fails closed on a mismatched row', async () => {+ readQuery.mockResolvedValueOnce({ rows: [], rowCount: 0 })+ await expect(service.getLinkForControlAdmin(CONTROL_ADMIN_ID)).resolves.toBeNull()++ readQuery.mockResolvedValueOnce({+ rows: [+ {+ ...storedLink(DESKTOP_USER_ID, OTHER_CONTROL_ADMIN_ID),+ desktop_user_exists: true,+ control_admin_exists: true,+ control_admin_status: 'active',+ },+ ],+ rowCount: 1,+ })+ await expect(service.getLinkForControlAdmin(CONTROL_ADMIN_ID)).rejects.toMatchObject({+ code: 'malformed_link',+ })+ })++ it('appends the governed unlink evidence before deleting current state', async () => {+ txQuery+ .mockResolvedValueOnce({ rows: [storedLink()], rowCount: 1 })+ .mockResolvedValueOnce({ rows: [], rowCount: 1 })++ await expect(+ service.unlink({+ desktopUserId: DESKTOP_USER_ID,+ controlAdminId: CONTROL_ADMIN_ID,+ operatorSub: OPERATOR_ID,+ })+ ).resolves.toEqual({+ unlinked: true,+ link: {+ desktopUserId: DESKTOP_USER_ID,+ controlAdminId: CONTROL_ADMIN_ID,+ source: 'initial_setup',+ createdAt: CREATED_AT,+ },+ })++ expect(appendPermissionEvents).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({+ operatorSub: OPERATOR_ID,+ changes: [+ expect.objectContaining({+ action: 'revoke',+ status: 'unlinked',+ resourceRef: `gfs_desktop_operator_link:${DESKTOP_USER_ID}:${CONTROL_ADMIN_ID}`,+ sourceAuditRef: 'gfs_desktop_operator_link_source:initial_setup',+ }),+ ],+ })+ )+ expect(appendPermissionEvents.mock.invocationCallOrder[0]).toBeLessThan(+ txQuery.mock.invocationCallOrder[1]!+ )+ expect(txQuery.mock.calls[1]?.[0]).toContain('DELETE FROM gfs_desktop_operator_links')+ })++ it('does not delete current state when governed unlink evidence fails', async () => {+ txQuery.mockResolvedValueOnce({ rows: [storedLink()], rowCount: 1 })+ appendPermissionEvents.mockRejectedValueOnce(new Error('event append failed'))++ await expect(+ service.unlink({+ desktopUserId: DESKTOP_USER_ID,+ controlAdminId: CONTROL_ADMIN_ID,+ operatorSub: OPERATOR_ID,+ })+ ).rejects.toThrow('event append failed')+ expect(txQuery).toHaveBeenCalledTimes(1)+ })++ it('makes unlink idempotent without emitting evidence for a nonexistent lifecycle change', async () => {+ txQuery.mockResolvedValueOnce({ rows: [], rowCount: 0 })++ await expect(+ service.unlink({+ desktopUserId: DESKTOP_USER_ID,+ controlAdminId: CONTROL_ADMIN_ID,+ operatorSub: OPERATOR_ID,+ })+ ).resolves.toEqual({ unlinked: false, link: null })+ expect(appendPermissionEvents).not.toHaveBeenCalled()+ expect(txQuery).toHaveBeenCalledTimes(1)+ })+})diff --git a/control-ui/components/ControlAdminsPanel/index.tsx b/control-ui/components/ControlAdminsPanel/index.tsxindex 3dcb8bec1..6addc4d06 100644--- a/control-ui/components/ControlAdminsPanel/index.tsx+++ b/control-ui/components/ControlAdminsPanel/index.tsx@@ -16,6 +16,7 @@ import {cancelControlAdminInvitation,deleteControlAdmin,getControlAdmins,+ revokeControlAdminGfsOperatorLink,} from '@lib/api'import type { ControlAdminsPanelProps } from './types'@@ -45,6 +46,7 @@ export function ControlAdminsPanel({const [loading, setLoading] = useState(true)const [cancellingInvitationId, setCancellingInvitationId] = useState<string | null>(null)const [deletingAdminId, setDeletingAdminId] = useState<string | null>(null)+ const [revokingGfsLinkAdminId, setRevokingGfsLinkAdminId] = useState<string | null>(null)const [error, setError] = useState('')const normalizedSearch = searchInput.trim().toLowerCase()@@ -180,6 +182,48 @@ export function ControlAdminsPanel({}}+ async function handleRevokeGfsOperatorLink(admin: ControlAdminListItem) {+ const label = admin.email ? `${admin.username} (${admin.email})` : admin.username+ const shouldRevoke = await confirm({+ title: 'Revoke Desktop GFS operator access',+ message: `Revoke Desktop GFS operator access for ${label}? The Control Admin, both passwords, and unrelated Control Plane access will remain unchanged.`,+ confirmLabel: 'Revoke access',+ tone: 'danger',+ })+ if (!shouldRevoke) return++ setRevokingGfsLinkAdminId(admin.id)+ setError('')+ try {+ const result = await revokeControlAdminGfsOperatorLink(admin.id)+ setAdmins(current =>+ current.map(item =>+ item.id === admin.id+ ? {+ ...item,+ gfsOperatorLink: null,+ gfsOperatorLinkStatus: 'revoked',+ }+ : item+ )+ )+ showToast(+ result.revoked+ ? 'Desktop GFS operator access revoked.'+ : 'Desktop GFS operator access was already revoked.',+ { tone: 'success' }+ )+ } catch (revokeError) {+ setError(+ revokeError instanceof Error+ ? revokeError.message+ : 'Failed to revoke Desktop GFS operator access'+ )+ } finally {+ setRevokingGfsLinkAdminId(null)+ }+ }+function openMemberAccess(admin: ControlAdminListItem) {if (admin.memberId) {router.push(CONTROL_ROUTES.usersAndTeams.user(admin.memberId))@@ -246,13 +290,14 @@ export function ControlAdminsPanel({<th>Username</th><th>Email</th><th>Status</th>+ <th>Desktop GFS access</th><th>Last sign-in</th><th aria-label="Actions" /></tr></thead><tbody>{loading ? (- <SkeletonTableRows columns={5} rows={5} />+ <SkeletonTableRows columns={6} rows={5} />) : filteredAdmins.length > 0 ? (filteredAdmins.map(admin => {const currentAdmin = isCurrentAdmin(admin)@@ -278,6 +323,30 @@ export function ControlAdminsPanel({</td><td>{admin.email || 'No email set'}</td><td>{formatAdminStatus(admin.status)}</td>+ <td>+ {admin.gfsOperatorLink ? (+ <div data-testid={`gfs-operator-link-${admin.id}`}>+ <div>+ {admin.gfsOperatorLink.status === 'active'+ ? 'Active'+ : admin.gfsOperatorLink.status === 'inactive_admin'+ ? 'Inactive admin'+ : 'Error'}+ </div>+ <div className="cu-table__cell-muted">+ Desktop user: {admin.gfsOperatorLink.desktopUserId}+ </div>+ <div className="cu-table__cell-muted">+ Control Admin: {admin.gfsOperatorLink.controlAdminId}+ </div>+ <div className="cu-table__cell-muted">+ Source: {admin.gfsOperatorLink.source}+ </div>+ </div>+ ) : (+ <span data-testid={`gfs-operator-link-${admin.id}`}>Revoked</span>+ )}+ </td><td>{formatDate(admin.lastLoginAt)}</td><td className="cu-table__cell-actions"><div className="cu-row-actions cu-row-actions--nowrap">@@ -303,6 +372,22 @@ export function ControlAdminsPanel({><IconUsers /></button>+ {admin.gfsOperatorLink && admin.gfsOperatorLink.status !== 'error' ? (+ <button+ type="button"+ className="cu-btn cu-btn--danger"+ disabled={revokingGfsLinkAdminId === admin.id}+ onClick={() => void handleRevokeGfsOperatorLink(admin)}+ aria-label={+ revokingGfsLinkAdminId === admin.id+ ? `Revoking Desktop GFS operator access for ${label}`+ : `Revoke Desktop GFS operator access for ${label}`+ }+ title="Remove only GFS operator authority; keep the admin and passwords"+ >+ {revokingGfsLinkAdminId === admin.id ? 'Revoking...' : 'Revoke GFS'}+ </button>+ ) : null}{currentAdmin ? (<buttontype="button"@@ -344,7 +429,7 @@ export function ControlAdminsPanel({})) : (<tr>- <td colSpan={5}>+ <td colSpan={6}>{normalizedSearch ? 'No admins match this search.' : 'No admins found.'}</td></tr>diff --git a/control-ui/components/__tests__/ControlAdminsPanel.gfsOperatorLink.test.tsx b/control-ui/components/__tests__/ControlAdminsPanel.gfsOperatorLink.test.tsxnew file mode 100644index 000000000..f215be260--- /dev/null+++ b/control-ui/components/__tests__/ControlAdminsPanel.gfsOperatorLink.test.tsx@@ -0,0 +1,118 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { getControlAdmins, revokeControlAdminGfsOperatorLink } from '@lib/api'+import { ControlAdminsPanel } from '../ControlAdminsPanel'++const confirmMock = vi.hoisted(() => vi.fn())+const showToastMock = vi.hoisted(() => vi.fn())++vi.mock('next/navigation', () => ({+ useRouter: () => ({ push: vi.fn() }),+}))++vi.mock('@components/AuthContext', () => ({+ useAuth: () => ({+ authState: {+ id: 'admin-1',+ isLoggedIn: true,+ isLoading: false,+ username: 'initial-admin',+ email: '[email protected]',+ },+ }),+}))++vi.mock('@components/ConfirmDialog', () => ({+ useConfirmDialog: () => ({ confirm: confirmMock, confirmDialog: null }),+}))++vi.mock('@components/Toast', () => ({+ useToast: () => ({ showToast: showToastMock }),+}))++vi.mock('@lib/api', async () => {+ const actual = await vi.importActual<typeof import('@lib/api')>('@lib/api')+ return {+ ...actual,+ getControlAdmins: vi.fn(),+ revokeControlAdminGfsOperatorLink: vi.fn(),+ }+})++const LINK = {+ desktopUserId: '11111111-1111-4111-8111-111111111111',+ controlAdminId: 'admin-1',+ source: 'initial_setup' as const,+ createdAt: '2026-08-10T12:00:00.000Z',+ status: 'active' as const,+}++describe('ControlAdminsPanel GFS operator link lifecycle', () => {+ beforeEach(() => {+ confirmMock.mockResolvedValue(true)+ vi.mocked(getControlAdmins).mockResolvedValue({+ admins: [+ {+ id: 'admin-1',+ username: 'initial-admin',+ email: '[email protected]',+ memberId: LINK.desktopUserId,+ status: 'active',+ gfsOperatorLink: LINK,+ gfsOperatorLinkStatus: 'active',+ lastLoginAt: null,+ createdAt: '2026-08-10T11:00:00.000Z',+ },+ ],+ invitations: [],+ })+ vi.mocked(revokeControlAdminGfsOperatorLink).mockResolvedValue({+ revoked: true,+ gfsOperatorLinkStatus: 'revoked',+ controlAdminId: 'admin-1',+ desktopUserId: LINK.desktopUserId,+ })+ })++ afterEach(() => {+ cleanup()+ vi.clearAllMocks()+ })++ it('shows the exact pair and revokes only GFS operator access after confirmation', async () => {+ render(<ControlAdminsPanel />)++ await screen.findByText(`Desktop user: ${LINK.desktopUserId}`)+ expect(screen.getByText(`Control Admin: ${LINK.controlAdminId}`)).toBeInTheDocument()+ expect(+ screen.getByRole('button', {+ name: 'Revoke Desktop GFS operator access for initial-admin ([email protected])',+ })+ ).toBeInTheDocument()++ fireEvent.click(+ screen.getByRole('button', {+ name: 'Revoke Desktop GFS operator access for initial-admin ([email protected])',+ })+ )++ await waitFor(() => expect(revokeControlAdminGfsOperatorLink).toHaveBeenCalledWith('admin-1'))+ expect(showToastMock).toHaveBeenCalledWith('Desktop GFS operator access revoked.', {+ tone: 'success',+ })+ expect(screen.getByTestId('gfs-operator-link-admin-1')).toHaveTextContent('Revoked')+ })++ it('does not call the revoke API when confirmation is declined', async () => {+ confirmMock.mockResolvedValueOnce(false)+ render(<ControlAdminsPanel />)++ const revokeButton = await screen.findByRole('button', {+ name: 'Revoke Desktop GFS operator access for initial-admin ([email protected])',+ })+ fireEvent.click(revokeButton)++ await waitFor(() => expect(confirmMock).toHaveBeenCalled())+ expect(revokeControlAdminGfsOperatorLink).not.toHaveBeenCalled()+ })+})diff --git a/control-ui/lib/api.ts b/control-ui/lib/api.tsindex 175af2183..09696fe0a 100644--- a/control-ui/lib/api.ts+++ b/control-ui/lib/api.ts@@ -547,6 +547,14 @@ export type ControlAdminListItem = {status: 'active' | 'disabled' | 'pending_password'passwordPending?: booleaninvitationId?: string+ gfsOperatorLink?: {+ desktopUserId: string+ controlAdminId: string+ source: 'initial_setup' | 'unknown'+ createdAt: string | null+ status: 'active' | 'inactive_admin' | 'error'+ } | null+ gfsOperatorLinkStatus?: 'active' | 'inactive_admin' | 'revoked' | 'error'lastLoginAt: string | nullcreatedAt: string}@@ -636,6 +644,23 @@ export async function deleteControlAdmin(adminId: string): Promise<{ deleted: tr}>}+export async function revokeControlAdminGfsOperatorLink(adminId: string): Promise<{+ revoked: boolean+ gfsOperatorLinkStatus: 'revoked'+ controlAdminId: string+ desktopUserId: string | null+}> {+ return apiSend(+ 'DELETE',+ `/api/v1/admin/control-admins/${encodeURIComponent(adminId)}/gfs-operator-link`+ ) as Promise<{+ revoked: boolean+ gfsOperatorLinkStatus: 'revoked'+ controlAdminId: string+ desktopUserId: string | null+ }>+}+export async function createMemberFromControlAdmin(adminId: string,payload: { reusePassword: boolean; teams: Array<{ teamId: string; role: TeamRole }> }diff --git a/deploy/overlays/minikube/configmaps/control-api-config.yaml b/deploy/overlays/minikube/configmaps/control-api-config.yamlindex d4d5f41d0..045626268 100644--- a/deploy/overlays/minikube/configmaps/control-api-config.yaml+++ b/deploy/overlays/minikube/configmaps/control-api-config.yaml@@ -32,6 +32,9 @@ data:CONTROL_API_DESKTOP_RPC_PROXY_BASE_URL: 'http://127.0.0.1:8094'CONTROL_API_DESKTOP_PROFILE_UI_BASE_URL: 'http://127.0.0.1:3001'CONTROL_API_DESKTOP_APP_NAME: 'Evenfire'+ # Self-hosted-only GFS operator parity. Managed/base deployments remain+ # fail-closed because this narrow elevation flag is absent there.+ CONTROL_API_DESKTOP_GFS_OPERATOR_LINKING_ENABLED: 'true'CONTROL_API_CONTROL_UI_BASE_URL: 'http://127.0.0.1:3000'CONTROL_API_CONTROL_UI_APP_NAME: 'Evenfire'CONTROL_API_POLICY_AUTH_AUDIENCE: 'control-api'diff --git a/desktop-app/package.json b/desktop-app/package.jsonindex 1b144708b..a335bed5b 100644--- a/desktop-app/package.json+++ b/desktop-app/package.json@@ -14,6 +14,7 @@"test": "vitest run","test:e2e": "vitest run --config test/e2e/vitest.config.ts","test:e2e:playwright": "npm run build && playwright test --config test/e2e-playwright/playwright.config.ts",+ "test:e2e:gfs-operator": "npm run build && playwright test --config test/e2e-playwright/playwright.gfs-desktop-operator.config.ts","qa:recorder:auth": "npm run build && playwright test --config test/e2e-playwright/playwright.qa-recorder.config.ts qa-recorder-auth.spec.ts","qa:recorder:navigation": "npm run build && playwright test --config test/e2e-playwright/playwright.qa-recorder.config.ts qa-recorder-navigation.spec.ts","qa:recorder:agents": "npm run build && playwright test --config test/e2e-playwright/playwright.qa-recorder.config.ts qa-recorder-agents.spec.ts",diff --git a/desktop-app/src/__tests__/appService.gfs.test.ts b/desktop-app/src/__tests__/appService.gfs.test.tsindex c0dc1fd0b..7b09935de 100644--- a/desktop-app/src/__tests__/appService.gfs.test.ts+++ b/desktop-app/src/__tests__/appService.gfs.test.ts@@ -15,6 +15,8 @@ function gfsService() {gfsClient: {grant: ReturnType<typeof vi.fn>createShare: ReturnType<typeof vi.fn>+ listShares: ReturnType<typeof vi.fn>+ revokeShare: ReturnType<typeof vi.fn>}grantGfs: (resourceId: string,@@ -24,16 +26,34 @@ function gfsService() {inherit?: boolean) => Promise<void>createGfsShare: (resourceId: string, subjectKeys: string[], drive?: string) => Promise<void>+ listGfsShares: (resourceId: string, drive?: string) => Promise<unknown[]>+ revokeGfsShare: (shareId: string) => Promise<void>}service.sessionToken = 'session-token'service.gfsClient = {grant: vi.fn().mockResolvedValue(undefined),createShare: vi.fn().mockResolvedValue(undefined),+ listShares: vi.fn().mockResolvedValue([]),+ revokeShare: vi.fn().mockResolvedValue(undefined),}return service}describe('AppService GFS delegation subject boundary', () => {+ it('forwards share list and revoke through the in-memory session token only', async () => {+ const service = gfsService()+ const shareId = '22222222-2222-4222-8222-222222222222'++ await service.listGfsShares(RESOURCE_ID, 'main')+ await service.revokeGfsShare(shareId)++ expect(service.gfsClient.listShares).toHaveBeenCalledWith(+ { resourceId: RESOURCE_ID, drive: 'main' },+ 'session-token'+ )+ expect(service.gfsClient.revokeShare).toHaveBeenCalledWith(shareId, 'session-token')+ })+it('passes only user/team grant subjects as ONE bulk subjects[] array', async () => {const service = gfsService()diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.tsindex f634eaf67..681e8a266 100644--- a/desktop-app/src/appService.ts+++ b/desktop-app/src/appService.ts@@ -1081,6 +1081,16 @@ export class AppService {await this.gfsClient.revokeGrant(grantId, this.requireSessionToken())}+ /** List direct URI shares on a resource for the combined access-management view. */+ async listGfsShares(resourceId: string, drive?: string) {+ return this.gfsClient.listShares({ resourceId, drive }, this.requireSessionToken())+ }++ /** Revoke a direct URI share by its server-issued row id. */+ async revokeGfsShare(shareId: string) {+ await this.gfsClient.revokeShare(shareId, this.requireSessionToken())+ }+/*** The caller's own agents with their canonical GFS host subjects — the grant* targets for per-agent delegation. Served fresh from external-rest-apidiff --git a/desktop-app/src/gfs/uriHandler.ts b/desktop-app/src/gfs/uriHandler.tsindex fa15e8a83..1a294c535 100644--- a/desktop-app/src/gfs/uriHandler.ts+++ b/desktop-app/src/gfs/uriHandler.ts@@ -114,15 +114,23 @@ export interface GfsChildrenPage {nextCursor: string | null}-export interface GfsAccessibleResource extends GfsResourceView {- sources: string[]- permissions: string[]- coversDescendants: boolean+export type GfsAccessibleResource = Omit<GfsResourceView, 'drive' | 'parentResourceId'> & {+ /** Operator-root children omit these ordinary/proxy response fields. */+ drive?: string+ parentResourceId?: string | null+ /** Present on the ordinary Shared-with-me view; root children do not need provenance. */+ sources?: string[]+ permissions?: string[]+ coversDescendants?: boolean}export interface GfsAccessibleResourcesPage {items: GfsAccessibleResource[]nextCursor: string | null+ /** Present only when the server resolved this Desktop session as a linked GFS operator. */+ rootResourceId?: string+ /** Non-secret renderer mode marker. Absence preserves the ordinary shared-resource view. */+ view?: 'operator'}/** Grant/share subject grammar (control-api routes/gfs/grants.ts parseSubject). */@@ -170,6 +178,16 @@ export interface GfsGrantListItem {inherit: boolean}+/** One direct URI-share row as GET /me/gfs/shares returns it. */+export interface GfsShareListItem {+ id: string+ drive: string+ resourceId: string+ subject: { type: string; id?: string }+ permissions: string[]+ includeDescendants: boolean+}+/** Bits the caller holds on a resource, as the affordances route reports them. */export interface GfsHeldAffordances {held: string[]@@ -207,8 +225,8 @@ export interface GfsDeleteInput {const DEFAULT_DRIVE = 'main'const TRANSPORT_TOKEN_FIELD = ['tok', 'en'].join('') as 'token'-/** Grant ids name gfs_grants rows (control-api routes/gfs/grants.ts UUID_RE). */-const GRANT_ID_RE = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/+/** Grant/share ids name ACL rows (control-api routes/gfs UUID_RE). */+const ACL_ID_RE = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$//*** Shape of a managed host subject id: `<party>:<namespace>/<name>` with k8s@@ -482,7 +500,7 @@ export class GfsClient {* built so a malformed value can never become a path segment.*/async revokeGrant(grantId: string, token: string): Promise<void> {- if (!GRANT_ID_RE.test(grantId)) {+ if (!ACL_ID_RE.test(grantId)) {throw new GfsUriError(`grant id must be a UUID: ${JSON.stringify(grantId)}`)}await this.transport.requestJson(@@ -513,6 +531,43 @@ export class GfsClient {throw surfaceGfsGrantError(error)}}++ /** List direct URI shares on one resource. This route is never inferred from grants. */+ async listShares(+ input: { resourceId: string; drive?: string },+ token: string+ ): Promise<GfsShareListItem[]> {+ const q = new URLSearchParams()+ q.set('drive', input.drive ?? DEFAULT_DRIVE)+ q.set('resourceId', input.resourceId)+ let payload: { items: GfsShareListItem[] }+ try {+ payload = await this.transport.requestJson<{ items: GfsShareListItem[] }>(+ 'GET',+ joinUrl(this.transport.baseUrl, '/api/v1/me/gfs/shares?' + q.toString()),+ { token }+ )+ } catch (error) {+ throw surfaceGfsGrantError(error)+ }+ if (!payload || typeof payload !== 'object' || !Array.isArray(payload.items)) {+ throw new GfsUriError('unexpected gfs shares response: missing items array')+ }+ return payload.items+ }++ /** Revoke a direct URI share by the UUID learned from listShares. */+ async revokeShare(shareId: string, token: string): Promise<void> {+ if (!ACL_ID_RE.test(shareId)) {+ throw new GfsUriError(`share id must be a UUID: ${JSON.stringify(shareId)}`)+ }+ await this.transport.requestJson(+ 'DELETE',+ joinUrl(this.transport.baseUrl, `/api/v1/me/gfs/shares/${encodeURIComponent(shareId)}`),+ { token }+ )+ }+async createResource(input: GfsCreateInput, session: string): Promise<GfsResourceView> {return createGfsResource(this.transport, input, session)}diff --git a/desktop-app/src/ipc.ts b/desktop-app/src/ipc.tsindex bd5248dca..cda724307 100644--- a/desktop-app/src/ipc.ts+++ b/desktop-app/src/ipc.ts@@ -516,6 +516,18 @@ export function registerIpcHandlers(service: AppService): void {assertTrustedSender(event)return service.revokeGfsGrant(sanitizeString(payload?.grantId))})+ ipcMain.handle(+ 'gfs:listShares',+ async (event, payload: { resourceId: string; drive?: string }) => {+ assertTrustedSender(event)+ const drive = payload?.drive ? sanitizeString(payload.drive) : undefined+ return service.listGfsShares(sanitizeString(payload?.resourceId), drive)+ }+ )+ ipcMain.handle('gfs:revokeShare', async (event, payload: { shareId: string }) => {+ assertTrustedSender(event)+ return service.revokeGfsShare(sanitizeString(payload?.shareId))+ })ipcMain.handle('gfs:createShare',async (event, payload: { resourceId: string; subjectKeys: string[]; drive?: string }) => {diff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.tsindex 4bd823c18..0f685064b 100644--- a/desktop-app/src/preload.ts+++ b/desktop-app/src/preload.ts@@ -98,6 +98,9 @@ const clerum = Object.freeze({listGrants: (resourceId: string, drive?: string) =>ipcRenderer.invoke('gfs:listGrants', { resourceId, drive }),revokeGrant: (grantId: string) => ipcRenderer.invoke('gfs:revokeGrant', { grantId }),+ listShares: (resourceId: string, drive?: string) =>+ ipcRenderer.invoke('gfs:listShares', { resourceId, drive }),+ revokeShare: (shareId: string) => ipcRenderer.invoke('gfs:revokeShare', { shareId }),// A desktop share grants READ access only (the minimal shared capability) —// unlike `grant`, it takes no permission bits by design. The server still// enforces the caller holds read + share (no-escalation).diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.tsindex 85f97e70c..6648baf73 100644--- a/desktop-app/src/renderer.d.ts+++ b/desktop-app/src/renderer.d.ts@@ -133,18 +133,20 @@ declare global {resourceId: stringrid: stringgfsUri: string- drive: string- parentResourceId: string | null+ drive?: string+ parentResourceId?: string | nullname: stringkind: 'file' | 'directory'path: string | nullversion: numberbytes: number- sources: string[]- permissions: string[]- coversDescendants: boolean+ sources?: string[]+ permissions?: string[]+ coversDescendants?: boolean}>nextCursor: string | null+ rootResourceId?: string+ view?: 'operator'}>listChildren: (resourceId: string,@@ -256,6 +258,20 @@ declare global {}>>revokeGrant: (grantId: string) => Promise<void>+ listShares: (+ resourceId: string,+ drive?: string+ ) => Promise<+ Array<{+ id: string+ drive: string+ resourceId: string+ subject: { type: string; id?: string }+ permissions: string[]+ includeDescendants: boolean+ }>+ >+ revokeShare: (shareId: string) => Promise<void>createShare: (resourceId: string, subjectKeys: string[], drive?: string) => Promise<void>}agents: {diff --git a/desktop-app/test/e2e-playwright/gfs-desktop-operator-parity.global-setup.ts b/desktop-app/test/e2e-playwright/gfs-desktop-operator-parity.global-setup.tsnew file mode 100644index 000000000..d81f4103c--- /dev/null+++ b/desktop-app/test/e2e-playwright/gfs-desktop-operator-parity.global-setup.ts@@ -0,0 +1,257 @@+import { execFileSync } from 'node:child_process'+import { createHash } from 'node:crypto'+import fs from 'node:fs'+import path from 'node:path'+import {+ gfsOperatorRuntimeEvidencePath,+ requireGfsOperatorRunId,+ writeJsonAtomically,+} from './gfsDesktopOperatorParityContract'+import { validateBaseUrls } from './global-setup'++const DESKTOP_APP_ROOT = path.resolve(__dirname, '../..')+const REPO_ROOT = path.resolve(DESKTOP_APP_ROOT, '..')+const REQUIRED_ARTIFACT_FILES = [+ path.join(DESKTOP_APP_ROOT, 'dist/main.js'),+ path.join(DESKTOP_APP_ROOT, 'dist/preload.js'),+ path.join(DESKTOP_APP_ROOT, 'ui-dist/index.html'),+]++function command(command: string, args: string[]): string {+ return execFileSync(command, args, {+ encoding: 'utf8',+ stdio: ['ignore', 'pipe', 'pipe'],+ }).trim()+}++function requiredEnvironment(name: string, candidates: Array<string | undefined>): string {+ const value = candidates.find(candidate => candidate?.trim())?.trim()+ if (!value) throw new Error(`[GFS-OPERATOR-E2E] ${name} is required.`)+ return value+}++function sha256File(filePath: string): string {+ return createHash('sha256').update(fs.readFileSync(filePath)).digest('hex')+}++function filesUnder(directory: string): string[] {+ return fs.readdirSync(directory, { withFileTypes: true }).flatMap(entry => {+ const entryPath = path.join(directory, entry.name)+ if (entry.isDirectory()) return filesUnder(entryPath)+ return entry.isFile() ? [entryPath] : []+ })+}++function isLoopbackUrl(rawUrl: string): boolean {+ try {+ return new Set(['127.0.0.1', 'localhost', '::1']).has(new URL(rawUrl).hostname)+ } catch {+ return false+ }+}++async function assertHttpReady(baseUrl: string, label: string, pathName: string): Promise<void> {+ let response: Response+ try {+ response = await fetch(`${baseUrl.replace(/\/$/, '')}${pathName}`, {+ redirect: 'manual',+ signal: AbortSignal.timeout(10_000),+ })+ } catch (error) {+ throw new Error(+ `[GFS-OPERATOR-E2E] ${label} is unavailable at ${baseUrl}${pathName}: ${(error as Error).message}`+ )+ }+ if (response.status < 200 || response.status >= 400) {+ throw new Error(+ `[GFS-OPERATOR-E2E] ${label} returned HTTP ${response.status} at ${baseUrl}${pathName}.`+ )+ }+}++function assertRepositoryHarness(): Array<{+ path: string+ sha256: string+ bytes: number+}> {+ const missing = REQUIRED_ARTIFACT_FILES.filter(filePath => !fs.existsSync(filePath))+ if (missing.length > 0) {+ throw new Error(+ `[GFS-OPERATOR-E2E] repository Electron harness is incomplete: ${missing+ .map(filePath => path.relative(REPO_ROOT, filePath))+ .join(', ')}. Build Desktop before running the suite.`+ )+ }+ const artifactFiles = [+ ...filesUnder(path.join(DESKTOP_APP_ROOT, 'dist')).filter(+ filePath =>+ !filePath.includes(`${path.sep}__tests__${path.sep}`) && !filePath.endsWith('.test.js')+ ),+ ...filesUnder(path.join(DESKTOP_APP_ROOT, 'ui-dist')).filter(+ filePath => path.basename(filePath) !== '.gitkeep'+ ),+ ].sort()+ return artifactFiles.map(filePath => ({+ path: path.relative(REPO_ROOT, filePath),+ sha256: sha256File(filePath),+ bytes: fs.statSync(filePath).size,+ }))+}++export default async function globalSetup(): Promise<void> {+ const runId = requireGfsOperatorRunId()+ const profile = requiredEnvironment('MINIKUBE_PROFILE', [process.env.MINIKUBE_PROFILE])+ const context = requiredEnvironment('E2E_K8S_CONTEXT', [process.env.E2E_K8S_CONTEXT])+ if (profile !== context) {+ throw new Error(+ `[GFS-OPERATOR-E2E] MINIKUBE_PROFILE=${profile} must equal E2E_K8S_CONTEXT=${context}.`+ )+ }+ if (!/^clerum-.+-[0-9a-f]{7,8}$/.test(context)) {+ throw new Error(`[GFS-OPERATOR-E2E] context=${context} is not a branch-owned profile name.`)+ }+ const selectedContext = command('kubectl', [+ '--context',+ context,+ 'config',+ 'view',+ '--minify',+ '-o',+ 'jsonpath={.contexts[0].name}',+ ])+ if (selectedContext !== context) {+ throw new Error(+ `[GFS-OPERATOR-E2E] explicit kubectl context resolved to ${selectedContext}; expected ${context}.`+ )+ }++ const head = command('git', ['-C', REPO_ROOT, 'rev-parse', 'HEAD'])+ const branch = command('git', ['-C', REPO_ROOT, 'branch', '--show-current'])+ const originDev = command('git', ['-C', REPO_ROOT, 'rev-parse', 'origin/dev'])+ const dirty = command('git', [+ '-C',+ REPO_ROOT,+ 'status',+ '--porcelain=v1',+ '--untracked-files=all',+ ])+ if (dirty) {+ throw new Error(+ '[GFS-OPERATOR-E2E] exact-HEAD evidence requires a clean worktree. Commit the intended implementation before the runtime gate.'+ )+ }+ if (!branch) {+ throw new Error('[GFS-OPERATOR-E2E] detached HEAD is not accepted for this branch-owned lane.')+ }++ const marker = JSON.parse(+ command('kubectl', [+ '--context',+ context,+ '-n',+ 'control-plane',+ 'get',+ 'configmap',+ 'clerum-pre-gate-sync-state',+ '-o',+ 'json',+ ])+ ) as { data?: Record<string, string> }+ const markerData = marker.data ?? {}+ const worktreeId = createHash('sha1').update(REPO_ROOT).digest('hex')+ if (+ markerData.gitHead !== head ||+ markerData.worktreeId !== worktreeId ||+ !markerData.clusterFingerprint+ ) {+ throw new Error(+ '[GFS-OPERATOR-E2E] branch profile marker does not match this exact worktree/HEAD: ' ++ `markerHead=${markerData.gitHead ?? '<missing>'} markerWorktree=${markerData.worktreeId ?? '<missing>'} ` ++ `expectedHead=${head} expectedWorktree=${worktreeId}.`+ )+ }+ const expectedFingerprint = process.env.E2E_EXPECTED_CLUSTER_FINGERPRINT?.trim()+ if (expectedFingerprint && markerData.clusterFingerprint !== expectedFingerprint) {+ throw new Error(+ `[GFS-OPERATOR-E2E] cluster fingerprint ${markerData.clusterFingerprint} does not match E2E_EXPECTED_CLUSTER_FINGERPRINT=${expectedFingerprint}.`+ )+ }++ const controlUi = requiredEnvironment('CONTROL_UI_BASE_URL', [+ process.env.CONTROL_UI_BASE_URL,+ process.env.CONTROL_UI_URL,+ ])+ const controlApi = requiredEnvironment('CONTROL_API_BASE_URL', [+ process.env.CONTROL_API_BASE_URL,+ process.env.CONTROL_API_URL,+ process.env.E2E_CONTROL_API_URL,+ ])+ const externalRest = requiredEnvironment('EXTERNAL_REST_API_BASE_URL', [+ process.env.EXTERNAL_REST_API_BASE_URL,+ process.env.EXTERNAL_REST_API_URL,+ process.env.E2E_EXTERNAL_REST_API_URL,+ ])+ const rpcProxy = requiredEnvironment('RPC_PROXY_BASE_URL', [+ process.env.RPC_PROXY_BASE_URL,+ process.env.RPC_PROXY_URL,+ process.env.E2E_RPC_PROXY_URL,+ ])+ validateBaseUrls({+ expectedContext: context,+ controlUiUrl: controlUi,+ controlApiUrl: controlApi,+ externalRestUrl: externalRest,+ rpcProxyUrl: rpcProxy,+ allowDevPortForward: false,+ })+ for (const [name, value] of Object.entries({ controlUi, controlApi, externalRest, rpcProxy })) {+ if (!isLoopbackUrl(value)) {+ throw new Error(`[GFS-OPERATOR-E2E] ${name} must use its branch-owned loopback forward.`)+ }+ }++ await Promise.all([+ assertHttpReady(controlUi, 'control-ui', '/'),+ assertHttpReady(controlApi, 'control-api', '/health'),+ assertHttpReady(externalRest, 'external-rest-api', '/health'),+ assertHttpReady(rpcProxy, 'rpc-proxy', '/health'),+ ])++ const artifactFiles = assertRepositoryHarness()+ const artifactFingerprint = createHash('sha256')+ .update(JSON.stringify(artifactFiles.map(file => [file.path, file.sha256, file.bytes])))+ .digest('hex')+ writeJsonAtomically(gfsOperatorRuntimeEvidencePath(runId), {+ schemaVersion: 1,+ suite: 'gfs-desktop-operator-parity',+ runId,+ capturedAt: new Date().toISOString(),+ repository: {+ root: REPO_ROOT,+ branch,+ head,+ originDev,+ clean: true,+ worktreeId,+ },+ runtime: {+ minikubeProfile: profile,+ kubernetesContext: context,+ clusterFingerprint: markerData.clusterFingerprint,+ markerGitHead: markerData.gitHead,+ markerWorktreeId: markerData.worktreeId,+ urls: { controlUi, controlApi, externalRest, rpcProxy },+ },+ artifact: {+ kind: 'repository-electron-harness',+ fingerprintSha256: artifactFingerprint,+ files: artifactFiles,+ },+ bootstrap: {+ entryPoint: '/admin/auth/setup',+ expectedStatus: 200,+ singleUse: true,+ positiveUiEvidence: false,+ },+ })+}diff --git a/desktop-app/test/e2e-playwright/gfs-desktop-operator-parity.reporter.ts b/desktop-app/test/e2e-playwright/gfs-desktop-operator-parity.reporter.tsnew file mode 100644index 000000000..68feaab17--- /dev/null+++ b/desktop-app/test/e2e-playwright/gfs-desktop-operator-parity.reporter.ts@@ -0,0 +1,95 @@+import type {+ FullConfig,+ FullResult,+ Reporter,+ TestCase,+ TestResult,+} from '@playwright/test/reporter'+import fs from 'node:fs'+import {+ type GfsOperatorScenarioResult,+ evaluateGfsOperatorScenarioResults,+ gfsOperatorResultSummaryPath,+ gfsOperatorRuntimeEvidencePath,+ requireGfsOperatorRunId,+ scenarioIdFromTitle,+ writeJsonAtomically,+} from './gfsDesktopOperatorParityContract'++export default class GfsDesktopOperatorParityReporter implements Reporter {+ private readonly results: GfsOperatorScenarioResult[] = []+ private configurationErrors: string[] = []++ onBegin(config: FullConfig): void {+ if (config.workers !== 1) {+ this.configurationErrors.push(`workers must be 1; received ${config.workers}`)+ }+ if (config.projects.some(project => project.retries !== 0)) {+ this.configurationErrors.push('retries must be 0 for every project')+ }+ }++ onTestEnd(test: TestCase, result: TestResult): void {+ const id = scenarioIdFromTitle(test.title)+ if (!id) return+ this.results.push({+ id,+ status: result.status,+ title: test.titlePath().join(' > '),+ })+ }++ async onEnd(result: FullResult): Promise<{ status: 'failed' } | void> {+ let runId: string+ try {+ runId = requireGfsOperatorRunId()+ } catch (error) {+ // eslint-disable-next-line no-console+ console.error(error)+ return { status: 'failed' }+ }++ const runtimeEvidencePath = gfsOperatorRuntimeEvidencePath(runId)+ const verdict = evaluateGfsOperatorScenarioResults(+ this.results,+ fs.existsSync(runtimeEvidencePath)+ )+ const errors = [...this.configurationErrors, ...verdict.errors]+ if (result.status !== 'passed') {+ errors.push(`Playwright ended with status=${result.status}`)+ }+ const ok = errors.length === 0+ writeJsonAtomically(gfsOperatorResultSummaryPath(runId), {+ schemaVersion: 1,+ suite: 'gfs-desktop-operator-parity',+ runId,+ completedAt: new Date().toISOString(),+ playwrightStatus: result.status,+ ok,+ errors,+ totals: {+ required: verdict.required,+ observed: verdict.observed,+ passed: verdict.passed,+ failed: verdict.failed,+ skipped: verdict.skipped,+ },+ scenarios: this.results,+ runtimeEvidencePath,+ })++ if (!ok) {+ // eslint-disable-next-line no-console+ console.error(`[GFS-OPERATOR-E2E] FAIL-LOUD: ${errors.join('; ')}`)+ return { status: 'failed' }+ }+ // eslint-disable-next-line no-console+ console.log(+ `[GFS-OPERATOR-E2E] PASS ${verdict.passed}/${verdict.required} required scenarios · run=${runId}`+ )+ }++ printsToStdio(): boolean {+ return true+ }+}diff --git a/desktop-app/test/e2e-playwright/gfs-desktop-operator-parity.test.ts b/desktop-app/test/e2e-playwright/gfs-desktop-operator-parity.test.tsnew file mode 100644index 000000000..699227a55--- /dev/null+++ b/desktop-app/test/e2e-playwright/gfs-desktop-operator-parity.test.ts@@ -0,0 +1,539 @@+import type { Locator, Page } from '@playwright/test'+import { UUID_RE } from '../../../tests/e2e/gfsFixtureCore'+import { type GfsResourceRow, expect, test } from './helpers/gfsDesktopOperatorParityFixtures'++async function expectToast(page: Page, message: string): Promise<void> {+ await expect(page.getByRole('status', { name: message, exact: true })).toBeVisible({+ timeout: 30_000,+ })+}++function resourceRow(page: Page, resource: GfsResourceRow): Locator {+ return page.getByTestId(`gfs-resource-row-${resource.resourceId}`)+}++async function openResourceManage(page: Page, resource: GfsResourceRow): Promise<Locator> {+ const row = resourceRow(page, resource)+ await expect(row).toBeVisible({ timeout: 30_000 })+ await row.getByRole('button', { name: `Options for ${resource.name}` }).click()+ await page.getByRole('menuitem', { name: 'Manage', exact: true }).click()+ const dialog = page.getByRole('dialog', {+ name: `Manage ${resource.kind === 'directory' ? 'folder' : 'file'} ${resource.name}`,+ })+ await expect(dialog).toBeVisible()+ return dialog+}++async function closeManageDialog(page: Page): Promise<void> {+ const close = page.getByRole('button', { name: 'Close manage dialog' })+ if ((await close.count()) > 0) await close.click()+}++async function uploadVisibleFile(+ page: Page,+ trigger: Locator,+ file: { name: string; mimeType: string; buffer: Buffer }+): Promise<void> {+ const chooserPromise = page.waitForEvent('filechooser')+ await trigger.click()+ const chooser = await chooserPromise+ await chooser.setFiles(file)+}++async function createRootFolder(+ page: Page,+ name: string,+ readResource: () => GfsResourceRow | null+): Promise<GfsResourceRow> {+ await page.getByTestId('gfs-create-folder-action').click()+ const form = page.getByRole('form', { name: 'Create folder' })+ await expect(form).toBeVisible()+ await form.getByLabel('Folder name').fill(name)+ await form.getByRole('button', { name: 'Create folder' }).click()+ await expectToast(page, `Folder ${name} created`)+ await expect.poll(readResource, { timeout: 30_000, intervals: [250, 500, 1_000] }).toMatchObject({+ name,+ kind: 'directory',+ deleted: false,+ })+ const resource = readResource()+ if (!resource) throw new Error(`folder ${name} was not persisted`)+ await closeManageDialog(page)+ await expect(resourceRow(page, resource)).toBeVisible({ timeout: 30_000 })+ return resource+}++async function selectOrdinarySubject(page: Page, ordinaryEmail: string): Promise<void> {+ const picker = page.getByRole('combobox', { name: 'Add people or teams' })+ await expect(picker).toBeVisible({ timeout: 30_000 })+ await picker.fill(ordinaryEmail)+ const listbox = page.getByRole('listbox', { name: 'Available people and teams' })+ await expect(listbox).toBeVisible()+ await listbox.getByRole('option').filter({ hasText: ordinaryEmail }).click()+}++test.describe.serial('GFS Desktop linked-operator parity', () => {+ test('@gfs-operator/setup-linked-operator setup creates the exact link before visible Desktop login', async ({+ operatorJourney,+ }) => {+ const setup = await operatorJourney.bootstrapInitialAdmin()+ await expect+ .poll(() => operatorJourney.readOperatorLink(), {+ timeout: 30_000,+ intervals: [250, 500, 1_000],+ message: 'waiting for /admin/auth/setup to persist its exact Desktop operator link',+ })+ .toMatchObject({ controlAdminId: setup.controlAdminId, source: 'initial_setup' })++ operatorJourney.operatorLink = operatorJourney.readOperatorLink()+ expect(operatorJourney.operatorLink).not.toBeNull()+ expect(operatorJourney.operatorLink?.controlAdminId).toBe(setup.controlAdminId)+ operatorJourney.createOrdinaryUserFixture()+ const rootResourceId = operatorJourney.readRootResourceId()++ const controlPage = await operatorJourney.loginControlUi()+ await operatorJourney.openControlAdmins()+ const linkStatus = controlPage.getByTestId(`gfs-operator-link-${setup.controlAdminId}`)+ await expect(linkStatus).toContainText('Active')+ await expect(linkStatus).toContainText(operatorJourney.operatorLink!.desktopUserId)+ await expect(linkStatus).toContainText(setup.controlAdminId)+ await expect(linkStatus).toContainText('initial_setup')+ await expect(+ controlPage.getByRole('button', {+ name: `Revoke Desktop GFS operator access for ${operatorJourney.operatorUsername} (${operatorJourney.operatorEmail})`,+ })+ ).toBeVisible()++ const desktopPage = await operatorJourney.launchOperatorDesktop()+ await operatorJourney.openFiles(desktopPage)+ await expect(desktopPage.getByTestId('gfs-view-operator')).toBeVisible()+ const root = desktopPage.getByTestId('gfs-root-operator')+ await expect(root).toHaveText('Global File System')+ await expect(root).toHaveAttribute('data-resource-id', rootResourceId)+ await expect(desktopPage.getByTestId('gfs-manage-access-action')).toBeVisible()+ })++ test('@gfs-operator/operator-root-crud root create/upload and nested CRUD use visible Desktop actions', async ({+ operatorJourney,+ }, testInfo) => {+ const page = operatorJourney.operatorPage!+ const rootId = operatorJourney.rootResourceId!+ expect(operatorJourney.operatorSubjectGrantCount()).toBe(0)+ await expect(page.getByTestId('gfs-view-operator')).toBeVisible()+ await expect(page.getByTestId('gfs-root-operator')).toHaveAttribute('data-resource-id', rootId)++ const crudFolder = await createRootFolder(page, operatorJourney.names.crudFolder, () =>+ operatorJourney.readResource(rootId, operatorJourney.names.crudFolder)+ )+ operatorJourney.resources.set('crudFolder', crudFolder)++ await uploadVisibleFile(page, page.getByTestId('gfs-upload-action'), {+ name: operatorJourney.names.rootFile,+ mimeType: 'text/markdown',+ buffer: Buffer.from('# root upload\n', 'utf8'),+ })+ await expectToast(page, `Uploaded ${operatorJourney.names.rootFile}`)+ await expect+ .poll(() => operatorJourney.readResource(rootId, operatorJourney.names.rootFile), {+ timeout: 30_000,+ intervals: [250, 500, 1_000],+ })+ .toMatchObject({ kind: 'file', deleted: false })+ const rootFile = operatorJourney.readResource(rootId, operatorJourney.names.rootFile)!+ operatorJourney.resources.set('rootFile', rootFile)++ let dialog = await openResourceManage(page, crudFolder)+ await dialog.getByRole('button', { name: `Options for ${crudFolder.name}` }).click()+ await page.getByRole('menuitem', { name: 'Rename', exact: true }).click()+ const renameForm = dialog.getByRole('form', { name: 'Rename resource' })+ await renameForm.getByLabel('New name').fill(operatorJourney.names.renamedFolder)+ await renameForm.getByRole('button', { name: 'Save' }).click()+ await expectToast(page, `Renamed to ${operatorJourney.names.renamedFolder}`)+ await closeManageDialog(page)+ await expect+ .poll(() => operatorJourney.readResource(rootId, operatorJourney.names.renamedFolder), {+ timeout: 30_000,+ intervals: [250, 500, 1_000],+ })+ .toMatchObject({ resourceId: crudFolder.resourceId, deleted: false })+ const renamedFolder = operatorJourney.readResource(rootId, operatorJourney.names.renamedFolder)!+ operatorJourney.resources.set('renamedFolder', renamedFolder)++ await resourceRow(page, renamedFolder)+ .getByRole('button', { name: renamedFolder.name, exact: true })+ .click()+ await expect(page.getByRole('navigation', { name: 'File location' })).toContainText(+ renamedFolder.name+ )+ await expect(page.getByTestId('gfs-root-operator')).toHaveAttribute('data-resource-id', rootId)++ await uploadVisibleFile(page, page.getByTestId('gfs-upload-action'), {+ name: operatorJourney.names.nestedFile,+ mimeType: 'text/markdown',+ buffer: Buffer.from('# nested version one\n', 'utf8'),+ })+ await expectToast(page, `Uploaded ${operatorJourney.names.nestedFile}`)+ await expect+ .poll(+ () =>+ operatorJourney.readResource(renamedFolder.resourceId, operatorJourney.names.nestedFile),+ { timeout: 30_000, intervals: [250, 500, 1_000] }+ )+ .toMatchObject({ kind: 'file', deleted: false })+ let nestedFile = operatorJourney.readResource(+ renamedFolder.resourceId,+ operatorJourney.names.nestedFile+ )!++ await resourceRow(page, nestedFile)+ .getByRole('button', { name: nestedFile.name, exact: true })+ .click()+ const preview = page.getByRole('dialog', { name: nestedFile.name })+ await expect(preview).toBeVisible()+ await expect(+ page.getByRole('article', { name: `Markdown preview of ${nestedFile.name}` })+ ).toContainText('nested version one')+ await page.getByRole('button', { name: 'Close Markdown preview' }).click()++ dialog = await openResourceManage(page, nestedFile)+ await dialog.getByRole('button', { name: `Options for ${nestedFile.name}` }).click()+ await page.getByRole('menuitem', { name: 'Rename', exact: true }).click()+ await dialog+ .getByRole('form', { name: 'Rename resource' })+ .getByLabel('New name')+ .fill(operatorJourney.names.renamedFile)+ await dialog+ .getByRole('form', { name: 'Rename resource' })+ .getByRole('button', { name: 'Save' })+ .click()+ await expectToast(page, `Renamed to ${operatorJourney.names.renamedFile}`)+ await expect+ .poll(+ () =>+ operatorJourney.readResource(renamedFolder.resourceId, operatorJourney.names.renamedFile),+ { timeout: 30_000, intervals: [250, 500, 1_000] }+ )+ .toMatchObject({ resourceId: nestedFile.resourceId, deleted: false })+ nestedFile = operatorJourney.readResource(+ renamedFolder.resourceId,+ operatorJourney.names.renamedFile+ )!+ dialog = page.getByRole('dialog', {+ name: `Manage file ${operatorJourney.names.renamedFile}`,+ })+ await expect(dialog).toBeVisible()++ await uploadVisibleFile(page, dialog.getByRole('button', { name: 'Replace file' }), {+ name: operatorJourney.names.renamedFile,+ mimeType: 'text/markdown',+ buffer: Buffer.from('# nested version two\n', 'utf8'),+ })+ await expectToast(page, `Replaced ${operatorJourney.names.renamedFile}`)+ await expect+ .poll(+ () =>+ operatorJourney.readResource(renamedFolder.resourceId, operatorJourney.names.renamedFile),+ { timeout: 30_000, intervals: [250, 500, 1_000] }+ )+ .toMatchObject({ version: nestedFile.version + 1, deleted: false })++ await dialog+ .getByRole('button', { name: `Options for ${operatorJourney.names.renamedFile}` })+ .click()+ const downloadPromise = page.waitForEvent('download')+ await page.getByRole('menuitem', { name: 'Download', exact: true }).click()+ const download = await downloadPromise+ expect(download.suggestedFilename()).toBe(operatorJourney.names.renamedFile)+ await download.saveAs(testInfo.outputPath(operatorJourney.names.renamedFile))+ await expectToast(page, `Downloaded ${operatorJourney.names.renamedFile}`)++ await dialog+ .getByRole('button', { name: `Options for ${operatorJourney.names.renamedFile}` })+ .click()+ await page.getByRole('menuitem', { name: 'Delete', exact: true }).click()+ const deleteDialog = page.getByRole('alertdialog', { name: 'Delete resource' })+ await deleteDialog.getByRole('button', { name: 'Delete', exact: true }).click()+ await expectToast(page, `Deleted ${operatorJourney.names.renamedFile}`)+ await expect+ .poll(+ () =>+ operatorJourney.readResource(renamedFolder.resourceId, operatorJourney.names.renamedFile),+ { timeout: 30_000, intervals: [250, 500, 1_000] }+ )+ .toMatchObject({ deleted: true })++ await page.getByTestId('gfs-root-operator').click()+ const renamedFolderAfterChildDelete = operatorJourney.readResource(+ rootId,+ operatorJourney.names.renamedFolder+ )!+ dialog = await openResourceManage(page, renamedFolderAfterChildDelete)+ await dialog+ .getByRole('button', { name: `Options for ${operatorJourney.names.renamedFolder}` })+ .click()+ await page.getByRole('menuitem', { name: 'Delete', exact: true }).click()+ await page+ .getByRole('alertdialog', { name: 'Delete resource' })+ .getByRole('button', { name: 'Delete', exact: true })+ .click()+ await expectToast(page, `Deleted ${operatorJourney.names.renamedFolder}`)++ operatorJourney.successfulCreateAuditFloor = operatorJourney.auditFloor()+ for (const [key, name] of [+ ['grantFolder', operatorJourney.names.grantFolder],+ ['shareFolder', operatorJourney.names.shareFolder],+ ['ordinaryFolder', operatorJourney.names.ordinaryFolder],+ ] as const) {+ const folder = await createRootFolder(page, name, () =>+ operatorJourney.readResource(rootId, name)+ )+ operatorJourney.resources.set(key, folder)+ }+ })++ test('@gfs-operator/ordinary-unlinked-regression unlinked Desktop remains grant-scoped Shared with me', async ({+ operatorJourney,+ }, testInfo) => {+ const ordinaryFolder = operatorJourney.resources.get('ordinaryFolder')!+ const fixtureGrantId = operatorJourney.seedOrdinaryReadGrant(ordinaryFolder.resourceId)+ const ordinary = await operatorJourney.launchOrdinaryDesktop(testInfo)+ try {+ await operatorJourney.openFiles(ordinary.page)+ await expect(ordinary.page.getByTestId('gfs-view-shared')).toBeVisible()+ await expect(ordinary.page.getByTestId('gfs-root-shared')).toHaveText('Shared with me')+ await expect(resourceRow(ordinary.page, ordinaryFolder)).toBeVisible()+ await expect(ordinary.page.getByTestId('gfs-create-folder-action')).toHaveCount(0)+ await expect(ordinary.page.getByTestId('gfs-upload-action')).toHaveCount(0)+ await expect(ordinary.page.getByTestId('gfs-manage-access-action')).toHaveCount(0)+ expect(operatorJourney.findGrant(ordinaryFolder.resourceId)?.id).toBe(fixtureGrantId)+ } finally {+ await ordinary.close()+ operatorJourney.removeFixtureGrant(fixtureGrantId)+ }+ await expect.poll(() => operatorJourney.findGrant(ordinaryFolder.resourceId)).toBeNull()+ })++ test('@gfs-operator/grant-share-lifecycle visible Desktop grant/share create, list, revoke removes recipient access', async ({+ operatorJourney,+ }, testInfo) => {+ const page = operatorJourney.operatorPage!+ const grantFolder = operatorJourney.resources.get('grantFolder')!+ const shareFolder = operatorJourney.resources.get('shareFolder')!+ const auditFloor = operatorJourney.auditFloor()++ let dialog = await openResourceManage(page, grantFolder)+ await selectOrdinarySubject(page, operatorJourney.ordinaryEmail)+ await dialog.getByRole('button', { name: 'Grant access', exact: true }).click()+ await expectToast(page, 'Access granted to 1 subject')+ await expect+ .poll(() => operatorJourney.findGrant(grantFolder.resourceId), {+ timeout: 30_000,+ intervals: [250, 500, 1_000],+ })+ .not.toBeNull()+ const grant = operatorJourney.findGrant(grantFolder.resourceId)!+ await expect(page.getByTestId(`gfs-access-row-grant-${grant.id}`)).toContainText(+ operatorJourney.ordinaryName+ )+ await closeManageDialog(page)++ dialog = await openResourceManage(page, shareFolder)+ await selectOrdinarySubject(page, operatorJourney.ordinaryEmail)+ await dialog.getByRole('button', { name: 'Create share', exact: true }).click()+ await expectToast(page, '1 share created')+ await expect+ .poll(() => operatorJourney.findShare(shareFolder.resourceId), {+ timeout: 30_000,+ intervals: [250, 500, 1_000],+ })+ .not.toBeNull()+ const share = operatorJourney.findShare(shareFolder.resourceId)!+ await expect(page.getByTestId(`gfs-access-row-share-${share.id}`)).toContainText(+ operatorJourney.ordinaryName+ )+ await closeManageDialog(page)++ const ordinary = await operatorJourney.launchOrdinaryDesktop(testInfo)+ try {+ await operatorJourney.openFiles(ordinary.page)+ await expect(ordinary.page.getByTestId('gfs-view-shared')).toBeVisible()+ await expect(resourceRow(ordinary.page, grantFolder)).toBeVisible()+ await expect(resourceRow(ordinary.page, shareFolder)).toBeVisible()++ dialog = await openResourceManage(page, grantFolder)+ await page.getByTestId(`gfs-revoke-grant-${grant.id}`).click()+ await expectToast(page, `Access revoked for ${operatorJourney.ordinaryName}`)+ await expect.poll(() => operatorJourney.findGrant(grantFolder.resourceId)).toBeNull()+ await closeManageDialog(page)++ dialog = await openResourceManage(page, shareFolder)+ await page.getByTestId(`gfs-revoke-share-${share.id}`).click()+ await expectToast(page, `Shared access revoked for ${operatorJourney.ordinaryName}`)+ await expect.poll(() => operatorJourney.findShare(shareFolder.resourceId)).toBeNull()+ await closeManageDialog(page)++ await ordinary.page.getByTestId('nav-chat').click()+ await operatorJourney.openFiles(ordinary.page)+ await expect(resourceRow(ordinary.page, grantFolder)).toHaveCount(0)+ await expect(resourceRow(ordinary.page, shareFolder)).toHaveCount(0)+ await expect(ordinary.page.getByTestId('gfs-empty-shared')).toBeVisible()+ } finally {+ await ordinary.close()+ }++ await expect+ .poll(+ () =>+ operatorJourney+ .auditRowsAfter(auditFloor, operatorJourney.operatorLink!.desktopUserId)+ .filter(+ row => row.authoritySource === 'linked-admin' && /^(grant|share)\./.test(row.op)+ )+ .map(row => row.op),+ { timeout: 30_000, intervals: [250, 500, 1_000] }+ )+ .toEqual(+ expect.arrayContaining([+ 'grant.put[read]',+ 'grant.delete',+ 'share.create[read]',+ 'share.delete',+ ])+ )+ })++ test('@gfs-operator/live-control-ui-unlink visible Control UI revoke immediately denies same Electron session', async ({+ operatorJourney,+ }) => {+ const controlPage = operatorJourney.controlPage!+ const page = operatorJourney.operatorPage!+ const link = operatorJourney.operatorLink!+ await expect(controlPage).toHaveURL(/\/users-and-teams\/admins(?:\?|$)/)+ const revoke = controlPage.getByRole('button', {+ name: `Revoke Desktop GFS operator access for ${operatorJourney.operatorUsername} (${operatorJourney.operatorEmail})`,+ })+ await expect(revoke).toBeVisible()+ await revoke.click()+ const confirm = controlPage.getByRole('alertdialog', {+ name: 'Revoke Desktop GFS operator access',+ })+ await expect(confirm).toBeVisible()+ await confirm.getByRole('button', { name: 'Revoke access', exact: true }).click()+ await expect(+ controlPage.getByText('Desktop GFS operator access revoked.', { exact: true })+ ).toBeVisible({ timeout: 30_000 })+ await expect(controlPage.getByTestId(`gfs-operator-link-${link.controlAdminId}`)).toHaveText(+ 'Revoked'+ )+ await expect.poll(() => operatorJourney.operatorLinkCount()).toBe(0)++ operatorJourney.deniedAuditFloor = operatorJourney.auditFloor()+ await page.getByTestId('gfs-create-folder-action').click()+ const form = page.getByRole('form', { name: 'Create folder' })+ await form.getByLabel('Folder name').fill(operatorJourney.names.deniedFolder)+ await form.getByRole('button', { name: 'Create folder' }).click()+ const denial = page.getByTestId('gfs-mutation-error-unauthorized')+ await expect(denial).toBeVisible({ timeout: 30_000 })+ await expect(denial).toHaveAttribute('aria-label', 'File access is not authorized')+ await expect(denial).toContainText(+ 'Your current Desktop session cannot access this location. Sign in again or contact an administrator.'+ )+ await expect(page.getByTestId('gfs-create-folder-action')).toHaveCount(0)+ await expect(page.getByTestId('gfs-upload-action')).toHaveCount(0)+ await expect+ .poll(() =>+ operatorJourney.readResource(+ operatorJourney.rootResourceId!,+ operatorJourney.names.deniedFolder+ )+ )+ .toBeNull()+ })++ test('@gfs-operator/audit-correlation successful and denied Desktop requests preserve exact actor and request IDs', async ({+ operatorJourney,+ }) => {+ const link = operatorJourney.operatorLink!+ const page = operatorJourney.operatorPage!+ const controlPage = operatorJourney.controlPage!+ await expect(page.getByTestId('gfs-mutation-error-unauthorized')).toBeVisible()+ await expect(controlPage).toHaveURL(/\/users-and-teams\/admins(?:\?|$)/)+ await expect(controlPage.getByTestId(`gfs-operator-link-${link.controlAdminId}`)).toHaveText(+ 'Revoked'+ )++ await expect+ .poll(+ () => {+ const rows = operatorJourney.auditRowsAfter(+ operatorJourney.successfulCreateAuditFloor,+ link.desktopUserId+ )+ const decisions = rows.filter(+ row =>+ row.subject === link.controlAdminId &&+ row.actorOnBehalfOf === link.controlAdminId &&+ row.authoritySource === 'linked-admin' &&+ row.op === 'write' &&+ row.outcome === 'allow' &&+ row.recordType === 'authorization_decision' &&+ row.mutationOutcome === null &&+ UUID_RE.test(row.requestId ?? '')+ )+ return decisions.some(decision =>+ rows.some(+ mutation =>+ mutation.requestId === decision.requestId &&+ mutation.subject === link.controlAdminId &&+ mutation.actorOnBehalfOf === link.controlAdminId &&+ mutation.desktopUserId === link.desktopUserId &&+ mutation.authoritySource === 'linked-admin' &&+ mutation.op === 'create' &&+ mutation.outcome === 'allow' &&+ mutation.recordType === 'mutation_outcome' &&+ mutation.mutationOutcome === 'succeeded'+ )+ )+ },+ { timeout: 30_000, intervals: [250, 500, 1_000] }+ )+ .toBe(true)++ await expect+ .poll(+ () =>+ operatorJourney+ .auditRowsAfter(operatorJourney.deniedAuditFloor, link.desktopUserId)+ .some(+ row =>+ row.subject === link.desktopUserId &&+ row.actorOnBehalfOf === null &&+ row.desktopUserId === link.desktopUserId &&+ row.authoritySource === 'user-session' &&+ row.op === 'write' &&+ row.outcome === 'deny' &&+ row.recordType === 'authorization_decision' &&+ row.mutationOutcome === null &&+ UUID_RE.test(row.requestId ?? '')+ ),+ { timeout: 30_000, intervals: [250, 500, 1_000] }+ )+ .toBe(true)++ const deniedRows = operatorJourney.auditRowsAfter(+ operatorJourney.deniedAuditFloor,+ link.desktopUserId+ )+ expect(+ deniedRows.filter(row => row.requestId && row.op === 'create' && row.mutationOutcome)+ ).toHaveLength(0)+ const lifecycle = operatorJourney.readUnlinkLifecycleEvent()+ expect(lifecycle).toMatchObject({+ operatorSub: link.controlAdminId,+ targetRef: `gfs_desktop_operator_link:${link.desktopUserId}:${link.controlAdminId}`,+ })+ expect(lifecycle?.detailRef).toContain(`desktop_user_id:${link.desktopUserId}`)+ expect(lifecycle?.detailRef).toContain(`control_admin_id:${link.controlAdminId}`)+ expect(lifecycle?.detailRef).toContain('source:initial_setup')+ })+})diff --git a/desktop-app/test/e2e-playwright/gfsDesktopOperatorParityContract.ts b/desktop-app/test/e2e-playwright/gfsDesktopOperatorParityContract.tsnew file mode 100644index 000000000..8c20c9d9d--- /dev/null+++ b/desktop-app/test/e2e-playwright/gfsDesktopOperatorParityContract.ts@@ -0,0 +1,127 @@+import fs from 'node:fs'+import path from 'node:path'++export const GFS_OPERATOR_REQUIRED_SCENARIOS = [+ '@gfs-operator/setup-linked-operator',+ '@gfs-operator/operator-root-crud',+ '@gfs-operator/grant-share-lifecycle',+ '@gfs-operator/ordinary-unlinked-regression',+ '@gfs-operator/live-control-ui-unlink',+ '@gfs-operator/audit-correlation',+] as const++export type GfsOperatorScenarioId = (typeof GFS_OPERATOR_REQUIRED_SCENARIOS)[number]+export type GfsOperatorScenarioStatus =+ | 'passed'+ | 'failed'+ | 'timedOut'+ | 'skipped'+ | 'interrupted'+ | 'unknown'++export interface GfsOperatorScenarioResult {+ id: GfsOperatorScenarioId+ status: GfsOperatorScenarioStatus+ title: string+}++export interface GfsOperatorContractVerdict {+ ok: boolean+ errors: string[]+ required: number+ observed: number+ passed: number+ failed: number+ skipped: number+}++const RUN_ID_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/++export function requireGfsOperatorRunId(value = process.env.E2E_GFS_OPERATOR_RUN_ID): string {+ const runId = value?.trim() ?? ''+ if (!RUN_ID_RE.test(runId)) {+ throw new Error(+ '[GFS-OPERATOR-E2E] E2E_GFS_OPERATOR_RUN_ID is required and must match ' ++ `${RUN_ID_RE}. Use a distinct run id for each fresh-profile execution.`+ )+ }+ return runId+}++export function gfsOperatorEvidenceDirectory(runId = requireGfsOperatorRunId()): string {+ const configured = process.env.E2E_GFS_OPERATOR_EVIDENCE_DIR?.trim()+ const base = configured+ ? path.resolve(configured)+ : path.resolve(__dirname, 'test-results', 'gfs-desktop-operator-parity')+ return path.join(base, runId)+}++export function gfsOperatorRuntimeEvidencePath(runId = requireGfsOperatorRunId()): string {+ return path.join(gfsOperatorEvidenceDirectory(runId), 'runtime-evidence.json')+}++export function gfsOperatorResultSummaryPath(runId = requireGfsOperatorRunId()): string {+ return path.join(gfsOperatorEvidenceDirectory(runId), 'required-scenarios.json')+}++export function scenarioIdFromTitle(title: string): GfsOperatorScenarioId | null {+ const matches = GFS_OPERATOR_REQUIRED_SCENARIOS.filter(+ id => title === id || title.startsWith(`${id} `)+ )+ return matches.length === 1 ? (matches[0] ?? null) : null+}++export function evaluateGfsOperatorScenarioResults(+ results: readonly GfsOperatorScenarioResult[],+ runtimeEvidencePresent: boolean+): GfsOperatorContractVerdict {+ const errors: string[] = []+ const byId = new Map<GfsOperatorScenarioId, GfsOperatorScenarioResult[]>()+ for (const result of results) {+ const current = byId.get(result.id) ?? []+ current.push(result)+ byId.set(result.id, current)+ }++ if (results.length === 0) {+ errors.push('zero required scenarios executed')+ }+ if (!runtimeEvidencePresent) {+ errors.push('runtime evidence is missing')+ }++ for (const id of GFS_OPERATOR_REQUIRED_SCENARIOS) {+ const matches = byId.get(id) ?? []+ if (matches.length === 0) {+ errors.push(`required scenario missing: ${id}`)+ continue+ }+ if (matches.length > 1) {+ errors.push(`required scenario executed ${matches.length} times: ${id}`)+ continue+ }+ const status = matches[0]?.status ?? 'unknown'+ if (status !== 'passed') {+ errors.push(`required scenario ${id} ended with status=${status}`)+ }+ }++ return {+ ok: errors.length === 0,+ errors,+ required: GFS_OPERATOR_REQUIRED_SCENARIOS.length,+ observed: results.length,+ passed: results.filter(result => result.status === 'passed').length,+ failed: results.filter(result =>+ ['failed', 'timedOut', 'interrupted', 'unknown'].includes(result.status)+ ).length,+ skipped: results.filter(result => result.status === 'skipped').length,+ }+}++export function writeJsonAtomically(filePath: string, value: unknown): void {+ fs.mkdirSync(path.dirname(filePath), { recursive: true })+ const temporaryPath = `${filePath}.${process.pid}.tmp`+ fs.writeFileSync(temporaryPath, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 })+ fs.renameSync(temporaryPath, filePath)+}diff --git a/desktop-app/test/e2e-playwright/helpers/gfsDesktopOperatorParityFixtures.ts b/desktop-app/test/e2e-playwright/helpers/gfsDesktopOperatorParityFixtures.tsnew file mode 100644index 000000000..fefd406d0--- /dev/null+++ b/desktop-app/test/e2e-playwright/helpers/gfsDesktopOperatorParityFixtures.ts@@ -0,0 +1,741 @@+import {+ type Browser,+ type BrowserContext,+ type ElectronApplication,+ type Page,+ type TestInfo,+ type WorkerInfo,+ test as base,+ _electron as electron,+ expect,+} from '@playwright/test'+import { createHash, randomBytes } from 'node:crypto'+import fs from 'node:fs'+import path from 'node:path'+import {+ UUID_RE,+ firstDataLine,+ kubectlOut,+ runControlPostgresSql,+ splitSqlRow,+ sqlLiteral,+} from '../../../../tests/e2e/gfsFixtureCore'+import { cleanupGfsFixture } from '../../../../tests/e2e/gfsResourceFixtures'+import { requireGfsOperatorRunId } from '../gfsDesktopOperatorParityContract'+import { openResourcesNavItem } from '../navigationHelpers'++const DESKTOP_APP_ROOT = path.resolve(__dirname, '../../..')+const MAIN_ENTRY = path.join(DESKTOP_APP_ROOT, 'dist/main.js')++function configuredUrl(label: string, candidates: Array<string | undefined>): string {+ const value = candidates.find(candidate => candidate?.trim())?.trim()+ if (!value) throw new Error(`[GFS-OPERATOR-E2E] ${label} is required.`)+ return value.replace(/\/$/, '')+}++function safeTraceName(title: string): string {+ return title+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-|-$/g, '')+ .slice(0, 80)+}++function bcryptHash(password: string): string {+ const output = kubectlOut(+ [+ '-n',+ 'control-plane',+ 'exec',+ '-i',+ 'deploy/control-api',+ '--',+ 'node',+ '-e',+ [+ "const bcrypt = require('bcryptjs')",+ "let input = ''",+ "process.stdin.on('data', chunk => { input += chunk })",+ "process.stdin.on('end', async () => console.log(await bcrypt.hash(input.trim(), 12)))",+ ].join(';'),+ ],+ 20_000,+ password+ ).trim()+ if (!/^\$2[aby]\$/.test(output)) {+ throw new Error('[GFS-OPERATOR-E2E] bcrypt fixture hash generation failed.')+ }+ return output+}++export interface OperatorLinkRow {+ desktopUserId: string+ controlAdminId: string+ source: string+}++export interface GfsResourceRow {+ resourceId: string+ name: string+ kind: 'directory' | 'file'+ bytes: number+ version: number+ deleted: boolean+}++export interface GfsAuditRow {+ sequenceNo: number+ subject: string+ actorOnBehalfOf: string | null+ desktopUserId: string | null+ authoritySource: string | null+ op: string+ outcome: string+ recordType: string | null+ mutationOutcome: string | null+ requestId: string | null+ gfsUri: string | null+}++export class GfsDesktopOperatorJourney {+ readonly runId = requireGfsOperatorRunId()+ readonly runTag = createHash('sha256').update(this.runId).digest('hex').slice(0, 10)+ readonly operatorUsername = `gfsop-${this.runTag}`+ readonly operatorEmail = `e2e-gfs-operator-${this.runTag}@example.invalid`+ readonly operatorPassword = `Gfs!${randomBytes(24).toString('base64url')}`+ readonly ordinaryEmail = `e2e-gfs-unlinked-${this.runTag}@example.invalid`+ readonly ordinaryName = `GFS Unlinked ${this.runTag}`+ readonly ordinaryPassword = `Gfs!${randomBytes(24).toString('base64url')}`+ readonly names = {+ crudFolder: `e2e-gfs-op-${this.runTag}-crud`,+ renamedFolder: `e2e-gfs-op-${this.runTag}-renamed`,+ rootFile: `e2e-gfs-op-${this.runTag}-root.md`,+ nestedFile: `e2e-gfs-op-${this.runTag}-nested.md`,+ renamedFile: `e2e-gfs-op-${this.runTag}-updated.md`,+ grantFolder: `e2e-gfs-op-${this.runTag}-grant`,+ shareFolder: `e2e-gfs-op-${this.runTag}-share`,+ ordinaryFolder: `e2e-gfs-op-${this.runTag}-ordinary`,+ deniedFolder: `e2e-gfs-op-${this.runTag}-denied`,+ auditDeniedFolder: `e2e-gfs-op-${this.runTag}-audit-denied`,+ }++ readonly controlUiUrl = configuredUrl('CONTROL_UI_BASE_URL', [+ process.env.CONTROL_UI_BASE_URL,+ process.env.CONTROL_UI_URL,+ ])+ readonly controlApiUrl = configuredUrl('CONTROL_API_BASE_URL', [+ process.env.CONTROL_API_BASE_URL,+ process.env.CONTROL_API_URL,+ process.env.E2E_CONTROL_API_URL,+ ])+ readonly externalRestUrl = configuredUrl('EXTERNAL_REST_API_BASE_URL', [+ process.env.EXTERNAL_REST_API_BASE_URL,+ process.env.EXTERNAL_REST_API_URL,+ process.env.E2E_EXTERNAL_REST_API_URL,+ ])+ readonly rpcProxyUrl = configuredUrl('RPC_PROXY_BASE_URL', [+ process.env.RPC_PROXY_BASE_URL,+ process.env.RPC_PROXY_URL,+ process.env.E2E_RPC_PROXY_URL,+ ])++ controlContext: BrowserContext | null = null+ controlPage: Page | null = null+ operatorApp: ElectronApplication | null = null+ operatorPage: Page | null = null+ operatorContext: BrowserContext | null = null+ operatorUserDataDir: string | null = null+ operatorVideoDir: string | null = null+ operatorLink: OperatorLinkRow | null = null+ ordinaryUserId: string | null = null+ ordinaryTeamId: string | null = null+ rootResourceId: string | null = null+ resources = new Map<string, GfsResourceRow>()+ successfulCreateAuditFloor = 0+ deniedAuditFloor = 0++ private activeTestInfo: TestInfo | null = null+ private operatorTraceActive = false+ private controlTraceActive = false+ private readonly liveDesktopPages = new Set<Page>()++ constructor(+ private readonly browser: Browser,+ private readonly workerInfo: WorkerInfo+ ) {}++ async start(): Promise<void> {+ this.controlContext = await this.browser.newContext({ baseURL: this.controlUiUrl })+ this.controlPage = await this.controlContext.newPage()+ }++ async beginTest(testInfo: TestInfo): Promise<void> {+ this.activeTestInfo = testInfo+ if (this.controlContext) {+ await this.controlContext.tracing.start({ screenshots: true, snapshots: true, sources: true })+ this.controlTraceActive = true+ }+ if (this.operatorContext) {+ await this.operatorContext.tracing.start({+ screenshots: true,+ snapshots: true,+ sources: true,+ })+ this.operatorTraceActive = true+ }+ }++ async endTest(testInfo: TestInfo): Promise<void> {+ const failed = testInfo.status !== testInfo.expectedStatus+ const traceName = safeTraceName(testInfo.title)+ if (failed) {+ for (const [index, page] of [...this.liveDesktopPages].entries()) {+ if (page.isClosed()) continue+ const screenshotPath = testInfo.outputPath(`desktop-${index + 1}.png`)+ await page.screenshot({ path: screenshotPath, fullPage: true }).catch(() => undefined)+ if (fs.existsSync(screenshotPath)) {+ await testInfo.attach(`desktop-${index + 1}`, {+ path: screenshotPath,+ contentType: 'image/png',+ })+ }+ }+ if (this.controlPage && !this.controlPage.isClosed()) {+ const screenshotPath = testInfo.outputPath('control-ui.png')+ await this.controlPage+ .screenshot({ path: screenshotPath, fullPage: true })+ .catch(() => undefined)+ if (fs.existsSync(screenshotPath)) {+ await testInfo.attach('control-ui', { path: screenshotPath, contentType: 'image/png' })+ }+ }+ }+ if (this.operatorTraceActive && this.operatorContext) {+ const tracePath = testInfo.outputPath(`${traceName}-electron-trace.zip`)+ await this.operatorContext.tracing.stop({ path: failed ? tracePath : undefined })+ this.operatorTraceActive = false+ if (failed && fs.existsSync(tracePath)) {+ await testInfo.attach('electron-trace', { path: tracePath, contentType: 'application/zip' })+ }+ }+ if (this.controlTraceActive && this.controlContext) {+ const tracePath = testInfo.outputPath(`${traceName}-control-trace.zip`)+ await this.controlContext.tracing.stop({ path: failed ? tracePath : undefined })+ this.controlTraceActive = false+ if (failed && fs.existsSync(tracePath)) {+ await testInfo.attach('control-ui-trace', {+ path: tracePath,+ contentType: 'application/zip',+ })+ }+ }+ this.activeTestInfo = null+ }++ async finish(): Promise<void> {+ const cleanupErrors: unknown[] = []+ for (const name of new Set([+ this.names.crudFolder,+ this.names.renamedFolder,+ this.names.rootFile,+ this.names.grantFolder,+ this.names.shareFolder,+ this.names.ordinaryFolder,+ this.names.deniedFolder,+ this.names.auditDeniedFolder,+ ])) {+ try {+ cleanupGfsFixture(name)+ } catch (error) {+ cleanupErrors.push(error)+ }+ }+ for (const app of [this.operatorApp]) {+ await app?.close().catch(error => cleanupErrors.push(error))+ }+ await this.controlContext?.close().catch(error => cleanupErrors.push(error))+ if (this.ordinaryUserId) {+ try {+ runControlPostgresSql(`+ DELETE FROM users+ WHERE id = ${sqlLiteral(this.ordinaryUserId)}::uuid+ AND email = ${sqlLiteral(this.ordinaryEmail)}+ AND email LIKE 'e2e-gfs-unlinked-%@example.invalid';+ `)+ } catch (error) {+ cleanupErrors.push(error)+ }+ }+ if (this.operatorUserDataDir) {+ try {+ const resolved = path.resolve(this.operatorUserDataDir)+ const allowedRoot = path.resolve(this.workerInfo.project.outputDir)+ if (!resolved.startsWith(`${allowedRoot}${path.sep}`)) {+ throw new Error(`refusing to remove user data outside ${allowedRoot}`)+ }+ if (fs.existsSync(resolved)) fs.rmSync(resolved, { recursive: true })+ } catch (error) {+ cleanupErrors.push(error)+ }+ }+ if (cleanupErrors.length > 0) {+ throw new AggregateError(cleanupErrors, 'GFS operator E2E cleanup did not complete')+ }+ }++ async bootstrapInitialAdmin(): Promise<{ controlAdminId: string }> {+ const response = await fetch(`${this.controlApiUrl}/admin/auth/setup`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ email: this.operatorEmail,+ username: this.operatorUsername,+ password: this.operatorPassword,+ seedDesktopPassword: true,+ }),+ signal: AbortSignal.timeout(30_000),+ })+ const body = (await response.json().catch(() => ({}))) as {+ error?: string+ me?: { id?: string; email?: string; username?: string }+ }+ if (response.status === 409) {+ throw new Error(+ '[GFS-OPERATOR-E2E] /admin/auth/setup returned 409. This one-shot journey requires a fresh, branch-owned profile whose bootstrap has not been consumed; no database reset or link insertion is performed by the suite.'+ )+ }+ if (response.status !== 200 || !UUID_RE.test(body.me?.id ?? '')) {+ throw new Error(+ `[GFS-OPERATOR-E2E] /admin/auth/setup returned HTTP ${response.status}: ${body.error ?? JSON.stringify(body)}`+ )+ }+ expect(body.me).toMatchObject({+ email: this.operatorEmail,+ username: this.operatorUsername,+ })+ return { controlAdminId: body.me!.id! }+ }++ readOperatorLink(): OperatorLinkRow | null {+ const row = firstDataLine(+ runControlPostgresSql(`+ SELECT user_id::text, control_admin_id::text, source+ FROM gfs_desktop_operator_links+ WHERE control_admin_id IN (+ SELECT id FROM control_admin_users WHERE lower(email) = lower(${sqlLiteral(this.operatorEmail)})+ )+ LIMIT 1;+ `)+ )+ if (!row) return null+ const [desktopUserId, controlAdminId, source] = splitSqlRow(row)+ if (!UUID_RE.test(desktopUserId) || !UUID_RE.test(controlAdminId)) {+ throw new Error(`[GFS-OPERATOR-E2E] malformed operator link row: ${row}`)+ }+ return { desktopUserId, controlAdminId, source }+ }++ operatorLinkCount(): number {+ if (!this.operatorLink) throw new Error('operator link is not initialized')+ return Number(+ firstDataLine(+ runControlPostgresSql(`+ SELECT count(*)::text FROM gfs_desktop_operator_links+ WHERE user_id = ${sqlLiteral(this.operatorLink?.desktopUserId ?? '')}::uuid+ AND control_admin_id = ${sqlLiteral(this.operatorLink?.controlAdminId ?? '')}::uuid;+ `)+ )+ )+ }++ operatorSubjectGrantCount(): number {+ if (!this.operatorLink) throw new Error('operator link is not initialized')+ return Number(+ firstDataLine(+ runControlPostgresSql(`+ SELECT count(*)::text+ FROM gfs_grants+ WHERE (subject_type = 'user' AND subject_id = ${sqlLiteral(this.operatorLink.desktopUserId)})+ OR (subject_type = 'operator' AND subject_id = '')+ OR subject_id = ${sqlLiteral(this.operatorLink.controlAdminId)};+ `)+ )+ )+ }++ createOrdinaryUserFixture(): { userId: string; teamId: string } {+ if (!this.operatorLink) throw new Error('operator link must exist before ordinary-user setup')+ const hash = bcryptHash(this.ordinaryPassword)+ const row = firstDataLine(+ runControlPostgresSql(`+ WITH operator_team AS (+ SELECT tm.team_id+ FROM team_members tm+ WHERE tm.user_id = ${sqlLiteral(this.operatorLink.desktopUserId)}::uuid+ AND tm.status = 'active'+ AND tm.role = 'admin'+ ORDER BY tm.created_at ASC+ LIMIT 1+ ), ordinary_user AS (+ INSERT INTO users(email, name, password_hash, password_set_at)+ VALUES(${sqlLiteral(this.ordinaryEmail)}, ${sqlLiteral(this.ordinaryName)}, ${sqlLiteral(hash)}, now())+ ON CONFLICT (email) DO UPDATE+ SET name = EXCLUDED.name,+ password_hash = EXCLUDED.password_hash,+ password_set_at = now(),+ updated_at = now()+ RETURNING id+ ), ordinary_profile AS (+ INSERT INTO profiles(user_id, display_name)+ SELECT id, ${sqlLiteral(this.ordinaryName)} FROM ordinary_user+ ON CONFLICT (user_id) DO UPDATE+ SET display_name = EXCLUDED.display_name, updated_at = now()+ RETURNING user_id+ ), membership AS (+ INSERT INTO team_members(team_id, user_id, role, status)+ SELECT operator_team.team_id, ordinary_user.id, 'member', 'active'+ FROM operator_team CROSS JOIN ordinary_user+ ON CONFLICT (team_id, user_id) DO UPDATE+ SET role = 'member', status = 'active', updated_at = now()+ RETURNING team_id, user_id+ )+ SELECT membership.user_id::text, membership.team_id::text+ FROM membership JOIN ordinary_profile ON ordinary_profile.user_id = membership.user_id;+ `)+ )+ const [userId, teamId] = splitSqlRow(row)+ if (!UUID_RE.test(userId) || !UUID_RE.test(teamId)) {+ throw new Error(`[GFS-OPERATOR-E2E] ordinary fixture could not be created: ${row}`)+ }+ const linkCount = Number(+ firstDataLine(+ runControlPostgresSql(+ `SELECT count(*)::text FROM gfs_desktop_operator_links WHERE user_id = ${sqlLiteral(userId)}::uuid;`+ )+ )+ )+ if (linkCount !== 0) throw new Error('ordinary fixture unexpectedly has an operator link')+ this.ordinaryUserId = userId+ this.ordinaryTeamId = teamId+ return { userId, teamId }+ }++ readRootResourceId(): string {+ const root = firstDataLine(+ runControlPostgresSql(+ `SELECT resource_id::text FROM gfs_resources WHERE drive = 'main' AND parent_resource_id IS NULL AND deleted_at IS NULL LIMIT 1;`+ )+ )+ if (!UUID_RE.test(root)) throw new Error('[GFS-OPERATOR-E2E] GFS drive root is not seeded')+ this.rootResourceId = root+ return root+ }++ readResource(parentResourceId: string, name: string): GfsResourceRow | null {+ if (!UUID_RE.test(parentResourceId))+ throw new Error(`invalid parent resource id ${parentResourceId}`)+ const row = firstDataLine(+ runControlPostgresSql(`+ SELECT resource_id::text, name, kind, bytes::text, version::text,+ (deleted_at IS NOT NULL)::text+ FROM gfs_resources+ WHERE drive = 'main'+ AND parent_resource_id = ${sqlLiteral(parentResourceId)}::uuid+ AND name = ${sqlLiteral(name)}+ ORDER BY updated_at DESC+ LIMIT 1;+ `)+ )+ if (!row) return null+ const [resourceId, persistedName, kind, bytes, version, deleted] = splitSqlRow(row)+ if (!UUID_RE.test(resourceId)) throw new Error(`malformed GFS resource row: ${row}`)+ return {+ resourceId,+ name: persistedName,+ kind: kind === 'directory' ? 'directory' : 'file',+ bytes: Number(bytes),+ version: Number(version),+ deleted: deleted === 't' || deleted === 'true',+ }+ }++ seedOrdinaryReadGrant(resourceId: string): string {+ if (!this.ordinaryUserId || !UUID_RE.test(resourceId))+ throw new Error('unsafe ordinary grant fixture')+ const grantId = firstDataLine(+ runControlPostgresSql(`+ INSERT INTO gfs_grants(+ drive, resource_id, subject_type, subject_id, permissions, inherit, granted_by+ ) VALUES(+ 'main', ${sqlLiteral(resourceId)}::uuid, 'user', ${sqlLiteral(this.ordinaryUserId)},+ ARRAY['read']::text[], false, 'e2e:ordinary-regression-precondition'+ )+ ON CONFLICT (drive, resource_id, subject_type, subject_id)+ DO UPDATE SET permissions = EXCLUDED.permissions, inherit = false,+ granted_by = EXCLUDED.granted_by, updated_at = now()+ RETURNING id::text;+ `)+ )+ if (!UUID_RE.test(grantId)) throw new Error('ordinary read-grant fixture was not persisted')+ return grantId+ }++ removeFixtureGrant(grantId: string): void {+ if (!UUID_RE.test(grantId)) throw new Error(`unsafe fixture grant id ${grantId}`)+ runControlPostgresSql(`+ DELETE FROM gfs_grants+ WHERE id = ${sqlLiteral(grantId)}::uuid+ AND granted_by = 'e2e:ordinary-regression-precondition';+ `)+ }++ findGrant(resourceId: string): { id: string; grantedBy: string } | null {+ if (!this.ordinaryUserId) return null+ const row = firstDataLine(+ runControlPostgresSql(`+ SELECT id::text, granted_by+ FROM gfs_grants+ WHERE resource_id = ${sqlLiteral(resourceId)}::uuid+ AND subject_type = 'user'+ AND subject_id = ${sqlLiteral(this.ordinaryUserId)}+ LIMIT 1;+ `)+ )+ if (!row) return null+ const [id, grantedBy] = splitSqlRow(row)+ if (!UUID_RE.test(id)) throw new Error(`malformed grant row: ${row}`)+ return { id, grantedBy }+ }++ findShare(resourceId: string): { id: string; createdBy: string } | null {+ if (!this.ordinaryUserId) return null+ const row = firstDataLine(+ runControlPostgresSql(`+ SELECT id::text, created_by+ FROM gfs_shares+ WHERE resource_id = ${sqlLiteral(resourceId)}::uuid+ AND subject_type = 'user'+ AND subject_id = ${sqlLiteral(this.ordinaryUserId)}+ LIMIT 1;+ `)+ )+ if (!row) return null+ const [id, createdBy] = splitSqlRow(row)+ if (!UUID_RE.test(id)) throw new Error(`malformed share row: ${row}`)+ return { id, createdBy }+ }++ auditFloor(): number {+ return Number(+ firstDataLine(+ runControlPostgresSql(`SELECT coalesce(max(sequence_no), 0)::text FROM gfs_audit;`)+ )+ )+ }++ auditRowsAfter(sequenceNo: number, desktopUserId: string): GfsAuditRow[] {+ const output = runControlPostgresSql(`+ SELECT jsonb_build_object(+ 'sequenceNo', sequence_no,+ 'subject', subject,+ 'actorOnBehalfOf', actor_on_behalf_of,+ 'desktopUserId', desktop_user_id,+ 'authoritySource', authority_source,+ 'op', op,+ 'outcome', outcome,+ 'recordType', record_type,+ 'mutationOutcome', mutation_outcome,+ 'requestId', request_id,+ 'gfsUri', gfs_uri+ )::text+ FROM gfs_audit+ WHERE sequence_no > ${Number(sequenceNo)}+ AND desktop_user_id = ${sqlLiteral(desktopUserId)}::uuid+ ORDER BY sequence_no ASC;+ `)+ return output+ .split('\n')+ .map(line => line.trim())+ .filter(line => line.startsWith('{') && line.endsWith('}'))+ .map(line => JSON.parse(line) as GfsAuditRow)+ }++ readUnlinkLifecycleEvent(): { operatorSub: string; targetRef: string; detailRef: string } | null {+ if (!this.operatorLink) return null+ const targetRef = `gfs_desktop_operator_link:${this.operatorLink.desktopUserId}:${this.operatorLink.controlAdminId}`+ const row = firstDataLine(+ runControlPostgresSql(`+ SELECT operator_sub, target_ref, payload_metadata->>'detail_ref'+ FROM administrative_events+ WHERE action = 'permission_revoke'+ AND target_type = 'permission'+ AND target_ref = ${sqlLiteral(targetRef)}+ AND payload_metadata->>'status' = 'unlinked'+ ORDER BY occurred_at DESC+ LIMIT 1;+ `)+ )+ if (!row) return null+ const [operatorSub, persistedTargetRef, detailRef] = splitSqlRow(row)+ return { operatorSub, targetRef: persistedTargetRef, detailRef }+ }++ async loginControlUi(): Promise<Page> {+ const page = this.requiredControlPage()+ await page.goto('/')+ await expect(page.getByLabel('Username or email')).toBeVisible({ timeout: 20_000 })+ await page.getByLabel('Username or email').fill(this.operatorEmail)+ await page.getByLabel(/password/i).fill(this.operatorPassword)+ await page.getByRole('button', { name: 'Sign in', exact: true }).click()+ await expect(page.getByRole('navigation', { name: 'Main sections' })).toBeVisible({+ timeout: 30_000,+ })+ const remindLater = page.getByRole('button', { name: 'Remind me later' })+ if ((await remindLater.count()) > 0) await remindLater.click()+ return page+ }++ async openControlAdmins(): Promise<Page> {+ const page = this.requiredControlPage()+ await page.getByRole('link', { name: 'Users & Teams', exact: true }).click()+ await expect(page).toHaveURL(/\/users-and-teams\/users(?:\?|$)/, { timeout: 20_000 })+ await page.getByRole('tab', { name: /^Admins(?: \(\d+\))?$/ }).click()+ await expect(page).toHaveURL(/\/users-and-teams\/admins(?:\?|$)/, { timeout: 20_000 })+ return page+ }++ async launchOperatorDesktop(): Promise<Page> {+ if (this.operatorApp) throw new Error('operator Electron process already launched')+ const outputRoot = this.workerInfo.project.outputDir+ this.operatorUserDataDir = path.join(outputRoot, `gfs-operator-user-data-${this.runTag}`)+ this.operatorVideoDir = path.join(outputRoot, `gfs-operator-video-${this.runTag}`)+ fs.mkdirSync(this.operatorUserDataDir, { recursive: true })+ fs.mkdirSync(this.operatorVideoDir, { recursive: true })+ this.operatorApp = await electron.launch({+ args: [`--user-data-dir=${this.operatorUserDataDir}`, MAIN_ENTRY],+ env: {+ ...process.env,+ EVENFIRE_RENDERER_URL: '',+ ELECTRON_RENDERER_URL: '',+ EXTERNAL_REST_API_BASE_URL: this.externalRestUrl,+ RPC_PROXY_BASE_URL: this.rpcProxyUrl,+ CLERUM_DESKTOP_CONFIG_PATH: path.join(this.operatorUserDataDir, 'runtime-config.json'),+ },+ recordVideo: { dir: this.operatorVideoDir, size: { width: 1280, height: 720 } },+ })+ this.operatorContext = this.operatorApp.context()+ if (this.activeTestInfo && !this.operatorTraceActive) {+ await this.operatorContext.tracing.start({+ screenshots: true,+ snapshots: true,+ sources: true,+ })+ this.operatorTraceActive = true+ }+ this.operatorPage = await this.operatorApp.firstWindow()+ this.liveDesktopPages.add(this.operatorPage)+ await this.operatorPage.waitForLoadState('domcontentloaded')+ await this.loginDesktop(this.operatorPage, this.operatorEmail, this.operatorPassword)+ return this.operatorPage+ }++ async launchOrdinaryDesktop(testInfo: TestInfo): Promise<{+ app: ElectronApplication+ page: Page+ close(): Promise<void>+ }> {+ const userDataDir = testInfo.outputPath(`ordinary-user-data-${this.runTag}`)+ const videoDir = testInfo.outputPath(`ordinary-video-${this.runTag}`)+ fs.mkdirSync(userDataDir, { recursive: true })+ fs.mkdirSync(videoDir, { recursive: true })+ const app = await electron.launch({+ args: [`--user-data-dir=${userDataDir}`, MAIN_ENTRY],+ env: {+ ...process.env,+ EVENFIRE_RENDERER_URL: '',+ ELECTRON_RENDERER_URL: '',+ EXTERNAL_REST_API_BASE_URL: this.externalRestUrl,+ RPC_PROXY_BASE_URL: this.rpcProxyUrl,+ CLERUM_DESKTOP_CONFIG_PATH: path.join(userDataDir, 'runtime-config.json'),+ },+ recordVideo: { dir: videoDir, size: { width: 1280, height: 720 } },+ })+ const page = await app.firstWindow()+ this.liveDesktopPages.add(page)+ await page.waitForLoadState('domcontentloaded')+ await this.loginDesktop(page, this.ordinaryEmail, this.ordinaryPassword)+ return {+ app,+ page,+ close: async () => {+ this.liveDesktopPages.delete(page)+ await app.close()+ const resolved = path.resolve(userDataDir)+ const allowedRoot = path.resolve(testInfo.outputDir)+ if (resolved.startsWith(`${allowedRoot}${path.sep}`)) {+ if (fs.existsSync(resolved)) fs.rmSync(resolved, { recursive: true })+ }+ },+ }+ }++ async loginDesktop(page: Page, email: string, password: string): Promise<void> {+ const emailInput = page.locator('#email-input')+ const passwordInput = page.locator('#password-input')+ await expect(emailInput).toBeVisible({ timeout: 30_000 })+ await expect(passwordInput).toBeVisible()+ await emailInput.fill(email)+ await passwordInput.fill(password)+ await page.getByRole('button', { name: /^Sign in$/ }).click()+ await expect(page.getByTestId('nav-settings-menu')).toBeVisible({ timeout: 45_000 })+ }++ async openFiles(page: Page): Promise<void> {+ await openResourcesNavItem(page, 'nav-files')+ await expect(page.getByRole('heading', { name: 'Files', exact: true })).toBeVisible({+ timeout: 30_000,+ })+ await expect(page.getByRole('region', { name: 'Global File System browser' })).toBeVisible()+ }++ private requiredControlPage(): Page {+ if (!this.controlPage) throw new Error('Control UI page has not been initialized')+ return this.controlPage+ }+}++type GfsDesktopOperatorTestFixtures = {+ captureGfsOperatorFailureEvidence: void+}++type GfsDesktopOperatorWorkerFixtures = {+ operatorJourney: GfsDesktopOperatorJourney+}++export const test = base.extend<GfsDesktopOperatorTestFixtures, GfsDesktopOperatorWorkerFixtures>({+ operatorJourney: [+ async ({ browser }, use, workerInfo) => {+ const journey = new GfsDesktopOperatorJourney(browser, workerInfo)+ await journey.start()+ try {+ await use(journey)+ } finally {+ await journey.finish()+ }+ },+ { scope: 'worker' },+ ],+ captureGfsOperatorFailureEvidence: [+ async ({ operatorJourney }, use, testInfo) => {+ await operatorJourney.beginTest(testInfo)+ try {+ await use()+ } finally {+ await operatorJourney.endTest(testInfo)+ }+ },+ { auto: true },+ ],+})++export { expect }diff --git a/desktop-app/test/e2e-playwright/playwright.gfs-desktop-operator.config.ts b/desktop-app/test/e2e-playwright/playwright.gfs-desktop-operator.config.tsnew file mode 100644index 000000000..43288027b--- /dev/null+++ b/desktop-app/test/e2e-playwright/playwright.gfs-desktop-operator.config.ts@@ -0,0 +1,34 @@+import { defineConfig } from '@playwright/test'+import path from 'node:path'+import {+ gfsOperatorEvidenceDirectory,+ requireGfsOperatorRunId,+} from './gfsDesktopOperatorParityContract'+import baseConfig from './playwright.config'++const runId = requireGfsOperatorRunId()+const evidenceDirectory = gfsOperatorEvidenceDirectory(runId)++export default defineConfig({+ ...baseConfig,+ testDir: __dirname,+ testMatch: 'gfs-desktop-operator-parity.test.ts',+ timeout: 240_000,+ retries: 0,+ workers: 1,+ fullyParallel: false,+ forbidOnly: true,+ globalSetup: path.resolve(__dirname, 'gfs-desktop-operator-parity.global-setup.ts'),+ outputDir: path.join(evidenceDirectory, 'test-results'),+ reporter: [+ ['list'],+ [path.resolve(__dirname, 'gfs-desktop-operator-parity.reporter.ts')],+ ['html', { open: 'never', outputFolder: path.join(evidenceDirectory, 'playwright-report') }],+ ],+ use: {+ ...baseConfig.use,+ screenshot: 'only-on-failure',+ trace: 'retain-on-failure',+ video: 'retain-on-failure',+ },+})diff --git a/desktop-app/test/gfsDesktopOperatorParityRunner.test.ts b/desktop-app/test/gfsDesktopOperatorParityRunner.test.tsnew file mode 100644index 000000000..c384dd842--- /dev/null+++ b/desktop-app/test/gfsDesktopOperatorParityRunner.test.ts@@ -0,0 +1,82 @@+import { describe, expect, it } from 'vitest'+import {+ GFS_OPERATOR_REQUIRED_SCENARIOS,+ type GfsOperatorScenarioResult,+ evaluateGfsOperatorScenarioResults,+ requireGfsOperatorRunId,+ scenarioIdFromTitle,+} from './e2e-playwright/gfsDesktopOperatorParityContract'++function passedResults(): GfsOperatorScenarioResult[] {+ return GFS_OPERATOR_REQUIRED_SCENARIOS.map(id => ({ id, status: 'passed', title: id }))+}++describe('GFS Desktop operator Playwright gate', () => {+ it('requires an explicit safe run id so evidence from two executions cannot overwrite', () => {+ expect(() => requireGfsOperatorRunId(undefined)).toThrow(/E2E_GFS_OPERATOR_RUN_ID is required/)+ expect(() => requireGfsOperatorRunId('../escape')).toThrow(/must match/)+ expect(() => requireGfsOperatorRunId('run one')).toThrow(/must match/)+ expect(requireGfsOperatorRunId('run_1-fresh')).toBe('run_1-fresh')+ })++ it('recognizes only one exact required scenario prefix', () => {+ expect(scenarioIdFromTitle('@gfs-operator/setup-linked-operator visible login')).toBe(+ '@gfs-operator/setup-linked-operator'+ )+ expect(scenarioIdFromTitle('setup-linked-operator')).toBeNull()+ })++ it('passes only when all six required scenarios pass once with runtime evidence', () => {+ expect(evaluateGfsOperatorScenarioResults(passedResults(), true)).toMatchObject({+ ok: true,+ required: 6,+ observed: 6,+ passed: 6,+ failed: 0,+ skipped: 0,+ errors: [],+ })+ })++ it('fails loudly when zero required scenarios execute', () => {+ const verdict = evaluateGfsOperatorScenarioResults([], true)+ expect(verdict.ok).toBe(false)+ expect(verdict.errors).toContain('zero required scenarios executed')+ for (const id of GFS_OPERATOR_REQUIRED_SCENARIOS) {+ expect(verdict.errors).toContain(`required scenario missing: ${id}`)+ }+ })++ it('fails loudly on a skipped required scenario', () => {+ const results = passedResults()+ results[2] = { ...results[2]!, status: 'skipped' }+ const verdict = evaluateGfsOperatorScenarioResults(results, true)+ expect(verdict.ok).toBe(false)+ expect(verdict.skipped).toBe(1)+ expect(verdict.errors).toContain(+ 'required scenario @gfs-operator/grant-share-lifecycle ended with status=skipped'+ )+ })++ it('fails loudly on missing, duplicate, failed, or interrupted scenarios', () => {+ const results = passedResults()+ results.splice(1, 1)+ results.push({ ...results[0]! })+ results[1] = { ...results[1]!, status: 'failed' }+ results[2] = { ...results[2]!, status: 'interrupted' }+ const verdict = evaluateGfsOperatorScenarioResults(results, true)+ expect(verdict.ok).toBe(false)+ expect(verdict.errors).toEqual(+ expect.arrayContaining([+ 'required scenario missing: @gfs-operator/operator-root-crud',+ 'required scenario executed 2 times: @gfs-operator/setup-linked-operator',+ ])+ )+ })++ it('fails when exact runtime/HEAD/artifact evidence is absent', () => {+ const verdict = evaluateGfsOperatorScenarioResults(passedResults(), false)+ expect(verdict.ok).toBe(false)+ expect(verdict.errors).toContain('runtime evidence is missing')+ })+})diff --git a/desktop-app/test/gfsUriHandler.test.ts b/desktop-app/test/gfsUriHandler.test.tsindex b9cb84ff4..566ddf801 100644--- a/desktop-app/test/gfsUriHandler.test.ts+++ b/desktop-app/test/gfsUriHandler.test.ts@@ -148,7 +148,7 @@ describe('GfsClient.listChildren', () => {})describe('GfsClient.listAccessible', () => {- it('lists readable GFS resources for the current user session', async () => {+ it('lists readable GFS resources for the current ordinary user session', async () => {const requestJson = vi.fn(async () => ({ok: true,data: {@@ -171,6 +171,38 @@ describe('GfsClient.listAccessible', () => {{ token: 'tok' })})++ it('preserves linked-operator root metadata and root-child shape', async () => {+ const rootResourceId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'+ const operatorChild = {+ resourceId: RID,+ rid: RID,+ gfsUri: `gfs://main/${RID}`,+ name: 'Projects',+ kind: 'directory' as const,+ path: '/Projects',+ version: 1,+ bytes: 0,+ }+ const requestJson = vi.fn(async () => ({+ ok: true,+ data: {+ items: [operatorChild],+ nextCursor: null,+ rootResourceId,+ view: 'operator',+ },+ })) as GfsTransport['requestJson']++ const out = await new GfsClient(transport({ requestJson })).listAccessible('tok')++ expect(out).toEqual({+ items: [operatorChild],+ nextCursor: null,+ rootResourceId,+ view: 'operator',+ })+ })})describe('GfsClient.affordances', () => {@@ -290,6 +322,7 @@ describe('GfsClient.grant', () => {})const GRANT_ID = '11111111-2222-3333-4444-555555555555'+const SHARE_ID = '66666666-7777-4888-8999-aaaaaaaaaaaa'const GRANT_ITEM = {id: GRANT_ID,@@ -373,6 +406,63 @@ describe('GfsClient.revokeGrant', () => {})})+const SHARE_ITEM = {+ id: SHARE_ID,+ drive: 'main',+ resourceId: RID,+ subject: { type: 'team', id: 'team-1' },+ permissions: ['read'],+ includeDescendants: true,+}++describe('GfsClient.listShares', () => {+ it('GETs the exact shares route and unwraps its direct items array', async () => {+ const requestJson = vi.fn(async () => ({ items: [SHARE_ITEM] })) as GfsTransport['requestJson']+ const out = await new GfsClient(transport({ requestJson })).listShares(+ { resourceId: RID, drive: 'main' },+ 'tok'+ )++ expect(out).toEqual([SHARE_ITEM])+ expect(requestJson).toHaveBeenCalledWith(+ 'GET',+ `https://api.example/api/v1/me/gfs/shares?drive=main&resourceId=${RID}`,+ { token: 'tok' }+ )+ })++ it('fails loud when the response carries no items array', async () => {+ const requestJson = vi.fn(async () => ({ ok: true })) as GfsTransport['requestJson']++ await expect(+ new GfsClient(transport({ requestJson })).listShares({ resourceId: RID }, 'tok')+ ).rejects.toThrow('unexpected gfs shares response: missing items array')+ })+})++describe('GfsClient.revokeShare', () => {+ it('DELETEs the exact share route with the bearer token', async () => {+ const requestJson = vi.fn(async () => ({ ok: true })) as GfsTransport['requestJson']++ await new GfsClient(transport({ requestJson })).revokeShare(SHARE_ID, 'tok')++ expect(requestJson).toHaveBeenCalledWith(+ 'DELETE',+ `https://api.example/api/v1/me/gfs/shares/${SHARE_ID}`,+ { token: 'tok' }+ )+ })++ it('rejects a non-UUID share id before any round-trip', async () => {+ const t = transport()++ await expect(new GfsClient(t).revokeShare('../shares', 'tok')).rejects.toThrow(+ /share id must be a UUID/+ )+ expect(t.requestJson).not.toHaveBeenCalled()+ })+})+describe('GfsClient.createShare', () => {it('POSTs ONE bulk read share for the subjects[] array', async () => {const requestJson = vi.fn(async () => ({ ok: true })) as GfsTransport['requestJson']diff --git a/desktop-app/test/ipc.test.ts b/desktop-app/test/ipc.test.tsindex 645029908..5d8e12aad 100644--- a/desktop-app/test/ipc.test.ts+++ b/desktop-app/test/ipc.test.ts@@ -115,6 +115,8 @@ describe('ipc host status stream handlers', () => {grantGfs: vi.fn(),listGfsGrants: vi.fn(),revokeGfsGrant: vi.fn(),+ listGfsShares: vi.fn(),+ revokeGfsShare: vi.fn(),listMyAgents: vi.fn(),createGfsShare: vi.fn(),setSandboxUiVisible: vi.fn(),@@ -490,6 +492,30 @@ describe('ipc host status stream handlers', () => {expect(service.revokeGfsGrant).toHaveBeenCalledWith('22222222-2222-2222-2222-222222222222')})+ it('routes GFS share list and revoke through trusted IPC with sanitized input', async () => {+ service.listGfsShares.mockResolvedValue([])+ service.revokeGfsShare.mockResolvedValue(undefined)+ const { event } = makeTrustedEvent()++ const listHandler = testState.handlers.get('gfs:listShares')+ await Promise.resolve(+ listHandler?.(event, {+ resourceId: ' 11111111-1111-1111-1111-111111111111 ',+ drive: ' main ',+ })+ )+ expect(service.listGfsShares).toHaveBeenCalledWith(+ '11111111-1111-1111-1111-111111111111',+ 'main'+ )++ const revokeHandler = testState.handlers.get('gfs:revokeShare')+ await Promise.resolve(+ revokeHandler?.(event, { shareId: ' 22222222-2222-4222-8222-222222222222 ' })+ )+ expect(service.revokeGfsShare).toHaveBeenCalledWith('22222222-2222-4222-8222-222222222222')+ })+it('lists my agents through the dedicated channel (not the cached catalog)', async () => {const agents = [{@@ -558,6 +584,26 @@ describe('ipc host status stream handlers', () => {expect(service.revokeGfsGrant).not.toHaveBeenCalled()})+ it.each([+ ['gfs:listShares', { resourceId: '11111111-1111-1111-1111-111111111111', drive: 'main' }],+ ['gfs:revokeShare', { shareId: '22222222-2222-4222-8222-222222222222' }],+ ])('rejects untrusted sender for %s', async (channel, payload) => {+ const handler = testState.handlers.get(channel)+ await expect(+ Promise.resolve(+ handler?.(+ {+ senderFrame: { url: 'https://evil.example.com' },+ sender: { id: 1, send: vi.fn(), once: vi.fn() },+ },+ payload+ )+ )+ ).rejects.toThrow('Untrusted IPC sender')+ expect(service.listGfsShares).not.toHaveBeenCalled()+ expect(service.revokeGfsShare).not.toHaveBeenCalled()+ })+it('rejects untrusted sender for my agents listing', async () => {const handler = testState.handlers.get('agents:listMine')await expect(diff --git a/desktop-app/ui/src/gfs/GfsGrantList/index.tsx b/desktop-app/ui/src/gfs/GfsGrantList/index.tsxindex 44721cf45..b6eac4279 100644--- a/desktop-app/ui/src/gfs/GfsGrantList/index.tsx+++ b/desktop-app/ui/src/gfs/GfsGrantList/index.tsx@@ -4,6 +4,7 @@ import type {GfsAgentSubjectOption,GfsDelegationSubjectOption,GfsGrantListItem,+ GfsShareListItem,} from '@/gfs/delegation.types'import type { GfsGrantListProps } from './types'@@ -16,7 +17,7 @@ import type { GfsGrantListProps } from './types'*/function subjectLabel(- subject: GfsGrantListItem['subject'],+ subject: GfsGrantListItem['subject'] | GfsShareListItem['subject'],agents: GfsAgentSubjectOption[],subjects: GfsDelegationSubjectOption[]): string {@@ -37,34 +38,54 @@ function subjectLabel(export function GfsGrantList({items,+ shares = [],loading = false,error = null,+ shareError = null,agents,subjects,onRevoke,+ onRevokeShare,revoking = false,+ revokingShare = false,}: GfsGrantListProps) {- if (error) {+ if (error || shareError) {return (- <StatusBanner tone={error.severity === 'quiet' ? 'info' : 'error'} text={error.message} />+ <div className="da-gfs-grant-list__errors" data-testid="gfs-access-list-error">+ {error ? (+ <StatusBanner tone={error.severity === 'quiet' ? 'info' : 'error'} text={error.message} />+ ) : null}+ {shareError ? (+ <StatusBanner+ tone={shareError.severity === 'quiet' ? 'info' : 'error'}+ text={shareError.message}+ />+ ) : null}+ </div>)}- if (loading && items.length === 0) {+ if (loading && items.length === 0 && shares.length === 0) {return <p className="muted">Loading access…</p>}- if (items.length === 0) {- return <p className="muted">No one has been granted access yet.</p>+ if (items.length === 0 && shares.length === 0) {+ return <p className="muted">No direct grants or shares yet.</p>}return (- <ul className="da-gfs-grant-list">+ <ul className="da-gfs-grant-list" aria-label="Resource access">{items.map(item => {const label = subjectLabel(item.subject, agents, subjects)return (- <li className="da-gfs-grant-list__row" key={item.id}>+ <li+ className="da-gfs-grant-list__row"+ data-testid={`gfs-access-row-grant-${item.id}`}+ key={`grant:${item.id}`}+ ><span className="da-gfs-grant-list__identity"><span className="da-gfs-grant-list__label">{label}</span>- <span className="da-gfs-grant-list__subject-type">{item.subject.type}</span>+ <span className="da-gfs-grant-list__subject-type">+ Direct grant · {item.subject.type}+ </span></span><span className="da-gfs-grant-list__meta"><span className="da-gfs-grant-list__chips">@@ -79,6 +100,7 @@ export function GfsGrantList({<Buttonaria-label={`Revoke access for ${label}`}color="danger"+ data-testid={`gfs-revoke-grant-${item.id}`}disabled={revoking}onClick={() => void onRevoke(item, label)}size="sm"@@ -90,6 +112,43 @@ export function GfsGrantList({</li>)})}+ {shares.map(item => {+ const label = subjectLabel(item.subject, agents, subjects)+ return (+ <li+ className="da-gfs-grant-list__row"+ data-testid={`gfs-access-row-share-${item.id}`}+ key={`share:${item.id}`}+ >+ <span className="da-gfs-grant-list__identity">+ <span className="da-gfs-grant-list__label">{label}</span>+ <span className="da-gfs-grant-list__subject-type">Share · {item.subject.type}</span>+ </span>+ <span className="da-gfs-grant-list__meta">+ <span className="da-gfs-grant-list__chips">+ {item.permissions.map(permission => (+ <Pill key={permission} size="xs" tone="neutral">+ {GFS_PERMISSION_LABELS[permission] ?? permission}+ </Pill>+ ))}+ </span>+ {item.includeDescendants ? <Badge tone="accent">Includes contents</Badge> : null}+ </span>+ <Button+ aria-label={`Revoke shared access for ${label}`}+ color="danger"+ data-testid={`gfs-revoke-share-${item.id}`}+ disabled={revokingShare || !onRevokeShare}+ onClick={() => void onRevokeShare?.(item, label)}+ size="sm"+ type="button"+ variant="outline"+ >+ Revoke+ </Button>+ </li>+ )+ })}</ul>)}diff --git a/desktop-app/ui/src/gfs/GfsGrantList/types.ts b/desktop-app/ui/src/gfs/GfsGrantList/types.tsindex 727e5faab..099234b1f 100644--- a/desktop-app/ui/src/gfs/GfsGrantList/types.ts+++ b/desktop-app/ui/src/gfs/GfsGrantList/types.ts@@ -3,20 +3,25 @@ import type {GfsAgentSubjectOption,GfsDelegationSubjectOption,GfsGrantListItem,+ GfsShareListItem,} from '@/gfs/delegation.types'export interface GfsGrantListProps {items: GfsGrantListItem[]+ shares?: GfsShareListItem[]loading?: boolean/*** Mapped list-load failure. Severity 'quiet' (manage_acl_required) renders an* informational banner instead of the list; 'error' renders an error banner.*/error?: GfsGrantErrorPresentation | null+ shareError?: GfsGrantErrorPresentation | null/** Label source for `host` subjects (the caller's own agents). */agents: GfsAgentSubjectOption[]/** Label source for `user`/`team` subjects (the visible team directory). */subjects: GfsDelegationSubjectOption[]onRevoke: (item: GfsGrantListItem, label: string) => void | Promise<void>+ onRevokeShare?: (item: GfsShareListItem, label: string) => void | Promise<void>revoking?: boolean+ revokingShare?: boolean}diff --git a/desktop-app/ui/src/gfs/__tests__/GfsGrantList.test.tsx b/desktop-app/ui/src/gfs/__tests__/GfsGrantList.test.tsxindex 141395364..c661f9c01 100644--- a/desktop-app/ui/src/gfs/__tests__/GfsGrantList.test.tsx+++ b/desktop-app/ui/src/gfs/__tests__/GfsGrantList.test.tsx@@ -2,7 +2,7 @@import { afterEach, describe, expect, it, vi } from 'vitest'import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'import { GfsGrantList } from '../GfsGrantList'-import type { GfsGrantListItem } from '../delegation.types'+import type { GfsGrantListItem, GfsShareListItem } from '../delegation.types'/*** "Who has access" list (Manage modal). Rows resolve host subjects to agent@@ -31,6 +31,18 @@ function grantItem(overrides: Partial<GfsGrantListItem>): GfsGrantListItem {}}+function shareItem(overrides: Partial<GfsShareListItem>): GfsShareListItem {+ return {+ id: 'share-1',+ drive: 'main',+ resourceId: 'res-1',+ subject: { type: 'team', id: 'team-1' },+ permissions: ['read'],+ includeDescendants: true,+ ...overrides,+ }+}+describe('GfsGrantList', () => {it('renders resolved subject labels, permission chips, and the inherit badge', () => {render(@@ -95,6 +107,32 @@ describe('GfsGrantList', () => {expect(onRevoke).toHaveBeenCalledWith(item, 'Chat LLM')})+ it('combines direct shares with grants and routes share revoke separately', () => {+ const onRevoke = vi.fn()+ const onRevokeShare = vi.fn()+ const share = shareItem({})+ render(+ <GfsGrantList+ agents={agents}+ items={[grantItem({})]}+ onRevoke={onRevoke}+ onRevokeShare={onRevokeShare}+ shares={[share]}+ subjects={subjects}+ />+ )++ const shareRow = screen.getByTestId('gfs-access-row-share-share-1')+ expect(within(shareRow).getByText('Share · team')).toBeTruthy()+ expect(within(shareRow).getByText('Includes contents')).toBeTruthy()+ fireEvent.click(+ within(shareRow).getByRole('button', { name: 'Revoke shared access for Core Team' })+ )++ expect(onRevokeShare).toHaveBeenCalledWith(share, 'Core Team')+ expect(onRevoke).not.toHaveBeenCalled()+ })+it('renders manage_acl_required as a quiet informational banner instead of the list', () => {render(<GfsGrantList@@ -134,6 +172,6 @@ describe('GfsGrantList', () => {it('renders an empty notice when nothing has been granted', () => {render(<GfsGrantList agents={agents} items={[]} onRevoke={vi.fn()} subjects={subjects} />)- expect(screen.getByText('No one has been granted access yet.')).toBeTruthy()+ expect(screen.getByText('No direct grants or shares yet.')).toBeTruthy()})})diff --git a/desktop-app/ui/src/gfs/delegation.types.ts b/desktop-app/ui/src/gfs/delegation.types.tsindex cf381bcdc..b7a608e9b 100644--- a/desktop-app/ui/src/gfs/delegation.types.ts+++ b/desktop-app/ui/src/gfs/delegation.types.ts@@ -52,3 +52,13 @@ export interface GfsGrantListItem {permissions: string[]inherit: boolean}++/** A direct URI-share row from `window.clerum.gfs.listShares()`. */+export interface GfsShareListItem {+ id: string+ drive: string+ resourceId: string+ subject: { type: string; id?: string }+ permissions: string[]+ includeDescendants: boolean+}diff --git a/desktop-app/ui/src/hooks/domain/__tests__/queryKeys.test.ts b/desktop-app/ui/src/hooks/domain/__tests__/queryKeys.test.tsindex 56d082a5c..1fa9d6bea 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/queryKeys.test.ts+++ b/desktop-app/ui/src/hooks/domain/__tests__/queryKeys.test.ts@@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest'import { desktopQueryKeys } from '../queryKeys'describe('desktopQueryKeys', () => {- it('scopes GFS child and affordance caches by authenticated session', () => {+ it('scopes GFS content and access-management caches by authenticated session', () => {const aliceScope = 'user-alice:team-red'const bobScope = 'user-bob:team-red'@@ -25,6 +25,25 @@ describe('desktopQueryKeys', () => {expect(desktopQueryKeys.gfsChildren(aliceScope, 'res-root', 'personal')).not.toEqual(desktopQueryKeys.gfsChildren(bobScope, 'res-root', 'personal'))+ expect(desktopQueryKeys.gfsGrants(aliceScope, 'res-root', 'personal')).toEqual([+ 'desktop-app',+ 'gfs',+ aliceScope,+ 'grants',+ 'personal',+ 'res-root',+ ])+ expect(desktopQueryKeys.gfsShares(aliceScope, 'res-root', 'personal')).toEqual([+ 'desktop-app',+ 'gfs',+ aliceScope,+ 'shares',+ 'personal',+ 'res-root',+ ])+ expect(desktopQueryKeys.gfsShares(aliceScope, 'res-root', 'personal')).not.toEqual(+ desktopQueryKeys.gfsShares(bobScope, 'res-root', 'personal')+ )})it('exposes a stable GFS root for logout cache invalidation', () => {diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsxindex f1bee87e7..862cf99c0 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx@@ -22,7 +22,14 @@ const userB = {teamName: 'Team B',}-function authValue(me: AuthContextValue['me']): AuthContextValue {+const userC = {+ ...userA,+ id: 'user-c',+ email: '[email protected]',+ name: 'User C',+}++function authValue(me: AuthContextValue['me'], envKey = 'env-a'): AuthContextValue {return {booting: false,busy: false,@@ -38,7 +45,15 @@ function authValue(me: AuthContextValue['me']): AuthContextValue {runtimeConfigSetupExternalRestApiBaseUrl: '',runtimeConfigSetupRpcProxyBaseUrl: '',authTransitioning: false,- runtimeConfigState: null,+ runtimeConfigState: {+ configured: true,+ isLocalhost: false,+ selectorVisible: false,+ activeOptionId: envKey,+ envKey,+ storagePath: `/tmp/${envKey}`,+ options: [],+ },runtimeConfigMissing: false,showRuntimeConfigSelector: false,dependencyHealth: null,@@ -70,6 +85,8 @@ function Probe() {<div data-testid="current-name">{ctrl.current?.name ?? 'none'}</div><div data-testid="current-version">{ctrl.current?.version ?? 'none'}</div><div data-testid="crumbs">{ctrl.crumbs.map(crumb => crumb.name).join(' / ')}</div>+ <div data-testid="view">{ctrl.view}</div>+ <div data-testid="operator-root">{ctrl.isOperatorRoot ? 'yes' : 'no'}</div><div data-testid="accessible-count">{ctrl.accessibleResources.length}</div><div data-testid="accessible-error">{ctrl.accessibleError ?? 'none'}</div><div data-testid="accessible-notice">{ctrl.accessibleNotice ?? 'none'}</div>@@ -90,6 +107,12 @@ function Probe() {<button type="button" onClick={() => void ctrl.refreshAffordances()}>refresh permissions</button>+ <button type="button" onClick={() => ctrl.reset()}>+ reset browser+ </button>+ <button type="button" onClick={() => void ctrl.createFolder('Root docs')}>+ create folder current+ </button><buttontype="button"onClick={() =>@@ -130,16 +153,26 @@ function Probe() {function Harness({ children }: { children: ReactNode }) {const [me, setMe] = useState<AuthContextValue['me']>(userA)+ const [envKey, setEnvKey] = useState('env-a')const [client] = useState(() => new QueryClient({ defaultOptions: { queries: { retry: false } } }))return (- <AuthContext.Provider value={authValue(me)}>+ <AuthContext.Provider value={authValue(me, envKey)}><QueryClientProvider client={client}>{children}<button type="button" onClick={() => setMe(userB)}>switch team</button>+ <button type="button" onClick={() => setMe(userC)}>+ switch user+ </button>+ <button type="button" onClick={() => setEnvKey('env-b')}>+ switch environment+ </button>+ <button type="button" onClick={() => setMe(null)}>+ sign out+ </button></QueryClientProvider></AuthContext.Provider>)@@ -151,24 +184,146 @@ describe('useGfsBrowserController', () => {vi.restoreAllMocks()})- it('resets visible GFS state when the authenticated session scope changes', async () => {+ it.each(['switch team', 'switch user', 'sign out'])(+ 'resets visible GFS state after %s changes the authenticated scope',+ async action => {+ Object.defineProperty(window, 'clerum', {+ configurable: true,+ value: {+ gfs: {+ listAccessible: vi.fn(async () => ({+ items: [],+ nextCursor: null,+ })),+ resolve: vi.fn(async () => ({+ resourceId: 'root',+ gfsUri: 'gfs://main/root',+ name: 'Root',+ kind: 'directory',+ })),+ listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),+ affordances: vi.fn(async () => ({+ held: [],+ canDelegate: false,+ grantableBits: [],+ canCreateShare: false,+ })),+ },+ },+ })++ render(<Probe />, { wrapper: Harness })++ await act(async () => {+ screen.getByRole('button', { name: 'open' }).click()+ })+ await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('root'))++ await act(async () => {+ screen.getByRole('button', { name: action }).click()+ })++ await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('none'))+ }+ )++ it('initializes the linked operator at the real root and uses it for root mutations', async () => {+ const rootResourceId = '11111111-1111-1111-1111-111111111111'+ const child = {+ resourceId: '22222222-2222-2222-2222-222222222222',+ rid: '22222222222222222222222222222222',+ gfsUri: 'gfs://main/22222222222222222222222222222222',+ drive: 'main',+ parentResourceId: rootResourceId,+ name: 'Projects',+ kind: 'directory' as const,+ path: '/Projects',+ version: 1,+ bytes: 0,+ sources: [],+ permissions: ['read', 'write'],+ coversDescendants: false,+ }+ const listChildren = vi.fn(async () => ({ items: [], nextCursor: null }))+ const createFolder = vi.fn(async () => child)Object.defineProperty(window, 'clerum', {configurable: true,value: {gfs: {listAccessible: vi.fn(async () => ({- items: [],+ items: [child],nextCursor: null,+ rootResourceId,+ view: 'operator' as const,})),- resolve: vi.fn(async () => ({- resourceId: 'root',- gfsUri: 'gfs://main/root',- name: 'Root',- kind: 'directory',+ resolve: vi.fn(),+ listChildren,+ affordances: vi.fn(async () => ({+ held: ['read', 'write', 'delete', 'manage_acl', 'share'],+ canDelegate: true,+ grantableBits: ['read', 'write', 'delete', 'manage_acl', 'share'],+ canCreateShare: true,})),+ createFolder,+ },+ },+ })++ render(<Probe />, { wrapper: Harness })++ await waitFor(() => expect(screen.getByTestId('current').textContent).toBe(rootResourceId))+ expect(screen.getByTestId('view').textContent).toBe('operator')+ expect(screen.getByTestId('operator-root').textContent).toBe('yes')+ expect(screen.getByTestId('crumbs').textContent).toBe('Global File System')+ expect(screen.getByTestId('accessible-count').textContent).toBe('1')+ expect(listChildren).not.toHaveBeenCalled()++ await act(async () => {+ screen.getByRole('button', { name: 'create folder current' }).click()+ })+ await waitFor(() =>+ expect(createFolder).toHaveBeenCalledWith(rootResourceId, 'Root docs', 'main')+ )++ await act(async () => {+ screen.getByRole('button', { name: 'open Projects' }).click()+ })+ await waitFor(() => expect(screen.getByTestId('current').textContent).toBe(child.resourceId))+ expect(screen.getByTestId('crumbs').textContent).toBe('Global File System / Projects')+ await waitFor(() =>+ expect(listChildren).toHaveBeenCalledWith(child.resourceId, 'main', undefined)+ )++ await act(async () => {+ screen.getByRole('button', { name: 'create folder current' }).click()+ })+ await waitFor(() =>+ expect(createFolder).toHaveBeenLastCalledWith(child.resourceId, 'Root docs', 'main')+ )++ await act(async () => {+ screen.getByRole('button', { name: 'reset browser' }).click()+ })+ await waitFor(() => expect(screen.getByTestId('current').textContent).toBe(rootResourceId))+ })++ it('replaces cached operator-root state when the environment changes', async () => {+ const roots = ['11111111-1111-1111-1111-111111111111', '22222222-2222-2222-2222-222222222222']+ let call = 0+ Object.defineProperty(window, 'clerum', {+ configurable: true,+ value: {+ gfs: {+ listAccessible: vi.fn(async () => ({+ items: [],+ nextCursor: null,+ rootResourceId: roots[Math.min(call++, roots.length - 1)],+ view: 'operator' as const,+ })),+ resolve: vi.fn(),listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),affordances: vi.fn(async () => ({- held: [],+ held: ['read'],canDelegate: false,grantableBits: [],canCreateShare: false,@@ -178,17 +333,92 @@ describe('useGfsBrowserController', () => {})render(<Probe />, { wrapper: Harness })+ await waitFor(() => expect(screen.getByTestId('current').textContent).toBe(roots[0]))await act(async () => {- screen.getByRole('button', { name: 'open' }).click()+ screen.getByRole('button', { name: 'switch environment' }).click()+ })++ await waitFor(() => expect(screen.getByTestId('current').textContent).toBe(roots[1]))+ expect(screen.getByTestId('crumbs').textContent).toBe('Global File System')+ })++ it('clears operator-root state when the next authenticated scope is an ordinary user', async () => {+ const rootResourceId = '11111111-1111-1111-1111-111111111111'+ const ordinaryResource = {+ resourceId: '33333333-3333-4333-8333-333333333333',+ rid: '33333333333343338333333333333333',+ gfsUri: 'gfs://main/33333333333343338333333333333333',+ drive: 'main',+ parentResourceId: null,+ name: 'Shared report.md',+ kind: 'file' as const,+ path: '/Shared report.md',+ version: 1,+ bytes: 12,+ sources: ['share'],+ permissions: ['read'],+ coversDescendants: false,+ }+ let call = 0+ Object.defineProperty(window, 'clerum', {+ configurable: true,+ value: {+ gfs: {+ listAccessible: vi.fn(async () =>+ call++ === 0+ ? { items: [], nextCursor: null, rootResourceId, view: 'operator' as const }+ : { items: [ordinaryResource], nextCursor: null }+ ),+ resolve: vi.fn(),+ listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),+ affordances: vi.fn(async () => ({+ held: ['read'],+ canDelegate: false,+ grantableBits: [],+ canCreateShare: false,+ })),+ },+ },})- await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('root'))++ render(<Probe />, { wrapper: Harness })+ await waitFor(() => expect(screen.getByTestId('operator-root').textContent).toBe('yes'))await act(async () => {screen.getByRole('button', { name: 'switch team' }).click()})- await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('none'))+ await waitFor(() => expect(screen.getByTestId('view').textContent).toBe('shared'))+ expect(screen.getByTestId('operator-root').textContent).toBe('no')+ expect(screen.getByTestId('current').textContent).toBe('none')+ expect(screen.getByTestId('crumbs').textContent).toBe('')+ expect(screen.getByTestId('accessible-count').textContent).toBe('1')+ })++ it('fails closed when operator mode omits a valid rootResourceId', async () => {+ Object.defineProperty(window, 'clerum', {+ configurable: true,+ value: {+ gfs: {+ listAccessible: vi.fn(async () => ({+ items: [],+ nextCursor: null,+ view: 'operator' as const,+ })),+ resolve: vi.fn(),+ listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),+ affordances: vi.fn(),+ },+ },+ })++ render(<Probe />, { wrapper: Harness })++ await waitFor(() =>+ expect(screen.getByTestId('accessible-error').textContent).toContain('operator_root_missing')+ )+ expect(screen.getByTestId('current').textContent).toBe('none')})it('refreshes cached affordances after permissions change outside Desktop', async () => {@@ -572,6 +802,29 @@ describe('useGfsBrowserController', () => {expect(screen.getByTestId('accessible-error').textContent).toBe('none')expect(screen.getByTestId('accessible-count').textContent).toBe('0')})++ it('keeps an unseeded drive distinct from the older-server 404 notice', async () => {+ Object.defineProperty(window, 'clerum', {+ configurable: true,+ value: {+ gfs: {+ listAccessible: vi.fn(async () => {+ throw new Error('404 Not Found: drive_not_seeded')+ }),+ resolve: vi.fn(),+ listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),+ affordances: vi.fn(),+ },+ },+ })++ render(<Probe />, { wrapper: Harness })++ await waitFor(() =>+ expect(screen.getByTestId('accessible-error').textContent).toContain('drive_not_seeded')+ )+ expect(screen.getByTestId('accessible-notice').textContent).toBe('none')+ })})// The grants listing is gated by the `grantsListEnabled` hook option (the Manage@@ -587,6 +840,7 @@ function ManageProbe() {<><div data-testid="current">{ctrl.current?.resourceId ?? 'none'}</div><div data-testid="grants-count">{ctrl.grants.length}</div>+ <div data-testid="shares-count">{ctrl.shares.length}</div><button type="button" onClick={() => void ctrl.openUri('gfs://main/root')}>open root</button>@@ -602,6 +856,9 @@ function ManageProbe() {<button type="button" onClick={() => void ctrl.revokeGrant('grant-42')}>revoke grant</button>+ <button type="button" onClick={() => void ctrl.revokeShare('share-42')}>+ revoke share+ </button><button type="button" onClick={() => void ctrl.grant(['user:bob'], ['read'], true)}>grant inherit true</button>@@ -635,6 +892,7 @@ describe('useGfsBrowserController — grants list / revoke / inherit (#826)', ()inherit: false,},])+ const listShares = vi.fn(async () => [])Object.defineProperty(window, 'clerum', {configurable: true,value: {@@ -649,6 +907,7 @@ describe('useGfsBrowserController — grants list / revoke / inherit (#826)', ()listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),affordances,listGrants,+ listShares,},},})@@ -663,17 +922,20 @@ describe('useGfsBrowserController — grants list / revoke / inherit (#826)', ()// fired by now — but Manage is closed, so the grants list must stay dormant.await waitFor(() => expect(affordances).toHaveBeenCalled())expect(listGrants).not.toHaveBeenCalled()+ expect(listShares).not.toHaveBeenCalled()await act(async () => {screen.getByRole('button', { name: 'open manage' }).click()})await waitFor(() => expect(listGrants).toHaveBeenCalledTimes(1))+ await waitFor(() => expect(listShares).toHaveBeenCalledTimes(1))expect(listGrants).toHaveBeenCalledWith('root', 'main')await waitFor(() => expect(screen.getByTestId('grants-count').textContent).toBe('1'))})it('refetches the grants list when refreshGrants runs', async () => {const listGrants = vi.fn(async () => [])+ const listShares = vi.fn(async () => [])Object.defineProperty(window, 'clerum', {configurable: true,value: {@@ -693,6 +955,7 @@ describe('useGfsBrowserController — grants list / revoke / inherit (#826)', ()canCreateShare: false,})),listGrants,+ listShares,},},})@@ -727,6 +990,7 @@ describe('useGfsBrowserController — grants list / revoke / inherit (#826)', ()inherit: false,},])+ const listShares = vi.fn(async () => [])Object.defineProperty(window, 'clerum', {configurable: true,value: {@@ -746,6 +1010,7 @@ describe('useGfsBrowserController — grants list / revoke / inherit (#826)', ()canCreateShare: false,})),listGrants,+ listShares,revokeGrant,},},@@ -771,6 +1036,63 @@ describe('useGfsBrowserController — grants list / revoke / inherit (#826)', ()await waitFor(() => expect(listGrants).toHaveBeenCalledTimes(2))})+ it('lists and revokes a share by id, then refetches only the share list', async () => {+ const listGrants = vi.fn(async () => [])+ const listShares = vi.fn(async () => [+ {+ id: 'share-42',+ drive: 'main',+ resourceId: 'root',+ subject: { type: 'team', id: 'qa' },+ permissions: ['read'],+ includeDescendants: true,+ },+ ])+ const revokeShare = vi.fn(async () => undefined)+ Object.defineProperty(window, 'clerum', {+ configurable: true,+ value: {+ gfs: {+ listAccessible: vi.fn(async () => ({ items: [], nextCursor: null })),+ resolve: vi.fn(async () => ({+ resourceId: 'root',+ gfsUri: 'gfs://main/root',+ name: 'Root',+ kind: 'directory',+ })),+ listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),+ affordances: vi.fn(async () => ({+ held: ['read', 'manage_acl', 'share'],+ canDelegate: true,+ grantableBits: ['read'],+ canCreateShare: true,+ })),+ listGrants,+ listShares,+ revokeShare,+ },+ },+ })++ render(<ManageProbe />, { wrapper: Harness })+ await act(async () => {+ screen.getByRole('button', { name: 'open root' }).click()+ })+ await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('root'))+ await act(async () => {+ screen.getByRole('button', { name: 'open manage' }).click()+ })+ await waitFor(() => expect(screen.getByTestId('shares-count').textContent).toBe('1'))++ await act(async () => {+ screen.getByRole('button', { name: 'revoke share' }).click()+ })++ await waitFor(() => expect(revokeShare).toHaveBeenCalledWith('share-42'))+ await waitFor(() => expect(listShares).toHaveBeenCalledTimes(2))+ expect(listGrants).toHaveBeenCalledTimes(1)+ })+it('forwards the inherit flag (true and false) to window.clerum.gfs.grant', async () => {const grant = vi.fn(async () => undefined)Object.defineProperty(window, 'clerum', {diff --git a/desktop-app/ui/src/hooks/domain/queryKeys.ts b/desktop-app/ui/src/hooks/domain/queryKeys.tsindex 88da02d27..80137d093 100644--- a/desktop-app/ui/src/hooks/domain/queryKeys.ts+++ b/desktop-app/ui/src/hooks/domain/queryKeys.ts@@ -22,6 +22,10 @@ export const desktopQueryKeys = {['desktop-app', 'gfs', sessionScope, 'children', drive, resourceId] as const,gfsAffordances: (sessionScope: string, resourceId: string, drive: string) =>['desktop-app', 'gfs', sessionScope, 'affordances', drive, resourceId] as const,+ gfsGrants: (sessionScope: string, resourceId: string, drive: string) =>+ ['desktop-app', 'gfs', sessionScope, 'grants', drive, resourceId] as const,+ gfsShares: (sessionScope: string, resourceId: string, drive: string) =>+ ['desktop-app', 'gfs', sessionScope, 'shares', drive, resourceId] as const,pluginGrants: ['desktop-app', 'plugin-sdk', 'grants'] as const,pluginActivity: (limit: number) =>['desktop-app', 'plugin-sdk', 'activity', String(limit)] as const,diff --git a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.tsindex 442fb210b..ce93d587a 100644--- a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts+++ b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts@@ -2,21 +2,21 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { useAuthContext } from '@contexts/AuthContext'import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'import { GFS_BREADCRUMB_MAX_DEPTH } from '@constants/gfsBrowser'-import type { GfsGrantListItem } from '@/gfs/delegation.types'+import type { GfsGrantListItem, GfsShareListItem } from '@/gfs/delegation.types'import { desktopQueryKeys } from './queryKeys'/*** P4-S07 — Desktop Global File System browser controller (user plane).** TanStack Query is the server-state source of truth (desktop-app/ui rule). The- * browse is access-driven: the user first sees explicit resources granted or- * shared with them, and can still open a `gfs://` URI manually. There is no- * full-drive tree on the user plane — listing the whole drive is an operator- * capability. Children are paginated with `useInfiniteQuery` so a large folder- * is never silently truncated.+ * browse is access-driven for ordinary users: they first see explicit resources+ * granted or shared with them, and can still open a `gfs://` URI manually. A+ * linked operator instead starts at the real drive root returned by discovery.+ * Children are paginated with `useInfiniteQuery` so a large folder is never+ * silently truncated.** Delegation (grant/share) and affordances flow through window.clerum.gfs, which- * reaches control-api `/external/gfs/*` on the existing Session-JWT plane.+ * reaches the `/api/v1/me/gfs/*` user plane with the existing Session JWT.* Enforcement (no-escalation) is always server-side; affordances only decide* which controls to SHOW.*/@@ -27,8 +27,8 @@ export interface GfsBrowserChild {resourceId: stringrid: stringgfsUri: string- drive: string- parentResourceId: string | null+ drive?: string+ parentResourceId?: string | nullname: stringkind: 'file' | 'directory'path: string | null@@ -37,9 +37,9 @@ export interface GfsBrowserChild {}interface GfsAccessibleResource extends GfsBrowserChild {- sources: string[]- permissions: string[]- coversDescendants: boolean+ sources?: string[]+ permissions?: string[]+ coversDescendants?: boolean}export interface GfsCrumb {@@ -49,6 +49,16 @@ export interface GfsCrumb {kind: 'file' | 'directory'version: numberbytes: number+ /** True only for the real drive root returned to a linked GFS operator. */+ isDriveRoot?: boolean+}++export type GfsBrowserView = 'operator' | 'shared'++export interface GfsBrowserFailure {+ kind: 'uninitialized' | 'unauthorized' | 'upstream'+ title: string+ message: string}export interface GfsBrowserAffordances {@@ -71,6 +81,7 @@ function toMessage(error: unknown): string {}function isResourceDiscoveryUnavailable(message: string): boolean {+ if (isUninitializedDriveError(message)) return falsereturn (message.includes('listAccessible is not a function') ||message.includes('gfs:listAccessible') ||@@ -78,6 +89,68 @@ function isResourceDiscoveryUnavailable(message: string): boolean {)}+function isUninitializedDriveError(message: string): boolean {+ const normalized = message.toLowerCase()+ return (+ normalized.includes('operator_root_missing') ||+ normalized.includes('gfs_drive_unseeded') ||+ normalized.includes('drive_not_seeded') ||+ normalized.includes('gfs_root_unseeded') ||+ normalized.includes('gfs_not_initialized') ||+ normalized.includes('not initialized') ||+ normalized.includes('unseeded')+ )+}++/** Stable user-facing state for root/folder read failures crossing Electron IPC. */+export function describeGfsBrowserFailure(message: string): GfsBrowserFailure {+ if (isUninitializedDriveError(message)) {+ return {+ kind: 'uninitialized',+ title: 'Global File System is not initialized',+ message: 'The drive exists in this environment, but its root is not ready yet.',+ }+ }+ const normalized = message.toLowerCase()+ if (+ /(^|\D)(401|403)(\D|$)/.test(normalized) ||+ normalized.includes('unauthorized') ||+ normalized.includes('forbidden') ||+ normalized.includes('not authenticated') ||+ normalized.includes('operator_link_inactive') ||+ normalized.includes('operator_link_invalid')+ ) {+ return {+ kind: 'unauthorized',+ title: 'File access is not authorized',+ message:+ 'Your current Desktop session cannot access this location. Sign in again or contact an administrator.',+ }+ }+ return {+ kind: 'upstream',+ title: 'Global File System is unavailable',+ message:+ 'The file service did not return a usable response. Try again when the service is available.',+ }+}++const RESOURCE_ID_RE =+ /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/++function rootCrumb(resourceId: string): GfsCrumb {+ const rid = resourceId.replace(/-/g, '').toLowerCase()+ return {+ resourceId,+ gfsUri: `gfs://${DRIVE}/${rid}`,+ name: 'Global File System',+ kind: 'directory',+ version: 0,+ bytes: 0,+ isDriveRoot: true,+ }+}+export function useGfsBrowserController(options: GfsBrowserControllerOptions = {}) {const { grantsListEnabled = false } = optionsconst queryClient = useQueryClient()@@ -106,7 +179,7 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {if (previous !== null) {setCrumbs([])setOpenError(null)- void queryClient.removeQueries({ queryKey: desktopQueryKeys.gfsRoot })+ void queryClient.removeQueries({ queryKey: [...desktopQueryKeys.gfsRoot, previous] })}}, [queryClient, sessionScope])@@ -124,6 +197,43 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {getNextPageParam: lastPage => lastPage.nextCursor ?? undefined,})+ const firstAccessiblePage = accessibleQuery.data?.pages[0]+ const view: GfsBrowserView = firstAccessiblePage?.view === 'operator' ? 'operator' : 'shared'+ const operatorRootResourceId =+ firstAccessiblePage?.view === 'operator' &&+ typeof firstAccessiblePage.rootResourceId === 'string' &&+ RESOURCE_ID_RE.test(firstAccessiblePage.rootResourceId)+ ? firstAccessiblePage.rootResourceId+ : null+ const operatorRoot = useMemo(+ () => (operatorRootResourceId ? rootCrumb(operatorRootResourceId) : null),+ [operatorRootResourceId]+ )+ const rootContractError =+ firstAccessiblePage?.view === 'operator' && !operatorRoot+ ? 'operator_root_missing: operator view did not include a valid rootResourceId'+ : null++ useEffect(() => {+ if (!firstAccessiblePage) return+ if (!operatorRoot) {+ setCrumbs(prev => (prev[0]?.isDriveRoot ? [] : prev))+ return+ }+ setCrumbs(prev => {+ const rest = prev[0]?.isDriveRoot ? prev.slice(1) : prev+ const first = prev[0]+ if (+ first?.isDriveRoot &&+ first.resourceId === operatorRoot.resourceId &&+ first.name === operatorRoot.name+ ) {+ return prev+ }+ return [operatorRoot, ...rest]+ })+ }, [firstAccessiblePage, operatorRoot])+const childrenQuery = useInfiniteQuery({queryKey: desktopQueryKeys.gfsChildren(sessionScope ?? 'anonymous',@@ -132,7 +242,8 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {),queryFn: ({ pageParam }) =>window.clerum.gfs.listChildren(current!.resourceId, DRIVE, pageParam),- enabled: Boolean(sessionScope) && Boolean(current) && currentIsDirectory,+ enabled:+ Boolean(sessionScope) && Boolean(current) && currentIsDirectory && !current?.isDriveRoot,initialPageParam: undefined as string | undefined,getNextPageParam: lastPage => lastPage.nextCursor ?? undefined,})@@ -158,7 +269,11 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {// The grants listing is the revoke-id source (the grant PUT returns no ids),// so writes must refetch it. Enabled only while the Manage dialog is open.const grantsQuery = useQuery({- queryKey: ['gfs', DRIVE, current?.resourceId ?? '', 'grants'],+ queryKey: desktopQueryKeys.gfsGrants(+ sessionScope ?? 'anonymous',+ current?.resourceId ?? '',+ DRIVE+ ),queryFn: () => window.clerum.gfs.listGrants(current!.resourceId, DRIVE),enabled: Boolean(sessionScope) && Boolean(current) && grantsListEnabled,})@@ -167,13 +282,34 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {if (!resourceId) returnawait queryClient.invalidateQueries({exact: true,- queryKey: ['gfs', DRIVE, resourceId, 'grants'],+ queryKey: desktopQueryKeys.gfsGrants(sessionScope ?? 'anonymous', resourceId, DRIVE),})- }, [current?.resourceId, queryClient])+ }, [current?.resourceId, queryClient, sessionScope])const revokeGrantMutation = useMutation({mutationFn: (grantId: string) => window.clerum.gfs.revokeGrant(grantId),onSuccess: refreshGrants,})+ const sharesQuery = useQuery({+ queryKey: desktopQueryKeys.gfsShares(+ sessionScope ?? 'anonymous',+ current?.resourceId ?? '',+ DRIVE+ ),+ queryFn: () => window.clerum.gfs.listShares(current!.resourceId, DRIVE),+ enabled: Boolean(sessionScope) && Boolean(current) && grantsListEnabled,+ })+ const refreshShares = useCallback(async () => {+ const resourceId = current?.resourceId+ if (!resourceId) return+ await queryClient.invalidateQueries({+ exact: true,+ queryKey: desktopQueryKeys.gfsShares(sessionScope ?? 'anonymous', resourceId, DRIVE),+ })+ }, [current?.resourceId, queryClient, sessionScope])+ const revokeShareMutation = useMutation({+ mutationFn: (shareId: string) => window.clerum.gfs.revokeShare(shareId),+ onSuccess: refreshShares,+ })const refreshGfs = useCallback(async () => {await queryClient.invalidateQueries({queryKey: desktopQueryKeys.gfsRoot,@@ -241,7 +377,9 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {[accessibleQuery.data])const grants = useMemo<GfsGrantListItem[]>(() => grantsQuery.data ?? [], [grantsQuery.data])- const accessibleErrorMessage = accessibleQuery.error ? toMessage(accessibleQuery.error) : null+ const shares = useMemo<GfsShareListItem[]>(() => sharesQuery.data ?? [], [sharesQuery.data])+ const accessibleErrorMessage =+ rootContractError ?? (accessibleQuery.error ? toMessage(accessibleQuery.error) : null)const accessibleNotice =sessionScope && !canListAccessibleResources? 'Automatic GFS discovery is not available in this desktop runtime. You can still open any GFS link you have.'@@ -249,59 +387,70 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {? 'Automatic GFS discovery is not available from this server yet. You can still open any GFS link you have.': null- const openUri = useCallback(async (uri: string) => {- setOpenError(null)- setResolving(true)- try {- const resource = await window.clerum.gfs.resolve(uri.trim())- const crumb: GfsCrumb = {- resourceId: resource.resourceId,- gfsUri: resource.gfsUri,- name: resource.name,- kind: resource.kind === 'directory' ? 'directory' : 'file',- version: resource.version ?? 0,- // `resolve` may omit bytes (older servers) — crumbs display 0 then,- // matching the `version ?? 0` handling above.- bytes: resource.bytes ?? 0,- }- const ancestors: GfsCrumb[] = []- const seenResourceIds = new Set([resource.resourceId])- let parentResourceId = resource.parentResourceId-- while (parentResourceId && ancestors.length < GFS_BREADCRUMB_MAX_DEPTH) {- if (seenResourceIds.has(parentResourceId)) break- seenResourceIds.add(parentResourceId)- try {- const parentRid = parentResourceId.replace(/-/g, '').toLowerCase()- const parent = await window.clerum.gfs.resolve(`gfs://${resource.drive}/${parentRid}`)- if (parent.kind !== 'directory') break- if (parent.name) {- ancestors.push({- resourceId: parent.resourceId,- gfsUri: parent.gfsUri,- name: parent.name,- kind: 'directory',- version: parent.version ?? 0,- bytes: parent.bytes ?? 0,- })+ const openUri = useCallback(+ async (uri: string) => {+ setOpenError(null)+ setResolving(true)+ try {+ const resource = await window.clerum.gfs.resolve(uri.trim())+ const crumb: GfsCrumb = {+ resourceId: resource.resourceId,+ gfsUri: resource.gfsUri,+ name: resource.name,+ kind: resource.kind === 'directory' ? 'directory' : 'file',+ version: resource.version ?? 0,+ // `resolve` may omit bytes (older servers) — crumbs display 0 then,+ // matching the `version ?? 0` handling above.+ bytes: resource.bytes ?? 0,+ }+ const ancestors: GfsCrumb[] = []+ const seenResourceIds = new Set([resource.resourceId])+ let parentResourceId = resource.parentResourceId++ while (parentResourceId && ancestors.length < GFS_BREADCRUMB_MAX_DEPTH) {+ if (seenResourceIds.has(parentResourceId)) break+ seenResourceIds.add(parentResourceId)+ try {+ const parentRid = parentResourceId.replace(/-/g, '').toLowerCase()+ const parent = await window.clerum.gfs.resolve(`gfs://${resource.drive}/${parentRid}`)+ if (parent.kind !== 'directory') break+ if (parent.name) {+ ancestors.push({+ resourceId: parent.resourceId,+ gfsUri: parent.gfsUri,+ name: parent.name,+ kind: 'directory',+ version: parent.version ?? 0,+ bytes: parent.bytes ?? 0,+ })+ }+ parentResourceId = parent.parentResourceId+ } catch {+ // A direct file grant can be readable while its parent is not. Keep+ // the file open and show only the ancestors the caller may resolve.+ break}- parentResourceId = parent.parentResourceId- } catch {- // A direct file grant can be readable while its parent is not. Keep- // the file open and show only the ancestors the caller may resolve.- break}- }- setCrumbs([...ancestors.reverse(), crumb])- return crumb- } catch (error) {- setOpenError(toMessage(error))- return false- } finally {- setResolving(false)- }- }, [])+ const resolvedCrumbs = [...ancestors.reverse(), crumb]+ setCrumbs(+ operatorRoot+ ? [+ operatorRoot,+ ...resolvedCrumbs.filter(item => item.resourceId !== operatorRoot.resourceId),+ ]+ : resolvedCrumbs+ )+ return crumb+ } catch (error) {+ setOpenError(toMessage(error))+ return false+ } finally {+ setResolving(false)+ }+ },+ [operatorRoot]+ )const openChild = useCallback((child: GfsBrowserChild) => {if (child.kind !== 'directory') return@@ -318,29 +467,37 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {])}, [])- const openResource = useCallback((resource: GfsBrowserChild) => {- setOpenError(null)- setCrumbs([- {+ const openResource = useCallback(+ (resource: GfsBrowserChild) => {+ setOpenError(null)+ const crumb: GfsCrumb = {resourceId: resource.resourceId,gfsUri: resource.gfsUri,name: resource.name,kind: resource.kind === 'directory' ? 'directory' : 'file',version: resource.version,bytes: resource.bytes,- },- ])- }, [])+ }+ setCrumbs(+ operatorRoot+ ? resource.resourceId === operatorRoot.resourceId+ ? [operatorRoot]+ : [operatorRoot, crumb]+ : [crumb]+ )+ },+ [operatorRoot]+ )const goToCrumb = useCallback((index: number) => {setCrumbs(prev => prev.slice(0, index + 1))}, [])const reset = useCallback(() => {- setCrumbs([])+ setCrumbs(operatorRoot ? [operatorRoot] : [])setOpenError(null)- void queryClient.removeQueries({ queryKey: ['desktop-app', 'gfs'] })- }, [queryClient])+ void queryClient.invalidateQueries({ queryKey: desktopQueryKeys.gfsRoot })+ }, [operatorRoot, queryClient])// Delegation actions throw on server rejection (e.g. 403 escalation_rejected);// the caller surfaces that — never swallow it. `inherit` is only sent when a@@ -365,6 +522,8 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {return {crumbs,current,+ view,+ isOperatorRoot: Boolean(current?.isDriveRoot),accessibleResources,items,affordances: (affordancesQuery.data as GfsBrowserAffordances | undefined) ?? null,@@ -404,6 +563,12 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {refreshGrants,revokeGrant: (grantId: string) => revokeGrantMutation.mutateAsync(grantId),revoking: revokeGrantMutation.isPending,+ shares,+ sharesError: sharesQuery.error,+ loadingShares: sharesQuery.isFetching,+ refreshShares,+ revokeShare: (shareId: string) => revokeShareMutation.mutateAsync(shareId),+ revokingShare: revokeShareMutation.isPending,createShare,createFolder: (name: string) => createFolderMutation.mutateAsync(name),createFile: (parentResourceId: string, name: string, encodedData: string) =>diff --git a/desktop-app/ui/src/pages/FilesPage.tsx b/desktop-app/ui/src/pages/FilesPage.tsxindex d21ef6b0b..d1ce8c8d2 100644--- a/desktop-app/ui/src/pages/FilesPage.tsx+++ b/desktop-app/ui/src/pages/FilesPage.tsx@@ -13,7 +13,11 @@ import {IconDownload,} from '@components/SidebarNav/icons'import { desktopQueryKeys } from '@hooks/domain/queryKeys'-import { useGfsBrowserController } from '@hooks/domain/useGfsBrowserController'+import {+ type GfsBrowserFailure,+ describeGfsBrowserFailure,+ useGfsBrowserController,+} from '@hooks/domain/useGfsBrowserController'import { assertGfsFileUploadSize } from '@lib/gfsFileUpload'import { describeGfsGrantError } from '@lib/gfsGrantErrors'import { gfsImagePreviewMimeType } from '@lib/gfsImagePreview'@@ -134,12 +138,15 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:const [filePreview, setFilePreview] = useState<GfsPreviewResource | null>(null)const [dragActive, setDragActive] = useState(false)const [droppedUploadCount, setDroppedUploadCount] = useState(0)+ const [mutationFailure, setMutationFailure] = useState<GfsBrowserFailure | null>(null)const uploadInputRef = useRef<HTMLInputElement | null>(null)const replaceInputRef = useRef<HTMLInputElement | null>(null)const ctrl = useGfsBrowserController({ grantsListEnabled: manageOpen })const {current,crumbs,+ view,+ isOperatorRoot,accessibleResources,items,affordances,@@ -195,8 +202,13 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:() => (ctrl.grantsError ? describeGfsGrantError(ctrl.grantsError) : null),[ctrl.grantsError])- const canWriteCurrent = hasBit(affordances, 'write')- const canDeleteCurrent = hasBit(affordances, 'delete')+ const sharesError = useMemo(+ () => (ctrl.sharesError ? describeGfsGrantError(ctrl.sharesError) : null),+ [ctrl.sharesError]+ )+ const mutationUnauthorized = mutationFailure?.kind === 'unauthorized'+ const canWriteCurrent = !mutationUnauthorized && hasBit(affordances, 'write')+ const canDeleteCurrent = !mutationUnauthorized && !isOperatorRoot && hasBit(affordances, 'delete')const currentIsFolder = current?.kind === 'directory'const currentIsFile = current?.kind === 'file'const currentPreviewAvailable = currentIsFile && isGfsPreviewFile(current?.name ?? '')@@ -224,6 +236,21 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:void refreshAffordances()}, [current?.resourceId, manageOpen, refreshAffordances])+ useEffect(() => {+ setMutationFailure(null)+ }, [current?.resourceId, view])++ const surfaceContentMutationError = (mutationError: unknown) => {+ const raw = mutationError instanceof Error ? mutationError.message : String(mutationError)+ const failure = describeGfsBrowserFailure(raw)+ if (failure.kind === 'unauthorized') {+ setMutationFailure(failure)+ pushToast?.(failure.message, 'error')+ return+ }+ pushToast?.(raw, 'error')+ }+const openFilePreview = (resource: Pick<GfsDriveResource, 'bytes' | 'gfsUri' | 'name'>): boolean => {@@ -291,6 +318,16 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:`${subjectKeys.length} ${subjectKeys.length === 1 ? 'share' : 'shares'} created`,'success')+ await ctrl.refreshShares()+ }++ const handleRevokeShare = async (shareId: string, label: string) => {+ try {+ await ctrl.revokeShare(shareId)+ pushToast?.(`Shared access revoked for ${label}`, 'success')+ } catch (revokeError) {+ pushToast?.(describeGfsGrantError(revokeError).message, 'error')+ }}const handleDownload = async (uri: string, name: string) => {@@ -345,11 +382,12 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:try {const name = await normalizeGfsResourceName(requestedName)await ctrl.createFolder(name)+ setMutationFailure(null)setCreateFolderName('')setCreateFolderOpen(false)pushToast?.(`Folder ${name} created`, 'success')} catch (createError) {- pushToast?.(createError instanceof Error ? createError.message : String(createError), 'error')+ surfaceContentMutationError(createError)}}@@ -361,9 +399,10 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:try {const name = await normalizeGfsResourceName(file.name)await ctrl.createFile(parentResourceId, name, await fileToEncodedData(file))+ setMutationFailure(null)pushToast?.(`Uploaded ${name}`, 'success')} catch (uploadError) {- pushToast?.(uploadError instanceof Error ? uploadError.message : String(uploadError), 'error')+ surfaceContentMutationError(uploadError)}}@@ -428,12 +467,10 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:if (!file || !current) returntry {await ctrl.replaceFile(current.resourceId, await fileToEncodedData(file), current.version)+ setMutationFailure(null)pushToast?.(`Replaced ${current.name}`, 'success')} catch (replaceError) {- pushToast?.(- replaceError instanceof Error ? replaceError.message : String(replaceError),- 'error'- )+ surfaceContentMutationError(replaceError)}}@@ -445,10 +482,11 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:const name = await normalizeGfsResourceName(requestedName)if (name === current.name) returnawait ctrl.renameResource(current.resourceId, name, current.version)+ setMutationFailure(null)setRenameOpen(false)pushToast?.(`Renamed to ${name}`, 'success')} catch (renameError) {- pushToast?.(renameError instanceof Error ? renameError.message : String(renameError), 'error')+ surfaceContentMutationError(renameError)}}@@ -456,25 +494,56 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:if (!current) returntry {await ctrl.deleteResource(current.resourceId, current.version)+ setMutationFailure(null)setDeleteOpen(false)setManageOpen(false)pushToast?.(`Deleted ${current.name}`, 'success')} catch (deleteError) {- pushToast?.(deleteError instanceof Error ? deleteError.message : String(deleteError), 'error')+ surfaceContentMutationError(deleteError)}}const visibleResources = useMemo<GfsDriveResource[]>(() => {- const resources = currentIsFolder ? items : currentIsFile ? [] : accessibleResources+ const resources = isOperatorRoot+ ? accessibleResources+ : currentIsFolder+ ? items+ : currentIsFile+ ? []+ : accessibleResourcesreturn [...resources].sort((left, right) => {if (left.kind === right.kind) return 0return left.kind === 'directory' ? -1 : 1})- }, [accessibleResources, currentIsFile, currentIsFolder, items])- const visibleLoading = currentIsFolder ? loading : !current ? loadingAccessible : false- const visibleError = currentIsFolder ? error : !current ? accessibleError : null- const hasMoreVisible = currentIsFolder ? ctrl.hasMore : !current && ctrl.hasMoreAccessible- const loadingMoreVisible = currentIsFolder ? ctrl.isFetchingMore : ctrl.isFetchingMoreAccessible+ }, [accessibleResources, currentIsFile, currentIsFolder, isOperatorRoot, items])+ const visibleLoading = isOperatorRoot+ ? loadingAccessible+ : currentIsFolder+ ? loading+ : !current+ ? loadingAccessible+ : false+ const visibleError = isOperatorRoot+ ? accessibleError+ : currentIsFolder+ ? error+ : !current+ ? accessibleError+ : null+ const visibleFailure = visibleError ? describeGfsBrowserFailure(visibleError) : null+ const hasMoreVisible = isOperatorRoot+ ? ctrl.hasMoreAccessible+ : currentIsFolder+ ? ctrl.hasMore+ : !current && ctrl.hasMoreAccessible+ const loadingMoreVisible = isOperatorRoot+ ? ctrl.isFetchingMoreAccessible+ : currentIsFolder+ ? ctrl.isFetchingMore+ : ctrl.isFetchingMoreAccessible+ const rootLabel = isOperatorRoot || view === 'operator' ? 'Global File System' : 'Shared with me'+ const operatorRootResourceId =+ view === 'operator' && crumbs[0]?.isDriveRoot ? crumbs[0].resourceId : undefinedconst openManage = (resource: GfsDriveResource) => {if (resource.resourceId !== current?.resourceId) ctrl.openResource(resource)@@ -498,7 +567,11 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:<section className="page da-gfs-page"><div className="page-header"><h2>Files</h2>- <p className="muted">Browse and manage everything shared with you in one place.</p>+ <p className="muted">+ {view === 'operator'+ ? 'Browse and manage the Global File System from its root.'+ : 'Browse and manage everything shared with you in one place.'}+ </p></div><div className="page-layout da-gfs-layout">@@ -506,6 +579,7 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:className="page-card da-gfs-drive"aria-label="Global File System browser"aria-busy={visibleLoading || droppedUploadCount > 0}+ data-testid={`gfs-view-${view}`}onDragEnter={handleGfsDragEnter}onDragLeave={handleGfsDragLeave}onDragOver={handleGfsDragOver}@@ -516,31 +590,77 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:<ButtonclassName="da-gfs-drive__breadcrumb"color="neutral"- disabled={!current}+ data-resource-id={operatorRootResourceId}+ data-testid={`gfs-root-${view}`}+ disabled={!current || isOperatorRoot}onClick={() => {setManageOpen(false)ctrl.reset()}}variant="text">- Shared with me+ {rootLabel}</Button>- {crumbs.map((crumb, index) => (- <span className="da-gfs-drive__crumb-group" key={crumb.resourceId}>- <IconChevronRight aria-hidden="true" />+ {crumbs.map((crumb, index) =>+ crumb.isDriveRoot ? null : (+ <span className="da-gfs-drive__crumb-group" key={crumb.resourceId}>+ <IconChevronRight aria-hidden="true" />+ <Button+ className="da-gfs-drive__breadcrumb"+ color="neutral"+ disabled={index === crumbs.length - 1}+ onClick={() => ctrl.goToCrumb(index)}+ variant="text"+ >+ {crumb.name}+ </Button>+ </span>+ )+ )}+ </nav>+ <div className="da-gfs-drive__header-actions">+ {currentIsFolder && canWriteCurrent ? (+ <><Button- className="da-gfs-drive__breadcrumb"- color="neutral"- disabled={index === crumbs.length - 1}- onClick={() => ctrl.goToCrumb(index)}- variant="text"+ data-testid="gfs-create-folder-action"+ loading={ctrl.mutating}+ onClick={() => {+ setCreateFolderName('')+ setCreateFolderOpen(true)+ setDeleteOpen(false)+ setManageOpen(true)+ }}+ size="sm"+ variant="outline">- {crumb.name}+ New folder</Button>- </span>- ))}- </nav>- <div className="da-gfs-drive__header-actions">+ <Button+ data-testid="gfs-upload-action"+ loading={ctrl.mutating}+ onClick={() => uploadInputRef.current?.click()}+ size="sm"+ variant="outline"+ >+ Upload file+ </Button>+ {isOperatorRoot && (affordances?.canDelegate || affordances?.canCreateShare) ? (+ <Button+ data-testid="gfs-manage-access-action"+ onClick={() => {+ setCreateFolderOpen(false)+ setDeleteOpen(false)+ setRenameOpen(false)+ setManageOpen(true)+ }}+ size="sm"+ variant="outline"+ >+ Manage access+ </Button>+ ) : null}+ </>+ ) : null}<Buttoncolor="neutral"onClick={() => setOpenLinkOpen(true)}@@ -569,6 +689,21 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:</div></div>+ {currentIsFolder && canWriteCurrent ? (+ <input+ aria-label="Upload file"+ className="visually-hidden"+ data-testid="gfs-upload-input"+ ref={uploadInputRef}+ type="file"+ onChange={event => {+ const file = event.currentTarget.files?.[0]+ event.currentTarget.value = ''+ void handleUploadFile(file)+ }}+ />+ ) : null}+{dragActive || droppedUploadCount > 0 ? (<div className="composer-drop-overlay da-gfs-drop-overlay" role="status">{droppedUploadCount > 0@@ -579,9 +714,29 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:) : null}{accessibleNotice ? <StatusBanner tone="info" text={accessibleNotice} /> : null}- {visibleError ? <StatusBanner tone="error" text={visibleError} /> : null}- {visibleLoading ? (+ {mutationFailure ? (+ <div+ data-testid={`gfs-mutation-error-${mutationFailure.kind}`}+ role="alert"+ aria-label={mutationFailure.title}+ >+ <StatusBanner+ tone="error"+ text={`${mutationFailure.title}. ${mutationFailure.message}`}+ />+ </div>+ ) : null}++ {visibleFailure ? (+ <div+ data-testid={`gfs-error-${visibleFailure.kind}`}+ role="alert"+ aria-label={visibleFailure.title}+ >+ <EmptyState title={visibleFailure.title} body={visibleFailure.message} />+ </div>+ ) : visibleLoading ? (<divclassName="da-gfs-loading"role="status"@@ -626,14 +781,24 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:</div></div>) : visibleResources.length === 0 ? (- <EmptyState- title={currentIsFolder ? 'This folder is empty' : 'No shared files yet'}- body={- currentIsFolder- ? 'Files and folders added here will appear in this list.'- : 'Resources shared directly with you or your teams will appear here.'- }- />+ <div data-testid={isOperatorRoot ? 'gfs-empty-operator' : 'gfs-empty-shared'}>+ <EmptyState+ title={+ isOperatorRoot+ ? 'Global File System is empty'+ : currentIsFolder+ ? 'This folder is empty'+ : 'No shared files yet'+ }+ body={+ isOperatorRoot+ ? 'Create a folder or upload a file to get started.'+ : currentIsFolder+ ? 'Files and folders added here will appear in this list.'+ : 'Resources shared directly with you or your teams will appear here.'+ }+ />+ </div>) : (<divclassName="da-grid da-gfs-drive__grid"@@ -651,7 +816,11 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:</div><div className="da-grid__body">{visibleResources.map(resource => (- <div className="da-grid__row da-grid__row--compact" key={resource.resourceId}>+ <div+ className="da-grid__row da-grid__row--compact"+ data-testid={`gfs-resource-row-${resource.resourceId}`}+ key={resource.resourceId}+ ><span className="da-gfs-list__icon da-grid__cell" aria-hidden="true">{resource.kind === 'directory' ? <IconContexts /> : <IconAttachFile />}</span>@@ -720,7 +889,9 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:<div className="da-gfs-footer-actions"><Buttonloading={loadingMoreVisible}- onClick={currentIsFolder ? ctrl.loadMore : ctrl.loadMoreAccessible}+ onClick={+ currentIsFolder && !isOperatorRoot ? ctrl.loadMore : ctrl.loadMoreAccessible+ }size="sm"variant="outline">@@ -842,7 +1013,7 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:: undefined}onDelete={- canDeleteCurrent+ canDeleteCurrent && !isOperatorRoot? () => {setDeleteOpen(true)setCreateFolderOpen(false)@@ -860,7 +1031,7 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:: undefined}onRename={- canWriteCurrent+ canWriteCurrent && !isOperatorRoot? () => {setRenameName(current.name)setRenameOpen(true)@@ -906,19 +1077,6 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:</span></header>- {currentIsFolder && canWriteCurrent ? (- <input- aria-label="Upload file"- className="visually-hidden"- ref={uploadInputRef}- type="file"- onChange={event => {- const file = event.currentTarget.files?.[0]- event.currentTarget.value = ''- void handleUploadFile(file)- }}- />- ) : null}{currentIsFile && canWriteCurrent ? (<inputaria-label="Replace file"@@ -1022,12 +1180,15 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:)}</section>- <section className="da-gfs-manage-section da-gfs-manage-section--grants">+ <section+ className="da-gfs-manage-section da-gfs-manage-section--grants"+ data-testid="gfs-access-management"+ ><div className="da-gfs-manage-section__header"><div><h4>Who has access</h4><p className="muted">- Existing grants on this resource. Revoking is immediate.+ Existing direct grants and shares on this resource. Revoking is immediate.</p></div></div>@@ -1035,9 +1196,13 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:agents={agentSubjects}error={grantsError}items={ctrl.grants}- loading={ctrl.loadingGrants}+ loading={ctrl.loadingGrants || ctrl.loadingShares}onRevoke={(item, label) => void handleRevokeGrant(item.id, label)}+ onRevokeShare={(item, label) => void handleRevokeShare(item.id, label)}revoking={ctrl.revoking}+ revokingShare={ctrl.revokingShare}+ shareError={sharesError}+ shares={ctrl.shares}subjects={delegationSubjects}/></section>diff --git a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsxindex 1df6c4947..faa1d5c0b 100644--- a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx+++ b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx@@ -14,12 +14,17 @@ const hookMock = vi.hoisted(() => ({useGfsBrowserController: vi.fn(),}))-vi.mock('@hooks/domain/useGfsBrowserController', () => hookMock)+vi.mock('@hooks/domain/useGfsBrowserController', async importOriginal => ({+ ...(await importOriginal<typeof import('@hooks/domain/useGfsBrowserController')>()),+ ...hookMock,+}))function baseController() {return {current: null,crumbs: [],+ view: 'shared' as const,+ isOperatorRoot: false,accessibleResources: [],items: [],affordances: null,@@ -49,6 +54,12 @@ function baseController() {refreshGrants: vi.fn(),revokeGrant: vi.fn(),revoking: false,+ shares: [],+ sharesError: null,+ loadingShares: false,+ refreshShares: vi.fn(),+ revokeShare: vi.fn(),+ revokingShare: false,createShare: vi.fn(),createFolder: vi.fn(),createFile: vi.fn(),@@ -125,6 +136,154 @@ describe('FilesPage', () => {expect(screen.queryByText(/Error invoking remote method/i)).toBeNull()})+ it('renders the real operator root with visible root create and upload actions', async () => {+ const rootResourceId = '11111111-1111-1111-1111-111111111111'+ const createFolder = vi.fn(async () => undefined)+ const createFile = vi.fn(async () => undefined)+ const pushToast = vi.fn()+ hookMock.useGfsBrowserController.mockReturnValue({+ ...baseController(),+ view: 'operator',+ isOperatorRoot: true,+ current: {+ resourceId: rootResourceId,+ gfsUri: 'gfs://main/11111111111111111111111111111111',+ name: 'Global File System',+ kind: 'directory',+ version: 0,+ bytes: 0,+ isDriveRoot: true,+ },+ crumbs: [+ {+ resourceId: rootResourceId,+ gfsUri: 'gfs://main/11111111111111111111111111111111',+ name: 'Global File System',+ kind: 'directory',+ version: 0,+ bytes: 0,+ isDriveRoot: true,+ },+ ],+ affordances: {+ held: ['read', 'write', 'delete', 'manage_acl', 'share'],+ canDelegate: true,+ grantableBits: ['read', 'write', 'delete', 'manage_acl', 'share'],+ canCreateShare: true,+ },+ createFolder,+ createFile,+ })++ renderFilesPage(pushToast)++ expect(screen.getByTestId('gfs-view-operator')).toBeTruthy()+ expect(screen.getByTestId('gfs-root-operator').textContent).toBe('Global File System')+ expect(screen.getByTestId('gfs-root-operator').getAttribute('data-resource-id')).toBe(+ rootResourceId+ )+ expect(screen.getByTestId('gfs-empty-operator').textContent).toContain(+ 'Global File System is empty'+ )+ expect(screen.getByTestId('gfs-manage-access-action').textContent).toBe('Manage access')++ fireEvent.click(screen.getByTestId('gfs-create-folder-action'))+ const createFolderForm = screen.getByRole('form', { name: 'Create folder' })+ fireEvent.change(screen.getByLabelText('Folder name'), { target: { value: 'Root docs' } })+ fireEvent.click(createFolderForm.querySelector('button[type="submit"]')!)+ await waitFor(() => expect(createFolder).toHaveBeenCalledWith('Root docs'))++ fireEvent.change(screen.getByTestId('gfs-upload-input'), {+ target: { files: [new File(['root upload'], 'root.md', { type: 'text/markdown' })] },+ })+ await waitFor(() =>+ expect(createFile).toHaveBeenCalledWith(rootResourceId, 'root.md', 'cm9vdCB1cGxvYWQ=')+ )+ })++ it.each(['401 Unauthorized', '403 Forbidden'])(+ 'fails closed with a stable alert after a %s root mutation denial',+ async status => {+ const rootResourceId = '11111111-1111-1111-1111-111111111111'+ const createFolder = vi.fn(async () => {+ throw new Error(`${status}: gfs_operator_link_invalid`)+ })+ const pushToast = vi.fn()+ hookMock.useGfsBrowserController.mockReturnValue({+ ...baseController(),+ view: 'operator',+ isOperatorRoot: true,+ current: {+ resourceId: rootResourceId,+ gfsUri: 'gfs://main/11111111111111111111111111111111',+ name: 'Global File System',+ kind: 'directory',+ version: 0,+ bytes: 0,+ isDriveRoot: true,+ },+ crumbs: [+ {+ resourceId: rootResourceId,+ gfsUri: 'gfs://main/11111111111111111111111111111111',+ name: 'Global File System',+ kind: 'directory',+ version: 0,+ bytes: 0,+ isDriveRoot: true,+ },+ ],+ affordances: {+ held: ['read', 'write', 'delete', 'manage_acl', 'share'],+ canDelegate: true,+ grantableBits: ['read', 'write', 'delete', 'manage_acl', 'share'],+ canCreateShare: true,+ },+ createFolder,+ })++ renderFilesPage(pushToast)+ fireEvent.click(screen.getByTestId('gfs-create-folder-action'))+ const form = screen.getByRole('form', { name: 'Create folder' })+ fireEvent.change(screen.getByLabelText('Folder name'), { target: { value: 'Denied' } })+ fireEvent.click(form.querySelector('button[type="submit"]')!)++ const alert = await screen.findByTestId('gfs-mutation-error-unauthorized')+ expect(alert.getAttribute('role')).toBe('alert')+ expect(alert.textContent).toContain('File access is not authorized')+ expect(screen.queryByTestId('gfs-create-folder-action')).toBeNull()+ expect(screen.queryByTestId('gfs-upload-action')).toBeNull()+ expect(pushToast).toHaveBeenCalledWith(+ 'Your current Desktop session cannot access this location. Sign in again or contact an administrator.',+ 'error'+ )+ }+ )++ it.each([+ ['unauthorized', '403 Forbidden: operator_link_inactive', 'File access is not authorized'],+ ['upstream', '502 Bad Gateway: gfsc_unreachable', 'Global File System is unavailable'],+ [+ 'uninitialized',+ 'operator_root_missing: missing rootResourceId',+ 'Global File System is not initialized',+ ],+ ] as const)(+ 'renders an explicit %s root state without a misleading empty result',+ (kind, error, title) => {+ hookMock.useGfsBrowserController.mockReturnValue({+ ...baseController(),+ accessibleError: error,+ })++ renderFilesPage()++ expect(screen.getByTestId(`gfs-error-${kind}`).textContent).toContain(title)+ expect(screen.queryByText('No shared files yet')).toBeNull()+ expect(screen.queryByTestId('gfs-empty-shared')).toBeNull()+ }+ )+it.each([['initial GFS discovery', { loadingAccessible: true }],[@@ -1024,6 +1183,68 @@ describe('FilesPage', () => {)})+ it('lists and revokes a direct share from the combined access surface', async () => {+ Object.defineProperty(window, 'clerum', {+ configurable: true,+ value: {+ agents: { listMine: vi.fn(async () => []) },+ team: {+ directory: vi.fn(async () => ({+ currentTeamId: 'team-1',+ items: [+ {+ team: { id: 'team-1', name: 'Core Team', role: 'admin' },+ members: [],+ contextIds: [],+ agentNames: [],+ },+ ],+ })),+ },+ },+ })+ const revokeShare = vi.fn(async () => undefined)+ const pushToast = vi.fn()+ hookMock.useGfsBrowserController.mockReturnValue({+ ...baseController(),+ current: {+ resourceId: 'folder-1',+ gfsUri: 'gfs://main/folder',+ name: 'Team folder',+ kind: 'directory',+ },+ affordances: {+ held: ['read', 'manage_acl', 'share'],+ canDelegate: true,+ grantableBits: ['read'],+ canCreateShare: true,+ },+ shares: [+ {+ id: 'share-1',+ drive: 'main',+ resourceId: 'folder-1',+ subject: { type: 'team', id: 'team-1' },+ permissions: ['read'],+ includeDescendants: true,+ },+ ],+ revokeShare,+ })++ renderFilesPage(pushToast)+ await openManageDialog('Team folder')++ const shareRow = await screen.findByTestId('gfs-access-row-share-share-1')+ expect(within(shareRow).getByText('Share · team')).toBeTruthy()+ fireEvent.click(+ within(shareRow).getByRole('button', { name: 'Revoke shared access for Core Team' })+ )++ await waitFor(() => expect(revokeShare).toHaveBeenCalledWith('share-1'))+ expect(pushToast).toHaveBeenCalledWith('Shared access revoked for Core Team', 'success')+ })+it('refreshes server affordances whenever the manage dialog opens', async () => {const refreshAffordances = vi.fn(async () => undefined)hookMock.useGfsBrowserController.mockReturnValue({diff --git a/docs/concepts/open-core-and-hosted.md b/docs/concepts/open-core-and-hosted.mdindex 4d4d66050..9c3fed8b6 100644--- a/docs/concepts/open-core-and-hosted.md+++ b/docs/concepts/open-core-and-hosted.md@@ -20,6 +20,10 @@ and not held back:production on any Kubernetes cluster.- **All three UIs** — Control UI, Desktop App, Profile UI — plus `electron-forge`packaging to ship the desktop app to your users.+- **Self-hosted initial-admin GFS parity** — the Desktop identity created for+ the first Control Admin during setup is linked directly for GFS operator+ access, and that link can be revoked from Control UI without changing the+ admin account or its credentials.- The **registry client**: connect to a registry to install and publishconnectors and recipes.- The **cluster E2E suites**.diff --git a/docs/how-to/desktop-setup-and-updates.md b/docs/how-to/desktop-setup-and-updates.mdindex cfae4e7fb..34c8b9974 100644--- a/docs/how-to/desktop-setup-and-updates.md+++ b/docs/how-to/desktop-setup-and-updates.md@@ -15,6 +15,17 @@ For packaging and shipping the build itself, see- You distribute a **packaged** build and want users to know when a new releaserequires them to update.+### Self-hosted first administrator++The first Control Admin created by the self-hosted `/admin/auth/setup` bootstrap+is a separate setup path from invitation onboarding. The Desktop identity+provisioned for that admin is linked directly for GFS operator access when the+self-hosted deployment enables the operator-link setting. Control UI displays+the exact pair and provides **Revoke/disable Desktop GFS operator access**;+revoking it removes only GFS authority and preserves the admin account,+passwords, identities, and unrelated permissions. Invitations and ordinary+member provisioning do not create or repair this link.+## The environment modelYou save only the **External REST API URL** for an instance. The app then asksdiff --git a/docs/surfaces/desktop-app.md b/docs/surfaces/desktop-app.mdindex de071f6c1..8efb55c95 100644--- a/docs/surfaces/desktop-app.md+++ b/docs/surfaces/desktop-app.md@@ -64,6 +64,27 @@ platform, and the [Control UI](control-ui.md) for the admin side of that split.(`SharedFilesTab`) scoped to a context, and the brokered Global FileSystem for cross-context storage.+## Self-hosted initial admin access to GFS++In a self-hosted installation, the Desktop identity provisioned for the first+Control Admin during the supported `/admin/auth/setup` bootstrap is linked+directly to that exact Control Admin. The link grants GFS operator authority+only; it is not inferred from an email address, a password, or a later+invitation. No Control UI credential, admin password, or Control API token is+ever sent to or stored by Desktop.++The Control UI shows the exact Desktop-user/Control-Admin pair and its current+link state. An authenticated administrator can confirm **Revoke/disable Desktop+GFS operator access**. That action removes only the GFS operator link: it does+not delete or disable the Control Admin, change either password, remove either+identity, or alter unrelated Control Plane permissions. The next GFS request+from the Desktop session is denied, while ordinary user behavior remains+subject to its existing user-plane authorization.++This initial-setup link is deliberately separate from invitations and ordinary+member provisioning. Those flows do not create, repair, or reassign an operator+link.+## ScreensThe app's top-level navigation (`NavItem` indiff --git a/external-rest-api/src/routes/gfs.ts b/external-rest-api/src/routes/gfs.tsindex ee7c0a245..29a97c12c 100644--- a/external-rest-api/src/routes/gfs.ts+++ b/external-rest-api/src/routes/gfs.ts@@ -1,5 +1,7 @@import { Router } from 'express'import type { NextFunction, Response } from 'express'+import type { Request } from 'express'+import { randomUUID } from 'node:crypto'import { Readable } from 'node:stream'import { pipeline } from 'node:stream/promises'import { ControlApiError, controlApiRequest, controlApiStreamRequest } from '../controlApiClient.js'@@ -21,6 +23,39 @@ import { type AuthedRequest, extractAuthToken, requireAuth } from '../middleware// client (a wedged gfsc looks identical to an internal bug).const PROPAGATED = new Set([400, 401, 403, 404, 409, 410, 412, 422, 429, 500, 502, 503, 504])const STREAM_HEADERS = ['content-type', 'content-length', 'content-disposition']+const UUID_ANY_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i++type GfsAuthedRequest = AuthedRequest & { gfsRequestId?: string }+type GfsRequestOptions = {+ query?: Record<string, string | undefined>+ body?: unknown+ userSessionToken?: string+ extraHeaders?: Record<string, string>+}++function attachGfsRequestId(req: Request, res: Response, next: NextFunction): void {+ const raw = req.header('x-request-id')?.trim()+ const requestId = raw && UUID_ANY_RE.test(raw) ? raw.toLowerCase() : randomUUID()+ ;(req as GfsAuthedRequest).gfsRequestId = requestId+ res.setHeader('x-request-id', requestId)+ next()+}++function withGfsRequestId(req: GfsAuthedRequest, options: GfsRequestOptions): GfsRequestOptions {+ return {+ ...options,+ extraHeaders: { ...options.extraHeaders, 'x-request-id': req.gfsRequestId! },+ }+}++function gfsControlApiRequest<T>(+ req: GfsAuthedRequest,+ method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE',+ path: string,+ options: GfsRequestOptions+): Promise<T> {+ return controlApiRequest<T>(method, path, withGfsRequestId(req, options))+}function forwardControlApiError(error: unknown, res: Response, next: NextFunction): void {if (error instanceof ControlApiError && PROPAGATED.has(error.status)) {@@ -35,11 +70,11 @@ function forwardControlApiError(error: unknown, res: Response, next: NextFunctioexport function createGfsRouter(): Router {const router = Router()- router.use('/me/gfs', requireAuth)+ router.use('/me/gfs', attachGfsRequestId, requireAuth)router.post('/me/gfs/token', async (req: AuthedRequest, res, next) => {try {- const data = await controlApiRequest('POST', '/external/gfs/token', {+ const data = await gfsControlApiRequest(req, 'POST', '/external/gfs/token', {userSessionToken: extractAuthToken(req),body: req.body ?? {},})@@ -51,7 +86,7 @@ export function createGfsRouter(): Router {router.get('/me/gfs/resolve', async (req: AuthedRequest, res, next) => {try {- const data = await controlApiRequest('GET', '/external/gfs/resolve', {+ const data = await gfsControlApiRequest(req, 'GET', '/external/gfs/resolve', {userSessionToken: extractAuthToken(req),query: { uri: typeof req.query.uri === 'string' ? req.query.uri : undefined },})@@ -63,7 +98,7 @@ export function createGfsRouter(): Router {router.get('/me/gfs/resources', async (req: AuthedRequest, res, next) => {try {- const data = await controlApiRequest('GET', '/external/gfs/resources', {+ const data = await gfsControlApiRequest(req, 'GET', '/external/gfs/resources', {userSessionToken: extractAuthToken(req),query: {drive: typeof req.query.drive === 'string' ? req.query.drive : undefined,@@ -79,7 +114,8 @@ export function createGfsRouter(): Router {router.get('/me/gfs/resources/:id/children', async (req: AuthedRequest, res, next) => {try {- const data = await controlApiRequest(+ const data = await gfsControlApiRequest(+ req,'GET',`/external/gfs/resources/${encodeURIComponent(req.params.id)}/children`,{@@ -99,7 +135,8 @@ export function createGfsRouter(): Router {router.get('/me/gfs/resources/:id/affordances', async (req: AuthedRequest, res, next) => {try {- const data = await controlApiRequest(+ const data = await gfsControlApiRequest(+ req,'GET',`/external/gfs/resources/${encodeURIComponent(req.params.id)}/affordances`,{@@ -115,7 +152,8 @@ export function createGfsRouter(): Router {router.patch('/me/gfs/resources/:id', async (req: AuthedRequest, res, next) => {try {- const data = await controlApiRequest(+ const data = await gfsControlApiRequest(+ req,'PATCH',`/external/gfs/resources/${encodeURIComponent(req.params.id)}`,{@@ -132,7 +170,8 @@ export function createGfsRouter(): Router {router.post('/me/gfs/resources/:id/children', async (req: AuthedRequest, res, next) => {try {- const data = await controlApiRequest(+ const data = await gfsControlApiRequest(+ req,'POST',`/external/gfs/resources/${encodeURIComponent(req.params.id)}/children`,{@@ -149,7 +188,8 @@ export function createGfsRouter(): Router {router.put('/me/gfs/resources/:id/content', async (req: AuthedRequest, res, next) => {try {- const data = await controlApiRequest(+ const data = await gfsControlApiRequest(+ req,'PUT',`/external/gfs/resources/${encodeURIComponent(req.params.id)}/content`,{@@ -166,7 +206,8 @@ export function createGfsRouter(): Router {router.delete('/me/gfs/resources/:id', async (req: AuthedRequest, res, next) => {try {- const data = await controlApiRequest(+ const data = await gfsControlApiRequest(+ req,'DELETE',`/external/gfs/resources/${encodeURIComponent(req.params.id)}`,{@@ -186,10 +227,10 @@ export function createGfsRouter(): Router {const upstream = await controlApiStreamRequest('GET',`/external/gfs/proxy/${encodeURIComponent(req.params.rid)}`,- {+ withGfsRequestId(req, {userSessionToken: extractAuthToken(req),query: { drive: typeof req.query.drive === 'string' ? req.query.drive : undefined },- }+ }))res.status(upstream.status)for (const header of STREAM_HEADERS) {@@ -218,7 +259,7 @@ export function createGfsRouter(): Router {// powers per-row revoke in the Manage modal.router.get('/me/gfs/grants', async (req: AuthedRequest, res, next) => {try {- const data = await controlApiRequest('GET', '/external/gfs/grants', {+ const data = await gfsControlApiRequest(req, 'GET', '/external/gfs/grants', {userSessionToken: extractAuthToken(req),query: {drive: typeof req.query.drive === 'string' ? req.query.drive : undefined,@@ -233,7 +274,7 @@ export function createGfsRouter(): Router {router.put('/me/gfs/grants', async (req: AuthedRequest, res, next) => {try {- const data = await controlApiRequest('PUT', '/external/gfs/grants', {+ const data = await gfsControlApiRequest(req, 'PUT', '/external/gfs/grants', {userSessionToken: extractAuthToken(req),body: req.body ?? {},})@@ -245,7 +286,8 @@ export function createGfsRouter(): Router {router.delete('/me/gfs/grants/:id', async (req: AuthedRequest, res, next) => {try {- const data = await controlApiRequest(+ const data = await gfsControlApiRequest(+ req,'DELETE',`/external/gfs/grants/${encodeURIComponent(req.params.id)}`,{ userSessionToken: extractAuthToken(req) }@@ -258,7 +300,7 @@ export function createGfsRouter(): Router {router.post('/me/gfs/shares', async (req: AuthedRequest, res, next) => {try {- const data = await controlApiRequest('POST', '/external/gfs/shares', {+ const data = await gfsControlApiRequest(req, 'POST', '/external/gfs/shares', {userSessionToken: extractAuthToken(req),body: req.body ?? {},})@@ -268,9 +310,25 @@ export function createGfsRouter(): Router {}})+ router.get('/me/gfs/shares', async (req: AuthedRequest, res, next) => {+ try {+ const data = await gfsControlApiRequest(req, 'GET', '/external/gfs/shares', {+ userSessionToken: extractAuthToken(req),+ query: {+ drive: typeof req.query.drive === 'string' ? req.query.drive : undefined,+ resourceId: typeof req.query.resourceId === 'string' ? req.query.resourceId : undefined,+ },+ })+ res.status(200).json(data)+ } catch (error) {+ forwardControlApiError(error, res, next)+ }+ })+router.delete('/me/gfs/shares/:id', async (req: AuthedRequest, res, next) => {try {- const data = await controlApiRequest(+ const data = await gfsControlApiRequest(+ req,'DELETE',`/external/gfs/shares/${encodeURIComponent(req.params.id)}`,{ userSessionToken: extractAuthToken(req) }diff --git a/external-rest-api/test/routes.gfs.test.ts b/external-rest-api/test/routes.gfs.test.tsindex 472104e5c..3c739b454 100644--- a/external-rest-api/test/routes.gfs.test.ts+++ b/external-rest-api/test/routes.gfs.test.ts@@ -27,6 +27,8 @@ vi.mock('../src/controlApiClient.js', () => ({const authTokenMock = vi.hoisted(() => ({ verifyToken: vi.fn() }))vi.mock('../src/authToken.js', () => authTokenMock)+const REQUEST_ID = '11111111-2222-4333-8444-555555555555'+function buildApp() {const app = express()app.use(express.json())@@ -53,13 +55,16 @@ describe('routes/gfs /me/gfs/* (user session passthrough → /external/gfs/*)',const res = await request(buildApp()).post('/me/gfs/token').set('authorization', 'Bearer sess-xyz')+ .set('x-request-id', REQUEST_ID).send({ scopes: ['gfs.read'] })expect(res.status).toBe(200)expect(res.body.token).toBe('gfs-tok')expect(clientMock.controlApiRequest).toHaveBeenCalledWith('POST', '/external/gfs/token', {userSessionToken: 'sess-xyz',body: { scopes: ['gfs.read'] },+ extraHeaders: { 'x-request-id': REQUEST_ID },})+ expect(res.headers['x-request-id']).toBe(REQUEST_ID)})it('forwards a user delegation grant to /external/gfs/grants', async () => {@@ -73,11 +78,13 @@ describe('routes/gfs /me/gfs/* (user session passthrough → /external/gfs/*)',const res = await request(buildApp()).put('/me/gfs/grants').set('authorization', 'Bearer sess-xyz')+ .set('x-request-id', REQUEST_ID).send(body)expect(res.status).toBe(200)expect(clientMock.controlApiRequest).toHaveBeenCalledWith('PUT', '/external/gfs/grants', {userSessionToken: 'sess-xyz',body,+ extraHeaders: { 'x-request-id': REQUEST_ID },})})@@ -89,11 +96,13 @@ describe('routes/gfs /me/gfs/* (user session passthrough → /external/gfs/*)',const res = await request(buildApp()).get('/me/gfs/resources?drive=main&limit=25&cursor=cursor-1').set('authorization', 'Bearer sess-xyz')+ .set('x-request-id', REQUEST_ID)expect(res.status).toBe(200)expect(res.body.data.nextCursor).toBe('next-page')expect(clientMock.controlApiRequest).toHaveBeenCalledWith('GET', '/external/gfs/resources', {userSessionToken: 'sess-xyz',query: { drive: 'main', limit: '25', cursor: 'cursor-1' },+ extraHeaders: { 'x-request-id': REQUEST_ID },})})@@ -145,13 +154,18 @@ describe('routes/gfs /me/gfs/* (user session passthrough → /external/gfs/*)',const res = await request(buildApp()).get('/me/gfs/proxy/abc?drive=main').set('authorization', 'Bearer sess-xyz')+ .set('x-request-id', REQUEST_ID)expect(res.status).toBe(200)const bytes = Buffer.isBuffer(res.body) ? res.body : Buffer.from(res.text ?? '')expect(bytes.toString('utf8')).toBe('hello')expect(clientMock.controlApiStreamRequest).toHaveBeenCalledWith('GET','/external/gfs/proxy/abc',- { userSessionToken: 'sess-xyz', query: { drive: 'main' } }+ {+ userSessionToken: 'sess-xyz',+ query: { drive: 'main' },+ extraHeaders: { 'x-request-id': REQUEST_ID },+ })})@@ -160,21 +174,25 @@ describe('routes/gfs /me/gfs/* (user session passthrough → /external/gfs/*)',await request(buildApp()).patch('/me/gfs/resources/abc?drive=main').set('authorization', 'Bearer sess-xyz')+ .set('x-request-id', REQUEST_ID).send({ newName: 'renamed.md', ifMatch: 1 }).expect(200)await request(buildApp()).post('/me/gfs/resources/abc/children?drive=main').set('authorization', 'Bearer sess-xyz')+ .set('x-request-id', REQUEST_ID).send({ name: 'docs', kind: 'directory' }).expect(201)await request(buildApp()).put('/me/gfs/resources/abc/content?drive=main').set('authorization', 'Bearer sess-xyz')+ .set('x-request-id', REQUEST_ID).send({ content: 'hello', ifMatch: 2 }).expect(200)await request(buildApp()).delete('/me/gfs/resources/abc?drive=main').set('authorization', 'Bearer sess-xyz')+ .set('x-request-id', REQUEST_ID).send({ ifMatch: 3 }).expect(200)@@ -186,6 +204,7 @@ describe('routes/gfs /me/gfs/* (user session passthrough → /external/gfs/*)',userSessionToken: 'sess-xyz',query: { drive: 'main' },body: { newName: 'renamed.md', ifMatch: 1 },+ extraHeaders: { 'x-request-id': REQUEST_ID },})expect(clientMock.controlApiRequest).toHaveBeenNthCalledWith(@@ -196,6 +215,7 @@ describe('routes/gfs /me/gfs/* (user session passthrough → /external/gfs/*)',userSessionToken: 'sess-xyz',query: { drive: 'main' },body: { name: 'docs', kind: 'directory' },+ extraHeaders: { 'x-request-id': REQUEST_ID },})expect(clientMock.controlApiRequest).toHaveBeenNthCalledWith(@@ -206,6 +226,7 @@ describe('routes/gfs /me/gfs/* (user session passthrough → /external/gfs/*)',userSessionToken: 'sess-xyz',query: { drive: 'main' },body: { content: 'hello', ifMatch: 2 },+ extraHeaders: { 'x-request-id': REQUEST_ID },})expect(clientMock.controlApiRequest).toHaveBeenNthCalledWith(@@ -216,6 +237,7 @@ describe('routes/gfs /me/gfs/* (user session passthrough → /external/gfs/*)',userSessionToken: 'sess-xyz',query: { drive: 'main' },body: { ifMatch: 3 },+ extraHeaders: { 'x-request-id': REQUEST_ID },})})@@ -224,6 +246,9 @@ describe('routes/gfs /me/gfs/* (user session passthrough → /external/gfs/*)',authTokenMock.verifyToken.mockReturnValue(null)const res = await request(buildApp()).post('/me/gfs/token').send({})expect(res.status).toBe(401)+ expect(res.headers['x-request-id']).toMatch(+ /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/+ )})})@@ -243,11 +268,13 @@ describe('GET /me/gfs/grants (delegation list passthrough)', () => {const res = await request(buildApp()).get('/me/gfs/grants?drive=main&resourceId=11111111-1111-1111-1111-111111111111').set('authorization', 'Bearer sess-xyz')+ .set('x-request-id', REQUEST_ID)expect(res.status).toBe(200)expect(res.body).toEqual({ items })expect(clientMock.controlApiRequest).toHaveBeenCalledWith('GET', '/external/gfs/grants', {userSessionToken: 'sess-xyz',query: { drive: 'main', resourceId: '11111111-1111-1111-1111-111111111111' },+ extraHeaders: { 'x-request-id': REQUEST_ID },})})@@ -276,3 +303,56 @@ describe('GET /me/gfs/grants (delegation list passthrough)', () => {expect(res.body).toEqual({ error: 'Too Many Requests', retryAfterSeconds: 17 })})})++describe('GET /me/gfs/shares (delegation list passthrough)', () => {+ it('forwards drive, resource, session, and request id without exposing an admin route', async () => {+ const items = [+ {+ id: 'aaaaaaaa-0000-4000-8000-000000000001',+ drive: 'main',+ resourceId: '11111111-1111-1111-1111-111111111111',+ subject: { type: 'user', id: '22222222-2222-4222-8222-222222222222' },+ permissions: ['read'],+ includeDescendants: true,+ },+ ]+ clientMock.controlApiRequest.mockResolvedValue({ items })++ const res = await request(buildApp())+ .get('/me/gfs/shares?drive=main&resourceId=11111111-1111-1111-1111-111111111111')+ .set('authorization', 'Bearer sess-xyz')+ .set('x-request-id', REQUEST_ID)++ expect(res.status).toBe(200)+ expect(res.body).toEqual({ items })+ expect(res.headers['x-request-id']).toBe(REQUEST_ID)+ expect(clientMock.controlApiRequest).toHaveBeenCalledWith('GET', '/external/gfs/shares', {+ userSessionToken: 'sess-xyz',+ query: { drive: 'main', resourceId: '11111111-1111-1111-1111-111111111111' },+ extraHeaders: { 'x-request-id': REQUEST_ID },+ })++ clientMock.controlApiRequest.mockClear()+ await request(buildApp())+ .get('/me/gfs/admin/shares')+ .set('authorization', 'Bearer sess-xyz')+ .expect(404)+ expect(clientMock.controlApiRequest).not.toHaveBeenCalled()+ })++ it.each([+ [401, 'unauthorized'],+ [403, 'manage_acl_required'],+ [503, 'gfs_authority_unavailable'],+ ] as const)('propagates %s %s verbatim with the same request id', async (status, error) => {+ clientMock.controlApiRequest.mockRejectedValue(new ControlApiError(error, status, { error }))+ const res = await request(buildApp())+ .get('/me/gfs/shares?drive=main&resourceId=11111111-1111-1111-1111-111111111111')+ .set('authorization', 'Bearer sess-xyz')+ .set('x-request-id', REQUEST_ID)++ expect(res.status).toBe(status)+ expect(res.body).toEqual({ error })+ expect(res.headers['x-request-id']).toBe(REQUEST_ID)+ })+})diff --git a/gfs-controller/src/api/copyRoute.ts b/gfs-controller/src/api/copyRoute.tsindex e6a382487..fad1a68b0 100644--- a/gfs-controller/src/api/copyRoute.ts+++ b/gfs-controller/src/api/copyRoute.ts@@ -1,6 +1,6 @@import type { GfsVerifiedClaims } from "../auth/verify";import type { AuditSink } from "../authz/audit";-import type { AuthzContext, AuthzQueryBudget, PermissionEpoch } from "../authz/permissionClient";+import { auditAttribution, type AuthzContext, type AuthzQueryBudget, type PermissionEpoch } from "../authz/permissionClient";import type { GfsPermission } from "../authz/resolve";import { checkTokenCeiling } from "../authz/tokenCeiling";import type { DeadlineBudget } from "../db/deadlineQuery";@@ -82,6 +82,7 @@ function checkDeadline(input: CopyRouteInput, deadlineAtMs: number, now: () => nasync function failedAudit(input: CopyRouteInput, sourceResourceId: string, error: unknown): Promise<void> {await input.deps.audit.record({recordType: "mutation_outcome", subject: input.context.primarySubject, op: "copy",+ ...auditAttribution(input.context),resourceId: sourceResourceId, drive: input.claims.drive, outcome: "error",reason: error instanceof GfsError ? error.code : "internal_error", requestId: input.requestId,matchedSubject: null, authorizationSource: null, cachedAuthorizationSource: null,@@ -168,6 +169,7 @@ export async function executeCopyRoute(input: CopyRouteInput): Promise<Record<stpublicationCalled = true;const published = await input.deps.writes.copy({requestId: input.requestId, subject: input.context.primarySubject, audit: input.deps.audit,+ ...auditAttribution(input.context),drive: input.claims.drive, destinationParentId, plan, destination, deadlineAtMs,signal: input.signal, now: relativeNow,authzEpoch: { captured: authzEpochCaptured, current: input.deps.permissionEpoch },diff --git a/gfs-controller/src/api/renameRoute.ts b/gfs-controller/src/api/renameRoute.tsindex 07ce41364..af2398f52 100644--- a/gfs-controller/src/api/renameRoute.ts+++ b/gfs-controller/src/api/renameRoute.ts@@ -1,6 +1,6 @@import type { GfsVerifiedClaims } from "../auth/verify";import type { AuditSink } from "../authz/audit";-import type { AuthzContext } from "../authz/permissionClient";+import { auditAttribution, type AuthzContext } from "../authz/permissionClient";import type { GfsWriteService } from "../db/writeStore";import { GfsError } from "./errors";import { toView } from "./read";@@ -46,6 +46,7 @@ export async function executeRenameRoute(input: RenameRouteInput): Promise<Retur}const updated = await input.writes.rename({requestId: input.requestId, subject: input.context.primarySubject, audit: input.audit,+ ...auditAttribution(input.context),drive, resourceId: input.resourceId, newName, ifMatch: Number(ifMatch),maxObjects: input.limits.maxObjects, deadlineAtMs: Date.now() + input.limits.timeoutMs,});diff --git a/gfs-controller/src/api/serve.test.ts b/gfs-controller/src/api/serve.test.tsindex 9835db416..31e73dec5 100644--- a/gfs-controller/src/api/serve.test.ts+++ b/gfs-controller/src/api/serve.test.ts@@ -370,6 +370,66 @@ function writeDeps(over: Partial<ServingDeps> = {}): { d: ServingDeps; calls: Ar}describe("GfsServingHandler — write routes (governed mutation)", () => {+ it("keeps linked actor, effective admin, token subject, and request id distinct through publication", async () => {+ const desktopUserId = "11111111-1111-4111-8111-111111111111";+ const controlAdminId = "22222222-2222-4222-8222-222222222222";+ const requestId = "33333333-3333-4333-8333-333333333333";+ const brokeredAuthority = {+ desktopUserId,+ controlAdminId,+ authoritySource: "linked-admin" as const,+ };+ const linkedClaims: GfsVerifiedClaims = {+ ...USER_WRITE_CLAIMS,+ sub: controlAdminId,+ principalType: "control-admin",+ brokeredAuthority,+ };+ const linkedContext: AuthzContext = {+ drive: "main",+ subjects: ["operator:"],+ isOperator: true,+ primarySubject: controlAdminId,+ effectiveControlAdminId: controlAdminId,+ desktopUserId,+ authoritySource: "linked-admin",+ requestId,+ };+ const { d, calls } = writeDeps({+ verifyToken: () => linkedClaims,+ resolveContext: async (claims, resolvedRequestId) => {+ expect(claims).toEqual({+ sub: controlAdminId,+ drive: "main",+ principalType: "control-admin",+ brokeredAuthority,+ });+ expect(resolvedRequestId).toBe(requestId);+ return linkedContext;+ },+ });+ const request = reqBody(`/v1/resources/${RID}/children`, {+ method: "POST",+ auth: "Bearer t",+ body: { name: "linked.txt", content: "hi" },+ });+ request.headers["x-request-id"] = requestId;++ const res = new FakeRes();+ await run(d, request, res);++ expect(res.statusCode).toBe(201);+ expect(calls[0].input).toMatchObject({+ mutation: {+ subject: controlAdminId,+ requestId,+ actorOnBehalfOf: controlAdminId,+ desktopUserId,+ authoritySource: "linked-admin",+ },+ });+ });+it("does not expose internal blob keys or physical paths in a failure response", async () => {const res = new FakeRes();const { d } = writeDeps({diff --git a/gfs-controller/src/api/serve.ts b/gfs-controller/src/api/serve.tsindex c440f3e65..21acf3f52 100644--- a/gfs-controller/src/api/serve.ts+++ b/gfs-controller/src/api/serve.ts@@ -1,7 +1,7 @@import { randomUUID } from "node:crypto";import type { IncomingMessage, ServerResponse } from "node:http";import type { GfsMetrics } from "../metrics";-import type { AuthzContext } from "../authz/permissionClient";+import { auditAttribution, type AuthzContext } from "../authz/permissionClient";import type { AuditSink } from "../authz/audit";import type { AccessibleResourcePage } from "../authz/accessibleStore";import type { GfsPermission } from "../authz/resolve";@@ -68,7 +68,7 @@ export function sanitizeForLog(value: string): string {export interface ServingDeps {verifyToken: (token: string) => GfsVerifiedClaims;resolveContext: (- claims: { sub: string; drive: string },+ claims: Pick<GfsVerifiedClaims, "sub" | "drive" | "brokeredAuthority" | "principalType">,requestId?: string) => Promise<AuthzContext>;/** Permission-store authorization (the source of truth). */@@ -354,7 +354,12 @@ export class GfsServingHandler {private async authContext(claims: GfsVerifiedClaims, req: IncomingMessage, admittedRequestId?: string): Promise<AuthzContext> {const requestId = admittedRequestId ?? headerValue(req, "x-request-id");try {- return await this.deps.resolveContext({ sub: claims.sub, drive: claims.drive }, requestId);+ return await this.deps.resolveContext({+ sub: claims.sub,+ drive: claims.drive,+ ...(claims.brokeredAuthority ? { brokeredAuthority: claims.brokeredAuthority } : {}),+ ...(claims.principalType ? { principalType: claims.principalType } : {}),+ }, requestId);} catch (err) {throw new GfsError("not_mounted",@@ -539,7 +544,12 @@ export class GfsServingHandler {const created = await this.deps.writeService!.create({drive: claims.drive, parentId, name, kind, content,- mutation: { subject: ctx.primarySubject, requestId, audit: this.deps.audit! },+ mutation: {+ subject: ctx.primarySubject,+ requestId,+ audit: this.deps.audit!,+ ...auditAttribution(ctx),+ },});sendJson(res, 201, ok(toView(created)));}@@ -563,7 +573,12 @@ export class GfsServingHandler {const updated = await this.deps.writeService!.replace({drive: claims.drive, resourceId, ifMatch, content,- mutation: { subject: ctx.primarySubject, requestId, audit: this.deps.audit! },+ mutation: {+ subject: ctx.primarySubject,+ requestId,+ audit: this.deps.audit!,+ ...auditAttribution(ctx),+ },});sendJson(res, 200, ok(toView(updated)));}diff --git a/gfs-controller/src/auth/verify.test.ts b/gfs-controller/src/auth/verify.test.tsindex 42932f094..eae62d8f6 100644--- a/gfs-controller/src/auth/verify.test.ts+++ b/gfs-controller/src/auth/verify.test.ts@@ -48,6 +48,14 @@ const goodPayload = {pathBindings: [{ path: "/org", permissions: ["read"] }],};+const DESKTOP_USER_ID = "11111111-1111-4111-8111-111111111111";+const CONTROL_ADMIN_ID = "22222222-2222-4222-8222-222222222222";+const linkedAdminAuthority = {+ desktopUserId: DESKTOP_USER_ID,+ controlAdminId: CONTROL_ADMIN_ID,+ authoritySource: "linked-admin",+};+describe("loadVerificationKey", () => {it("FAILS CLOSED when the public key is absent", () => {expect(() => loadVerificationKey("")).toThrow(KeyConfigError);@@ -127,6 +135,62 @@ describe("verifyGfsToken", () => {it("REJECTS a garbage token string", () => {expect(() => verifyGfsToken("not-a-jwt", { key, audience: AUD })).toThrow(GfsAuthError);});++ it("accepts a complete signed linked-admin broker claim without conflating token subject and actor", () => {+ const claims = verifyGfsToken(+ sign({+ ...goodPayload,+ sub: CONTROL_ADMIN_ID,+ principalType: "control-admin",+ brokeredAuthority: linkedAdminAuthority,+ }),+ { key, audience: AUD }+ );++ expect(claims.sub).toBe(CONTROL_ADMIN_ID);+ expect(claims.brokeredAuthority).toEqual(linkedAdminAuthority);+ });++ it.each([+ { desktopUserId: DESKTOP_USER_ID, controlAdminId: CONTROL_ADMIN_ID },+ { ...linkedAdminAuthority, authoritySource: "user-session" },+ { ...linkedAdminAuthority, desktopUserId: "not-a-uuid" },+ { ...linkedAdminAuthority, controlAdminId: "not-a-uuid" },+ ])("rejects malformed brokered authority metadata: %j", brokeredAuthority => {+ const token = sign({ ...goodPayload, sub: CONTROL_ADMIN_ID, brokeredAuthority });+ expect(() => verifyGfsToken(token, { key, audience: AUD })).toThrow(GfsAuthError);+ });++ it("rejects broker metadata whose effective admin differs from the signed token subject", () => {+ const token = sign({+ ...goodPayload,+ sub: DESKTOP_USER_ID,+ principalType: "control-admin",+ brokeredAuthority: linkedAdminAuthority,+ });+ expect(() => verifyGfsToken(token, { key, audience: AUD })).toThrow(GfsAuthError);+ });++ it("rejects broker metadata without explicit control-admin provenance", () => {+ const token = sign({+ ...goodPayload,+ sub: CONTROL_ADMIN_ID,+ brokeredAuthority: linkedAdminAuthority,+ });+ expect(() => verifyGfsToken(token, { key, audience: AUD })).toThrow(+ /requires control-admin principalType/+ );+ });++ it("accepts the signed user principal marker and rejects unknown markers", () => {+ expect(+ verifyGfsToken(sign({ ...goodPayload, principalType: "user" }), { key, audience: AUD })+ .principalType+ ).toBe("user");+ expect(() =>+ verifyGfsToken(sign({ ...goodPayload, principalType: "operator" }), { key, audience: AUD })+ ).toThrow(/invalid principalType/);+ });});describe("verifyGfsToken lifetime claim requirements", () => {diff --git a/gfs-controller/src/auth/verify.ts b/gfs-controller/src/auth/verify.tsindex 0aeff1672..6c77e13fc 100644--- a/gfs-controller/src/auth/verify.ts+++ b/gfs-controller/src/auth/verify.ts@@ -21,15 +21,55 @@ export interface GfsPathBinding {permissions: string[];}+export interface GfsBrokeredAuthority {+ desktopUserId: string;+ controlAdminId: string;+ authoritySource: "linked-admin";+}+export interface GfsVerifiedClaims {sub: string;drive: string;scopes: GfsScope[];pathBindings: GfsPathBinding[];+ brokeredAuthority?: GfsBrokeredAuthority;+ principalType?: "user" | "control-admin";iat: number;exp: number;}+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++function parseBrokeredAuthority(raw: unknown, sub: string): GfsBrokeredAuthority | undefined {+ if (raw === undefined || raw === null) return undefined;+ if (typeof raw !== "object" || Array.isArray(raw)) {+ throw new GfsAuthError("brokeredAuthority must be an object");+ }+ const record = raw as Record<string, unknown>;+ if (Object.keys(record).sort().join(",") !== "authoritySource,controlAdminId,desktopUserId") {+ throw new GfsAuthError("brokeredAuthority must contain exactly the supported fields");+ }+ const desktopUserId = record.desktopUserId;+ const controlAdminId = record.controlAdminId;+ if (typeof desktopUserId !== "string" || !UUID_RE.test(desktopUserId)) {+ throw new GfsAuthError("brokeredAuthority.desktopUserId must be a UUID");+ }+ if (typeof controlAdminId !== "string" || !UUID_RE.test(controlAdminId)) {+ throw new GfsAuthError("brokeredAuthority.controlAdminId must be a UUID");+ }+ if (record.authoritySource !== "linked-admin") {+ throw new GfsAuthError("brokeredAuthority.authoritySource is invalid");+ }+ if (sub.toLowerCase() !== controlAdminId.toLowerCase()) {+ throw new GfsAuthError("brokeredAuthority control admin must match token sub");+ }+ return {+ desktopUserId: desktopUserId.toLowerCase(),+ controlAdminId: controlAdminId.toLowerCase(),+ authoritySource: "linked-admin",+ };+}+export class GfsAuthError extends Error {readonly code = "unauthorized";constructor(message: string) {@@ -119,12 +159,16 @@ export function verifyGfsToken(token: string, opts: VerifyOptions): GfsVerifiedCconst rawScopes = record.scopes;const iat = record.iat;const exp = record.exp;+ const principalType = record.principalType;if (typeof sub !== "string" || sub.length === 0) throw new GfsAuthError("missing sub");if (typeof drive !== "string" || drive.length === 0) throw new GfsAuthError("missing drive");if (!Array.isArray(rawScopes)) throw new GfsAuthError("missing scopes");if (!Number.isSafeInteger(iat)) throw new GfsAuthError("missing or invalid iat");if (!Number.isSafeInteger(exp)) throw new GfsAuthError("missing or invalid exp");+ if (principalType !== undefined && principalType !== "user" && principalType !== "control-admin") {+ throw new GfsAuthError("invalid principalType");+ }const issuedAt = iat as number;const expiresAt = exp as number;if (expiresAt <= issuedAt) throw new GfsAuthError("token exp must be after iat");@@ -137,11 +181,18 @@ export function verifyGfsToken(token: string, opts: VerifyOptions): GfsVerifiedCscopes.push(scope as GfsScope);}+ const brokeredAuthority = parseBrokeredAuthority(record.brokeredAuthority, sub);+ if (brokeredAuthority && principalType !== "control-admin") {+ throw new GfsAuthError("brokeredAuthority requires control-admin principalType");+ }+return {sub,drive,scopes,pathBindings: parsePathBindings(record.pathBindings),+ ...(brokeredAuthority ? { brokeredAuthority } : {}),+ ...(principalType ? { principalType } : {}),iat: issuedAt,exp: expiresAt,};diff --git a/gfs-controller/src/authz/audit.ts b/gfs-controller/src/authz/audit.tsindex 3681cfcce..d7d4f3a8e 100644--- a/gfs-controller/src/authz/audit.ts+++ b/gfs-controller/src/authz/audit.ts@@ -29,6 +29,12 @@ export type AuthorizationEvidence =interface AuditEventBase {subject: string;+ /** Effective Control Admin for linked-admin brokerage; null otherwise. */+ actorOnBehalfOf?: string | null;+ /** Authenticated Desktop actor for user-session and linked-admin requests. */+ desktopUserId?: string;+ /** Request authority provenance, distinct from permission-store evidence. */+ authoritySource?: "user-session" | "linked-admin";op: string;resourceId: string;drive: string;@@ -72,6 +78,9 @@ export class DbAuditSink implements AuditSink {.update(JSON.stringify([event.subject,+ event.actorOnBehalfOf ?? null,+ event.desktopUserId ?? null,+ event.authoritySource ?? null,event.op,gfsUri,event.outcome,@@ -88,12 +97,13 @@ export class DbAuditSink implements AuditSink {const append = (target: Queryable) => target.query(`INSERT INTO gfs_audit- (subject, op, gfs_uri, outcome, request_id, row_hash, record_type,+ (subject, actor_on_behalf_of, op, gfs_uri, outcome, request_id, row_hash, record_type,matched_subject, authorization_source, cached_authorization_source,- mutation_outcome)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,+ mutation_outcome, desktop_user_id, authority_source)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13::uuid, $14)`,[event.subject,+ event.actorOnBehalfOf ?? null,event.op,gfsUri,event.outcome,@@ -104,6 +114,8 @@ export class DbAuditSink implements AuditSink {event.authorizationSource,event.cachedAuthorizationSource,event.mutationOutcome,+ event.desktopUserId ?? null,+ event.authoritySource ?? null,]);diff --git a/gfs-controller/src/authz/dbAuditSink.test.ts b/gfs-controller/src/authz/dbAuditSink.test.tsindex 238dd6159..20c199522 100644--- a/gfs-controller/src/authz/dbAuditSink.test.ts+++ b/gfs-controller/src/authz/dbAuditSink.test.ts@@ -53,6 +53,7 @@ describe("DbAuditSink", () => {);expect(db.values).toEqual(["agent:reader-1",+ null,"read","gfs://main/resource-id","allow",@@ -63,9 +64,44 @@ describe("DbAuditSink", () => {"direct_grant",null,null,+ null,+ null,]);expect(db.text).not.toMatch(/\b(path|name|blob_key)\b/);- expect(String(db.values[5])).toMatch(/^[0-9a-f]{64}$/);+ expect(String(db.values[6])).toMatch(/^[0-9a-f]{64}$/);+ });++ it("persists linked Desktop actor and effective Control Admin without overloading store evidence", async () => {+ const db = new AuditDb();+ await new DbAuditSink(db).record({+ ...directDecision,+ subject: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",+ actorOnBehalfOf: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",+ desktopUserId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",+ authoritySource: "linked-admin",+ authorizationSource: "operator",+ matchedSubject: "operator:",+ });++ expect(db.text).toContain("actor_on_behalf_of");+ expect(db.text).toContain("desktop_user_id");+ expect(db.text).toContain("authority_source");+ expect(db.values).toEqual([+ "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",+ "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",+ "read",+ "gfs://main/resource-id",+ "allow",+ "req-7",+ expect.stringMatching(/^[0-9a-f]{64}$/),+ "authorization_decision",+ "operator:",+ "operator",+ null,+ null,+ "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",+ "linked-admin",+ ]);});it("persists cache attribution and includes it in the deterministic hash", async () => {@@ -82,15 +118,15 @@ describe("DbAuditSink", () => {await new DbAuditSink(repeated).record(cachedDecision);await new DbAuditSink(direct).record(directDecision);- expect(first.values.slice(6, 11)).toEqual([+ expect(first.values.slice(7, 12)).toEqual(["authorization_decision","agent:reader-1","cache","direct_grant",null,]);- expect(first.values[5]).toBe(repeated.values[5]);- expect(first.values[5]).not.toBe(direct.values[5]);+ expect(first.values[6]).toBe(repeated.values[6]);+ expect(first.values[6]).not.toBe(direct.values[6]);});it("uses a supplied transaction client instead of the default pool", async () => {@@ -102,8 +138,9 @@ describe("DbAuditSink", () => {expect(pool.text).toBe("");expect(pool.values).toEqual([]);expect(transaction.text).toContain("INSERT INTO gfs_audit");- expect(transaction.values.slice(0, 4)).toEqual([+ expect(transaction.values.slice(0, 5)).toEqual(["agent:reader-1",+ null,"read","gfs://main/resource-id","allow",@@ -120,7 +157,7 @@ describe("DbAuditSink", () => {mutationOutcome: "failed",});- expect(db.values.slice(6, 11)).toEqual([+ expect(db.values.slice(7, 12)).toEqual(["mutation_outcome","agent:reader-1","direct_grant",diff --git a/gfs-controller/src/authz/permissionClient.ts b/gfs-controller/src/authz/permissionClient.tsindex 484470962..0e6d1644d 100644--- a/gfs-controller/src/authz/permissionClient.ts+++ b/gfs-controller/src/authz/permissionClient.ts@@ -33,6 +33,26 @@ export interface AuthzContext {/** The token's `sub`, recorded verbatim in the audit row. */primarySubject: string;requestId?: string;+ /** Desktop actor for a user-session or linked-admin broker request. */+ desktopUserId?: string;+ /** Effective linked Control Admin. Absent for ordinary users/direct admins. */+ effectiveControlAdminId?: string;+ /** Broker authority provenance; separate from permission-store evidence. */+ authoritySource?: "user-session" | "linked-admin";+}++export function auditAttribution(ctx: AuthzContext): {+ actorOnBehalfOf: string | null;+ desktopUserId?: string;+ authoritySource?: "user-session" | "linked-admin";+} {+ return {+ actorOnBehalfOf: ctx.authoritySource === "linked-admin"+ ? (ctx.effectiveControlAdminId ?? null)+ : null,+ desktopUserId: ctx.desktopUserId,+ authoritySource: ctx.authoritySource,+ };}export interface AuthorizationRequest {@@ -179,6 +199,7 @@ export class PermissionClient {const append = async (queryable?: Queryable) => {for (const request of requests) await this.audit.record({subject: ctx.primarySubject,+ ...auditAttribution(ctx),op: request.op,resourceId: request.resourceId,drive: ctx.drive,@@ -253,6 +274,7 @@ export class PermissionClient {};await this.audit.record({subject: ctx.primarySubject,+ ...auditAttribution(ctx),op,resourceId,drive: ctx.drive,diff --git a/gfs-controller/src/authz/subjectResolver.test.ts b/gfs-controller/src/authz/subjectResolver.test.tsindex b0c8346af..ea801dc22 100644--- a/gfs-controller/src/authz/subjectResolver.test.ts+++ b/gfs-controller/src/authz/subjectResolver.test.ts@@ -63,7 +63,11 @@ describe("resolveAuthzContext (spec §Subjects — check-time resolution)", () =it("grants intrinsic operator authority when sub is in control_admin_users", async () => {const opId = "11111111-1111-1111-1111-111111111111";const db = fakeDb({ operators: new Set([opId]) });- const ctx = await resolveAuthzContext(db, { sub: opId, drive: "main" });+ const ctx = await resolveAuthzContext(db, {+ sub: opId,+ drive: "main",+ principalType: "control-admin",+ });expect(ctx.isOperator).toBe(true);expect(ctx.subjects).toEqual(["operator:"]);expect(ctx.primarySubject).toBe(opId);@@ -71,6 +75,77 @@ describe("resolveAuthzContext (spec §Subjects — check-time resolution)", () =expect(db.calls.some((q) => q.includes("team_members"))).toBe(false);});+ it("keeps an unmarked colliding UUID on the conservative user path", async () => {+ const collidingId = "88888888-8888-4888-8888-888888888888";+ const db = fakeDb({ operators: new Set([collidingId]) });+ const ctx = await resolveAuthzContext(db, { sub: collidingId, drive: "main" });+ expect(ctx.isOperator).toBe(false);+ expect(ctx.subjects).toEqual([`user:${collidingId}`]);+ expect(db.calls.some(query => query.includes("control_admin_users"))).toBe(false);+ });++ it("never elevates a signed user principal whose UUID also exists in the admin table", async () => {+ const collidingId = "99999999-9999-4999-8999-999999999999";+ const db = fakeDb({+ operators: new Set([collidingId]),+ teamsByUser: { [collidingId]: ["team-user"] },+ });++ const ctx = await resolveAuthzContext(db, {+ sub: collidingId,+ drive: "main",+ principalType: "user",+ });++ expect(ctx.isOperator).toBe(false);+ expect(ctx.subjects).toEqual([`user:${collidingId}`, "team:team-user"]);+ expect(ctx.authoritySource).toBe("user-session");+ expect(db.calls.some(query => query.includes("control_admin_users"))).toBe(false);+ });++ it("preserves linked Desktop actor, effective admin, source, token subject, and request id", async () => {+ const desktopUserId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";+ const controlAdminId = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";+ const db = fakeDb({ operators: new Set([controlAdminId]) });++ const ctx = await resolveAuthzContext(db, {+ sub: controlAdminId,+ drive: "main",+ brokeredAuthority: {+ desktopUserId,+ controlAdminId,+ authoritySource: "linked-admin",+ },+ }, "cccccccc-cccc-4ccc-8ccc-cccccccccccc");++ expect(ctx).toEqual({+ drive: "main",+ subjects: ["operator:"],+ isOperator: true,+ primarySubject: controlAdminId,+ effectiveControlAdminId: controlAdminId,+ desktopUserId,+ authoritySource: "linked-admin",+ requestId: "cccccccc-cccc-4ccc-8ccc-cccccccccccc",+ });+ });++ it("fails closed when a signed linked-admin claim names an inactive or missing admin", async () => {+ const controlAdminId = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";+ const db = fakeDb({});++ await expect(resolveAuthzContext(db, {+ sub: controlAdminId,+ drive: "main",+ brokeredAuthority: {+ desktopUserId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",+ controlAdminId,+ authoritySource: "linked-admin",+ },+ })).rejects.toThrow("linked admin is not active");+ expect(db.calls.some((q) => q.includes("team_members"))).toBe(false);+ });+it("resolves a user to itself plus its ACTIVE team memberships", async () => {const userId = "22222222-2222-2222-2222-222222222222";const db = fakeDb({ teamsByUser: { [userId]: ["team-a", "team-b"] } });@@ -85,6 +160,9 @@ describe("resolveAuthzContext (spec §Subjects — check-time resolution)", () =const db = fakeDb({});const ctx = await resolveAuthzContext(db, { sub: userId, drive: "main" });expect(ctx.subjects).toEqual([`user:${userId}`]);+ expect(ctx.desktopUserId).toBe(userId);+ expect(ctx.authoritySource).toBe("user-session");+ expect(ctx.effectiveControlAdminId).toBeUndefined();});it("propagates a store error (fail-closed — never a silent allow)", async () => {diff --git a/gfs-controller/src/authz/subjectResolver.ts b/gfs-controller/src/authz/subjectResolver.tsindex 320253d9b..9652e51b8 100644--- a/gfs-controller/src/authz/subjectResolver.ts+++ b/gfs-controller/src/authz/subjectResolver.ts@@ -1,4 +1,5 @@import { AuthzContext } from "./permissionClient";+import type { GfsBrokeredAuthority } from "../auth/verify";/*** Check-time subject resolution for gfsc (spec community.md §Subjects, §Auth).@@ -11,12 +12,10 @@ import { AuthzContext } from "./permissionClient";* queries the store directly), so the resolution happens here, not in the token.** Principal grammar (spec §gfs access token `sub`):- * - `<uuid>` → a human. Two DISJOINT pools: an operator mints with- * `sub = control_admin_users.id`; a user with- * `sub = users.id`. gfsc probes control_admin_users to- * distinguish — an operator gets intrinsic authority +- * `operator:`; a user gets `user:<id>` plus its active- * `team:` memberships.+ * - `<uuid>` → a human. The signed `principalType` distinguishes+ * a Control Admin from a user; an omitted marker is+ * conservatively a user. Linked-admin metadata is+ * validated separately and rechecks active admin state.* - `host:1st:<ns>/<name>` → 1st-party Host (HCC). subjects = { sub }* - `host:3rd:<ns>/<name>` → 3rd-party recipe mcp-host (WRC). subjects = { sub }*@@ -56,11 +55,33 @@ async function isOperatorId(db: SubjectsDb, adminId: string): Promise<boolean> {*/export async function resolveAuthzContext(db: SubjectsDb,- claims: { sub: string; drive: string },+ claims: {+ sub: string;+ drive: string;+ brokeredAuthority?: GfsBrokeredAuthority;+ principalType?: "user" | "control-admin";+ },requestId?: string): Promise<AuthzContext> {const sub = claims.sub;+ if (claims.brokeredAuthority) {+ const brokered = claims.brokeredAuthority;+ if (brokered.controlAdminId !== sub || !(await isOperatorId(db, brokered.controlAdminId))) {+ throw new Error("linked admin is not active");+ }+ return {+ drive: claims.drive,+ subjects: ["operator:"],+ isOperator: true,+ primarySubject: sub,+ effectiveControlAdminId: brokered.controlAdminId,+ desktopUserId: brokered.desktopUserId,+ authoritySource: "linked-admin",+ requestId,+ };+ }+// Host principal — the `sub` IS the canonical subject key; no group resolution// in v1 (the host→context binding is a P3+ follow-up, deny-by-default until// `context` is a first-class grantee).@@ -68,15 +89,22 @@ export async function resolveAuthzContext(return { drive: claims.drive, subjects: [sub], isOperator: false, primarySubject: sub, requestId };}- // Human principal — a bare id. The operator pool and the user pool are disjoint- // UUID spaces, so a single probe of control_admin_users distinguishes them.- if (await isOperatorId(db, sub)) {- // Intrinsic authority; `authorize()` short-circuits on isOperator so the- // subject set is only recorded, but resolving to `operator:` keeps it honest.- return { drive: claims.drive, subjects: ["operator:"], isOperator: true, primarySubject: sub, requestId };+ if (claims.principalType === "control-admin") {+ if (!(await isOperatorId(db, sub))) throw new Error("control admin is not active");+ return {+ drive: claims.drive,+ subjects: ["operator:"],+ isOperator: true,+ primarySubject: sub,+ requestId,+ };}- // Otherwise a user: itself plus every team it is an ACTIVE member of+ // Every remaining bare principal is resolved conservatively as a user. An+ // omitted marker never probes the admin table: only an explicit signed+ // control-admin marker (or validated broker metadata above) can elevate.+ // This also keeps legacy/unmarked user tokens fail-closed during rollout.+ // A user resolves to itself plus every team it is an ACTIVE member of// (soft-deleted memberships excluded — deny-by-default).const subjects = new Set<string>([`user:${sub}`]);const res = await db.query(@@ -86,5 +114,13 @@ export async function resolveAuthzContext(for (const row of res.rows) {subjects.add(`team:${String(row.team_id)}`);}- return { drive: claims.drive, subjects: [...subjects], isOperator: false, primarySubject: sub, requestId };+ return {+ drive: claims.drive,+ subjects: [...subjects],+ isOperator: false,+ primarySubject: sub,+ desktopUserId: sub,+ authoritySource: "user-session",+ requestId,+ };}diff --git a/gfs-controller/src/db/copyPublication.ts b/gfs-controller/src/db/copyPublication.tsindex eca730e55..acbcbeada 100644--- a/gfs-controller/src/db/copyPublication.ts+++ b/gfs-controller/src/db/copyPublication.ts@@ -239,6 +239,9 @@ function auditEvent(input: CopyInput, resourceId: string, mutationOutcome: "succreturn {recordType: "mutation_outcome" as const,subject: input.subject,+ actorOnBehalfOf: input.actorOnBehalfOf ?? null,+ desktopUserId: input.desktopUserId,+ authoritySource: input.authoritySource,op: "copy",resourceId: normalizeResourceId(resourceId),drive: input.drive,diff --git a/gfs-controller/src/db/managedMutationAudit.test.ts b/gfs-controller/src/db/managedMutationAudit.test.tsnew file mode 100644index 000000000..0101219e2--- /dev/null+++ b/gfs-controller/src/db/managedMutationAudit.test.ts@@ -0,0 +1,71 @@+import { describe, expect, it, vi } from "vitest";+import type { AuditSink } from "../authz/audit";+import { recordManagedMutation } from "./managedMutationAudit";++describe("recordManagedMutation actor correlation", () => {+ it("persists linked authority on the mutation row with the same request id", async () => {+ const record = vi.fn<AuditSink["record"]>().mockResolvedValue(undefined);+ const desktopUserId = "11111111-1111-4111-8111-111111111111";+ const controlAdminId = "22222222-2222-4222-8222-222222222222";+ const requestId = "33333333-3333-4333-8333-333333333333";++ await recordManagedMutation(+ {+ subject: controlAdminId,+ requestId,+ audit: { record },+ actorOnBehalfOf: controlAdminId,+ desktopUserId,+ authoritySource: "linked-admin",+ },+ { op: "create", resourceId: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", drive: "main" },+ "succeeded"+ );++ expect(record).toHaveBeenCalledWith(+ expect.objectContaining({+ subject: controlAdminId,+ actorOnBehalfOf: controlAdminId,+ desktopUserId,+ authoritySource: "linked-admin",+ requestId,+ op: "create",+ outcome: "allow",+ recordType: "mutation_outcome",+ mutationOutcome: "succeeded",+ }),+ undefined+ );+ });++ it("persists ordinary Desktop authority with no effective admin", async () => {+ const record = vi.fn<AuditSink["record"]>().mockResolvedValue(undefined);+ const desktopUserId = "11111111-1111-4111-8111-111111111111";++ await recordManagedMutation(+ {+ subject: desktopUserId,+ requestId: "33333333-3333-4333-8333-333333333333",+ audit: { record },+ actorOnBehalfOf: null,+ desktopUserId,+ authoritySource: "user-session",+ },+ { op: "replace", resourceId: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", drive: "main" },+ "failed",+ "precondition_failed"+ );++ expect(record).toHaveBeenCalledWith(+ expect.objectContaining({+ subject: desktopUserId,+ actorOnBehalfOf: null,+ desktopUserId,+ authoritySource: "user-session",+ recordType: "mutation_outcome",+ mutationOutcome: "failed",+ }),+ undefined+ );+ });+});diff --git a/gfs-controller/src/db/managedMutationAudit.ts b/gfs-controller/src/db/managedMutationAudit.tsindex 86a1bba01..c093c3dac 100644--- a/gfs-controller/src/db/managedMutationAudit.ts+++ b/gfs-controller/src/db/managedMutationAudit.ts@@ -7,6 +7,9 @@ export interface ManagedMutationContext {subject: string;requestId: string;audit: AuditSink;+ actorOnBehalfOf?: string | null;+ desktopUserId?: string;+ authoritySource?: "user-session" | "linked-admin";}export async function recordManagedMutation(@@ -19,6 +22,9 @@ export async function recordManagedMutation(if (!context) return;await context.audit.record({recordType: "mutation_outcome", subject: context.subject, op: input.op,+ actorOnBehalfOf: context.actorOnBehalfOf ?? null,+ desktopUserId: context.desktopUserId,+ authoritySource: context.authoritySource,resourceId: normalizeResourceId(input.resourceId), drive: input.drive,outcome: outcome === "succeeded" ? "allow" : "error", reason,requestId: context.requestId, matchedSubject: null, authorizationSource: null,diff --git a/gfs-controller/src/db/renamePublication.ts b/gfs-controller/src/db/renamePublication.tsindex 3954e4ffa..2edfbef17 100644--- a/gfs-controller/src/db/renamePublication.ts+++ b/gfs-controller/src/db/renamePublication.ts@@ -11,6 +11,9 @@ export interface RenameInput {requestId: string;subject: string;audit: AuditSink;+ actorOnBehalfOf?: string | null;+ desktopUserId?: string;+ authoritySource?: "user-session" | "linked-admin";drive: string;resourceId: string;newName: string;@@ -172,6 +175,9 @@ function buildPaths(tree: readonly Row[], root: Row, parentPath: string, newNamefunction auditEvent(input: RenameInput, outcome: "succeeded" | "failed", reason?: string) {return {recordType: "mutation_outcome" as const, subject: input.subject, op: "rename",+ actorOnBehalfOf: input.actorOnBehalfOf ?? null,+ desktopUserId: input.desktopUserId,+ authoritySource: input.authoritySource,resourceId: normalizeResourceId(input.resourceId), drive: input.drive,outcome: outcome === "succeeded" ? "allow" as const : "error" as const,reason, requestId: input.requestId, matchedSubject: null,diff --git a/gfs-controller/src/db/writeStore.ts b/gfs-controller/src/db/writeStore.tsindex c12af53f9..455f1b851 100644--- a/gfs-controller/src/db/writeStore.ts+++ b/gfs-controller/src/db/writeStore.ts@@ -212,6 +212,9 @@ export interface CopyInput {requestId: string;subject: string;audit: AuditSink;+ actorOnBehalfOf?: string | null;+ desktopUserId?: string;+ authoritySource?: "user-session" | "linked-admin";drive: string;destinationParentId: string;plan: CopyPreflightPlan;