Skip to content

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

TypeScript

Merge remote-tracking branch 'origin/dev' into codex/issue-160-agent-grant-cas

Josué553f591b862d
diff --cc control-api/package-lock.json
index 96de124bf,96de124bf..ff14bc2b4
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@@ -1,12 -1,12 +1,12 @@@
{
"name": "clerum-control-api",
-- "version": "0.1.366",
++ "version": "0.1.367",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
-- "version": "0.1.366",
++ "version": "0.1.367",
"dependencies": {
"@clerum/image-policy": "file:../packages/image-policy",
"@clerum/llm-providers": "file:../packages/llm-providers",
diff --cc control-api/package.json
index c394516e6,c394516e6..2a655b11c
--- a/control-api/package.json
+++ b/control-api/package.json
@@@ -1,6 -1,6 +1,6 @@@
{
"name": "clerum-control-api",
-- "version": "0.1.366",
++ "version": "0.1.367",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --cc control-api/src/gfs/legacyStandaloneGrantMigration.ts
index 000000000,05e3fcd4c..5f423ac27
mode 000000,100644..100644
--- a/control-api/src/gfs/legacyStandaloneGrantMigration.ts
+++ b/control-api/src/gfs/legacyStandaloneGrantMigration.ts
@@@ -1,0 -1,233 +1,240 @@@
+ export const LEGACY_STANDALONE_SUBJECT_KEY = 'host:1st:mcp-host/standalone'
+
+ export interface LegacyGrantMigrationApi {
+ getLegacyGrants(): Promise<unknown>
+ getTrustedHostDirectory(): Promise<unknown>
+ putGrant(body: Record<string, unknown>): Promise<{ ok: boolean; status?: number; error?: string }>
+ }
+
+ export interface LegacyGrantInventoryItem {
+ id: string
+ drive: string
+ resourceId: string
+ permissions: string[]
+ inherit: boolean
+ }
+
+ export interface TrustedHostCandidate {
+ name: string
+ namespace: string
+ displayName: string
+ active: true
+ gfsSubject: { type: 'host'; id: string }
+ }
+
+ const K8S_NAME_RE = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/
+ const UUID_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
+ const MAX_INVENTORY_ITEMS = 1000
+ const MAX_TARGETS_PER_SOURCE = 100
+ const MIGRATABLE_MANAGED_AGENT_PERMISSIONS = new Set(['read', 'write'])
+
+ function isK8sName(value: unknown): value is string {
+ return typeof value === 'string' && value.length <= 63 && K8S_NAME_RE.test(value)
+ }
+
+ function normalizeCandidate(value: unknown): TrustedHostCandidate | null {
+ if (!value || typeof value !== 'object') return null
+ const item = value as Record<string, unknown>
+ if (item.active !== true || !isK8sName(item.name) || !isK8sName(item.namespace)) return null
+ const subject = item.gfsSubject as Record<string, unknown> | undefined
+ const expectedId = `1st:${item.namespace}/${item.name}`
+ const displayName = typeof item.displayName === 'string' ? item.displayName : item.name
+ if (subject?.type !== 'host' || subject.id !== expectedId) return null
+ if (`host:${expectedId}` === LEGACY_STANDALONE_SUBJECT_KEY) return null
+ if (/^all([ -]clerum)?[ -]agents$/i.test(displayName.trim())) return null
+ if (item.hidden === true || item.deleted === true || item.status === 'deleted') return null
+ return {
+ name: item.name,
+ namespace: item.namespace,
+ displayName,
+ active: true,
+ gfsSubject: { type: 'host', id: expectedId },
+ }
+ }
+
+ function normalizeGrant(value: unknown): LegacyGrantInventoryItem {
+ if (!value || typeof value !== 'object') throw new Error('legacy_grant_report_invalid')
+ const item = value as Record<string, unknown>
+ if (!UUID_RE.test(String(item.id ?? '')) || !UUID_RE.test(String(item.resourceId ?? ''))) {
+ throw new Error('legacy_grant_report_invalid')
+ }
+ if (typeof item.drive !== 'string' || !Array.isArray(item.permissions)) {
+ throw new Error('legacy_grant_report_invalid')
+ }
+ if (item.permissions.some(permission => typeof permission !== 'string')) {
+ throw new Error('legacy_grant_report_invalid')
+ }
+ if (
+ item.permissions.length === 0 ||
+ item.permissions.some(permission => !MIGRATABLE_MANAGED_AGENT_PERMISSIONS.has(permission))
+ ) {
+ // Never silently reduce or reproduce historical authority. An operator
+ // must review and replace a legacy grant containing forbidden bits before
+ // it can be migrated to individual HCC-managed agents.
+ throw new Error('legacy_grant_permissions_forbidden')
+ }
+ return {
+ id: String(item.id),
+ drive: item.drive,
+ resourceId: String(item.resourceId),
+ permissions: [...new Set(item.permissions as string[])].sort(),
+ inherit: item.inherit === true,
+ }
+ }
+
+ function canonicalJson(value: unknown): string {
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`
+ if (value && typeof value === 'object') {
+ const record = value as Record<string, unknown>
- return `{${Object.keys(record).sort().map(key => `${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(',')}}`
++ return `{${Object.keys(record)
++ .sort()
++ .map(key => `${JSON.stringify(key)}:${canonicalJson(record[key])}`)
++ .join(',')}}`
+ }
+ return JSON.stringify(value)
+ }
+
+ export function sameReviewedInventory(left: unknown, right: unknown): boolean {
+ return canonicalJson(left) === canonicalJson(right)
+ }
+
+ export async function buildLegacyGrantMigrationReport(api: LegacyGrantMigrationApi) {
+ const [legacyValue, directoryValue] = await Promise.all([
+ api.getLegacyGrants(),
+ api.getTrustedHostDirectory(),
+ ])
+ const legacy = legacyValue as { sourceSubject?: unknown; grants?: unknown }
+ const directory = directoryValue as { agents?: unknown }
+ if (legacy?.sourceSubject !== LEGACY_STANDALONE_SUBJECT_KEY || !Array.isArray(legacy.grants)) {
+ throw new Error('legacy_grant_report_invalid')
+ }
+ if (!Array.isArray(directory?.agents)) throw new Error('trusted_host_directory_invalid')
+ if (legacy.grants.length > MAX_INVENTORY_ITEMS || directory.agents.length > MAX_INVENTORY_ITEMS) {
+ throw new Error('migration_inventory_limit_exceeded')
+ }
+
- const sourceGrants = legacy.grants.map(normalizeGrant).sort(
- (a, b) =>
- a.drive.localeCompare(b.drive) ||
- a.resourceId.localeCompare(b.resourceId) ||
- a.id.localeCompare(b.id)
- )
++ const sourceGrants = legacy.grants
++ .map(normalizeGrant)
++ .sort(
++ (a, b) =>
++ a.drive.localeCompare(b.drive) ||
++ a.resourceId.localeCompare(b.resourceId) ||
++ a.id.localeCompare(b.id)
++ )
+ const validIndividualHostCandidates = directory.agents
+ .map(normalizeCandidate)
+ .filter((candidate): candidate is TrustedHostCandidate => candidate !== null)
+ .sort((a, b) => a.gfsSubject.id.localeCompare(b.gfsSubject.id))
+ if (
+ new Set(validIndividualHostCandidates.map(candidate => candidate.gfsSubject.id)).size !==
+ validIndividualHostCandidates.length
+ ) {
+ throw new Error('trusted_host_directory_duplicate')
+ }
+ return {
+ mode: 'report' as const,
+ sourceSubject: LEGACY_STANDALONE_SUBJECT_KEY,
+ sourceGrants,
+ validIndividualHostCandidates,
+ mappingTemplate: {
+ version: 1,
+ reviewedSourceGrants: sourceGrants,
+ reviewedHostCandidates: validIndividualHostCandidates,
+ mappings: sourceGrants.map(grant => ({ sourceGrantId: grant.id, targets: [] as string[] })),
+ },
+ note: 'Candidate Hosts are inventory only; no assignment is inferred.',
+ }
+ }
+
+ export function validateReviewedLegacyGrantMapping(
+ report: Awaited<ReturnType<typeof buildLegacyGrantMigrationReport>>,
+ mappingValue: unknown
+ ): Map<string, string[]> {
+ if (!mappingValue || typeof mappingValue !== 'object') throw new Error('mapping_invalid')
+ const mapping = mappingValue as Record<string, unknown>
+ if (mapping.version !== 1 || !Array.isArray(mapping.mappings)) throw new Error('mapping_invalid')
+ if (!sameReviewedInventory(mapping.reviewedSourceGrants, report.sourceGrants)) {
+ throw new Error('source_inventory_changed')
+ }
- if (!sameReviewedInventory(mapping.reviewedHostCandidates, report.validIndividualHostCandidates)) {
++ if (
++ !sameReviewedInventory(mapping.reviewedHostCandidates, report.validIndividualHostCandidates)
++ ) {
+ throw new Error('trusted_host_directory_changed')
+ }
+ const grants = new Set(report.sourceGrants.map(grant => grant.id))
+ const candidates = new Set(
+ report.validIndividualHostCandidates.map(candidate => `host:${candidate.gfsSubject.id}`)
+ )
+ const reviewed = new Map<string, string[]>()
+ for (const value of mapping.mappings) {
+ if (!value || typeof value !== 'object') throw new Error('mapping_invalid')
+ const entry = value as Record<string, unknown>
+ if (typeof entry.sourceGrantId !== 'string' || reviewed.has(entry.sourceGrantId)) {
+ throw new Error('mapping_source_duplicate_or_invalid')
+ }
+ if (!grants.has(entry.sourceGrantId)) throw new Error('mapping_source_unknown')
+ if (
+ !Array.isArray(entry.targets) ||
+ entry.targets.length === 0 ||
+ entry.targets.length > MAX_TARGETS_PER_SOURCE
+ ) {
+ throw new Error('mapping_targets_required_or_excessive')
+ }
+ const targets = entry.targets.map(String)
+ if (new Set(targets).size !== targets.length) throw new Error('mapping_target_duplicate')
+ for (const target of targets) {
+ if (
+ target === LEGACY_STANDALONE_SUBJECT_KEY ||
+ !target.startsWith('host:1st:') ||
+ !candidates.has(target)
+ ) {
+ throw new Error('mapping_target_not_current_trusted_host')
+ }
+ }
+ reviewed.set(entry.sourceGrantId, targets.sort())
+ }
+ if (reviewed.size !== grants.size) throw new Error('mapping_source_missing')
+ return reviewed
+ }
+
+ export async function applyReviewedLegacyGrantMigration(
+ api: LegacyGrantMigrationApi,
+ mapping: unknown
+ ) {
+ // This fresh report is intentionally the final inventory read before any
+ // mutation. The exact reviewed snapshots must still match current truth.
+ const report = await buildLegacyGrantMigrationReport(api)
+ const reviewed = validateReviewedLegacyGrantMapping(report, mapping)
+ const sources = []
+ for (const grant of report.sourceGrants) {
+ const targets = []
+ for (const target of reviewed.get(grant.id) ?? []) {
+ const result = await api.putGrant({
+ drive: grant.drive,
+ resourceId: grant.resourceId,
+ subject: { type: 'host', id: target.slice('host:'.length) },
+ permissions: grant.permissions,
+ inherit: grant.inherit,
+ })
+ targets.push({
+ target,
+ ok: result.ok,
+ status: result.status ?? null,
+ error: result.error ?? null,
+ })
+ }
+ sources.push({
+ sourceGrantId: grant.id,
+ legacyGrantPreserved: true,
+ readyForRetirement: targets.every(target => target.ok),
+ targets,
+ })
+ }
+ return {
+ mode: 'apply' as const,
+ sourceSubject: LEGACY_STANDALONE_SUBJECT_KEY,
+ allApprovedIndividualGrantsSucceeded: sources.every(source => source.readyForRetirement),
+ legacyGrantsDeleted: false,
+ sources,
+ }
+ }
diff --cc control-api/src/gfs/seedResources.ts
index 4aa4dde76,3ce31a88c..9458a5282
--- a/control-api/src/gfs/seedResources.ts
+++ b/control-api/src/gfs/seedResources.ts
@@@ -87,6 -126,13 +126,12 @@@ export interface SeedDb
export class DbSeedResourceStore implements SeedResourceStore {
constructor(private readonly db: SeedDb) {}
+ async acquireStructureLock(drive: string): Promise<void> {
- await this.db.query(
- `SELECT pg_advisory_xact_lock(hashtext('gfs:structure:' || $1)::bigint)`,
- [drive]
- )
++ await this.db.query(`SELECT pg_advisory_xact_lock(hashtext('gfs:structure:' || $1)::bigint)`, [
++ drive,
++ ])
+ }
+
async ensureDirectory(input: {
drive: string
parentResourceId: string | null
@@@ -125,8 -219,65 +218,67 @@@
WHERE drive = $1 AND parent_resource_id = $2 AND name = $3 AND deleted_at IS NULL`,
[drive, parentResourceId, name]
)
- return resourceIdOf(existing.rows[0])
+ const racedSibling = directoryRowOf(existing.rows[0])
+ if (racedSibling.kind !== 'directory' || racedSibling.path_cache !== expectedPath) {
+ throw new Error('[gfs] seed: concurrently inserted directory is not canonical')
+ }
+ return racedSibling.resource_id
+ }
+
+ private async loadDirectoryChain(resourceId: string): Promise<DirectoryChainRow[]> {
+ const result = await this.db.query(
+ `WITH RECURSIVE chain AS (
+ SELECT r.resource_id, r.drive, r.parent_resource_id, r.name, r.kind, r.path_cache,
+ r.deleted_at, ARRAY[r.resource_id]::uuid[] visited, false cycle
+ FROM gfs_resources r WHERE r.resource_id = $1::uuid
+ UNION ALL
+ SELECT p.resource_id, p.drive, p.parent_resource_id, p.name, p.kind, p.path_cache,
+ p.deleted_at, c.visited || p.resource_id, p.resource_id = ANY(c.visited)
+ FROM chain c JOIN gfs_resources p ON p.resource_id = c.parent_resource_id
+ WHERE NOT c.cycle
+ ) SELECT resource_id, drive, parent_resource_id, name, kind, path_cache, deleted_at, cycle
+ FROM chain`,
+ [resourceId]
+ )
+ return result.rows as DirectoryChainRow[]
+ }
+ }
+
+ interface DirectoryChainRow {
+ resource_id: string
+ drive: string
+ parent_resource_id: string | null
+ name: string
+ kind: string
+ path_cache: string | null
+ deleted_at: string | null
+ cycle?: boolean
+ }
+
+ function directoryRowOf(row: unknown): DirectoryChainRow {
+ const value = row as DirectoryChainRow | undefined
+ if (!value || typeof value.resource_id !== 'string') {
+ throw new Error('[gfs] seed: expected a resource_id row but got none')
+ }
+ return value
+ }
+
+ function canonicalDirectoryPath(rows: DirectoryChainRow[], drive: string): string {
+ if (
+ rows.length === 0 ||
- rows.some(row => row.cycle || row.deleted_at !== null || row.drive !== drive || row.kind !== 'directory') ||
++ rows.some(
++ row => row.cycle || row.deleted_at !== null || row.drive !== drive || row.kind !== 'directory'
++ ) ||
+ rows.at(-1)?.parent_resource_id !== null ||
+ rows.at(-1)?.name !== GFS_ROOT_NAME
+ ) {
+ throw new Error('[gfs] seed: parent ancestry is not a live same-drive directory chain')
}
+ const segments = rows
+ .slice(0, -1)
+ .map(row => row.name)
+ .reverse()
+ return segments.length === 0 ? '/' : `/${segments.join('/')}`
}
function resourceIdOf(row: unknown): string {
diff --cc control-api/src/routes/admin/hostsOverview.ts
index f9e50f83f,cbf9f0990..efa531bd0
--- a/control-api/src/routes/admin/hostsOverview.ts
+++ b/control-api/src/routes/admin/hostsOverview.ts
@@@ -3,6 -3,6 +3,7 @@@ import { config } from '../../config.js
import { asyncHandler } from '../../http/asyncHandler.js'
import { enforceNamespace } from '../../http/namespaceAudit.js'
import { K8sGateway } from '../../k8s.js'
++import { buildAgentDirectoryEntry } from '../../services/directory/accessReconciliation.js'
import {
listAllTeams,
listTeamsByAgent,
diff --cc control-api/src/routes/external/gfs.ts
index 42305a782,1ba8cccde..d3a655351
--- a/control-api/src/routes/external/gfs.ts
+++ b/control-api/src/routes/external/gfs.ts
@@@ -7,7 -7,8 +7,8 @@@ import
} from '../../auth/gfsToken.js'
import { config } from '../../config.js'
import { pool } from '../../db.js'
-import { GfsTreeError, clampLimit, decodeCursor, encodeCursor } from '../../gfs/tree.js'
+ import { isValidHostSubjectId, makeHostSubjectId } from '../../gfs/hostSubject.js'
+import { GfsTreeError, clampLimit, decodeCursor, encodeCursor } from '../../gfs/tree.js'
import { asyncHandler } from '../../http/asyncHandler.js'
import {
type ExternalAuthedRequest,
diff --cc control-api/src/routes/gfs/index.ts
index 8b2183501,bf88da8d7..b82c8b199
--- a/control-api/src/routes/gfs/index.ts
+++ b/control-api/src/routes/gfs/index.ts
@@@ -1,5 -1,5 +1,6 @@@
import { Router } from 'express'
import { registerGfsGrantRoutes } from './grants.js'
++import { registerLegacyStandaloneGrantReportRoute } from './legacyStandaloneGrants.js'
import { registerGfsProvisionerTokenRoute } from './provisionerToken.js'
import { registerGfsProxyRoute } from './proxy.js'
import { registerGfsResolveRoutes } from './resolve.js'
diff --cc control-api/src/routes/gfs/resources.ts
index b7211de41,5c2ee7ae9..012ad7fa4
--- a/control-api/src/routes/gfs/resources.ts
+++ b/control-api/src/routes/gfs/resources.ts
@@@ -65,13 -56,10 +56,14 @@@ interface ResourceRow
name: string
kind: string
version: number
+ deleted_at: string | null
}
-export interface ResourcePatch { newName?: unknown; newParentId?: unknown; ifMatch?: unknown }
+export interface ResourcePatch {
+ newName?: unknown
+ newParentId?: unknown
+ ifMatch?: unknown
+}
async function loadResource(db: GrantsDb, resourceId: string): Promise<ResourceRow | null> {
const res = await db.query(
@@@ -82,11 -70,107 +74,113 @@@
return (res.rows[0] as ResourceRow | undefined) ?? null
}
- /**
- * Authorize and apply a rename/move. Pure of HTTP — throws ResourcePatchError
- * with the spec error code; tests drive it with a fake GrantsDb. Returns the new
- * version (etag).
- */
-interface AncestorRow extends ResourceRow { cycle: boolean }
++interface AncestorRow extends ResourceRow {
++ cycle: boolean
++}
+ async function acquireStructureLock(db: GrantsDb, drive: string): Promise<void> {
+ await db.query(`SELECT pg_advisory_xact_lock(hashtext('gfs:structure:' || $1)::bigint)`, [drive])
+ }
+
+ async function lockRows(db: GrantsDb, resourceIds: Iterable<string>): Promise<void> {
+ const ids = [...new Set(resourceIds)].sort()
+ if (ids.length === 0) return
+ await db.query(
+ `SELECT resource_id
+ FROM gfs_resources
+ WHERE resource_id = ANY($1::uuid[])
+ ORDER BY resource_id
+ FOR UPDATE`,
+ [ids]
+ )
+ }
+
+ async function loadAncestorChain(db: GrantsDb, resourceId: string): Promise<AncestorRow[]> {
+ const result = await db.query(
+ `WITH RECURSIVE chain AS (
+ SELECT r.resource_id, r.drive, r.parent_resource_id, r.name, r.kind, r.version, r.deleted_at,
+ ARRAY[r.resource_id]::uuid[] AS visited, false AS cycle
+ FROM gfs_resources r WHERE r.resource_id = $1::uuid
+ UNION ALL
+ SELECT p.resource_id, p.drive, p.parent_resource_id, p.name, p.kind,
+ p.version, p.deleted_at, c.visited || p.resource_id,
+ p.resource_id = ANY(c.visited) AS cycle
+ FROM chain c JOIN gfs_resources p ON p.resource_id = c.parent_resource_id WHERE NOT c.cycle
+ )
+ SELECT resource_id, drive, parent_resource_id, name, kind, version, deleted_at, cycle
+ FROM chain`,
+ [resourceId]
+ )
+ return result.rows as AncestorRow[]
+ }
+
+ function assertLiveDirectoryChain(rows: AncestorRow[], drive: string): void {
+ if (
+ rows.length === 0 ||
- rows.some(row =>
- row.cycle || row.deleted_at !== null || row.drive !== drive || row.kind !== 'directory'
++ rows.some(
++ row => row.cycle || row.deleted_at !== null || row.drive !== drive || row.kind !== 'directory'
+ ) ||
+ rows.at(-1)?.parent_resource_id !== null
+ ) {
+ throw new ResourcePatchError(412, 'precondition_failed')
+ }
+ }
+
+ function directoryPath(rows: AncestorRow[]): string {
- const names = rows.slice(0, -1).map(row => row.name).reverse()
++ const names = rows
++ .slice(0, -1)
++ .map(row => row.name)
++ .reverse()
+ return names.length === 0 ? '/' : `/${names.join('/')}`
+ }
-const sameChain = (a: AncestorRow[], b: AncestorRow[]) => a.length === b.length && a.every((row, i) => row.resource_id === b[i]?.resource_id)
++const sameChain = (a: AncestorRow[], b: AncestorRow[]) =>
++ a.length === b.length && a.every((row, i) => row.resource_id === b[i]?.resource_id)
+ async function refreshSubtreePaths(
+ db: GrantsDb,
+ drive: string,
+ resourceId: string,
+ rootPath: string
+ ): Promise<void> {
+ const result = await db.query(
+ `WITH RECURSIVE subtree AS (
+ SELECT r.resource_id, $3::text canonical_path,
+ ARRAY[r.resource_id]::uuid[] visited, false cycle FROM gfs_resources r
+ WHERE r.resource_id = $2::uuid AND r.drive = $1 AND r.deleted_at IS NULL
+ UNION ALL
+ SELECT child.resource_id,
+ CASE WHEN parent.canonical_path = '/' THEN '/' || child.name
+ ELSE parent.canonical_path || '/' || child.name END,
+ parent.visited || child.resource_id, child.resource_id = ANY(parent.visited)
+ FROM subtree parent JOIN gfs_resources child ON child.parent_resource_id = parent.resource_id
+ AND child.drive = $1 AND child.deleted_at IS NULL WHERE NOT parent.cycle
+ ),
+ canonical AS (
+ SELECT resource_id, canonical_path FROM subtree WHERE NOT cycle
+ ),
+ updated AS (
+ UPDATE gfs_resources resource SET path_cache = canonical.canonical_path, updated_at = now()
+ FROM canonical WHERE resource.resource_id = canonical.resource_id RETURNING resource.resource_id
+ )
+ SELECT (SELECT count(DISTINCT resource_id) FROM subtree WHERE NOT cycle) AS expected_count,
+ (SELECT count(*) FROM updated) AS updated_count,
+ (SELECT count(*) FROM canonical) AS canonical_count,
+ (SELECT count(DISTINCT canonical_path) FROM canonical) AS distinct_path_count,
+ EXISTS (SELECT 1 FROM subtree WHERE cycle) AS has_cycle`,
+ [drive, resourceId, rootPath]
+ )
+ const row = result.rows[0] as Record<string, string | number | boolean> | undefined
+ if (!row) throw new ResourcePatchError(412, 'precondition_failed')
+ const expected = Number(row.expected_count)
+ if (
+ row.has_cycle ||
+ expected === 0 ||
+ Number(row.updated_count) !== expected ||
+ Number(row.canonical_count) !== expected ||
+ Number(row.distinct_path_count) !== expected
+ ) {
+ throw new ResourcePatchError(412, 'precondition_failed')
+ }
+ }
+
export async function applyResourcePatch(
db: GrantsDb,
caller: GfsCaller,
@@@ -122,7 -193,60 +203,70 @@@
: 'resource.move'
: 'resource.rename'
- // Authorization with audited denials (spec: every authz denial is audited).
+ let ifMatch: number | undefined
+ if (patch.ifMatch !== undefined) {
+ ifMatch = Number(patch.ifMatch)
+ if (!Number.isInteger(ifMatch)) throw new ResourcePatchError(412, 'precondition_failed')
+ }
+
+ const requestedName = wantsRename ? validateName(patch.newName) : observedResource.name
+ const requestedDestination = wantsMove ? String(patch.newParentId) : null
+ if (wantsMove && !UUID_RE.test(requestedDestination!))
+ throw new ResourcePatchError(400, 'path_invalid')
+
- const observedDestination = requestedDestination ? await loadResource(db, requestedDestination) : null
++ const observedDestination = requestedDestination
++ ? await loadResource(db, requestedDestination)
++ : null
+ if (requestedDestination && (!observedDestination || observedDestination.deleted_at !== null))
+ throw new ResourcePatchError(404, 'not_found')
+ if (requestedDestination && observedDestination?.drive !== drive) {
- await audit({ actorKey: caller.actorKey, targetKey: caller.actorKey, op, drive, resourceId, outcome: 'denied' })
++ await audit({
++ actorKey: caller.actorKey,
++ targetKey: caller.actorKey,
++ op,
++ drive,
++ resourceId,
++ outcome: 'denied',
++ })
+ throw new ResourcePatchError(403, 'cross_boundary')
+ }
+ if (requestedDestination && observedDestination?.kind !== 'directory')
+ throw new ResourcePatchError(400, 'not_a_directory')
+ const initialChains = await Promise.all([
+ observedResource.parent_resource_id
+ ? loadAncestorChain(db, observedResource.parent_resource_id)
+ : Promise.resolve([]),
+ requestedDestination ? loadAncestorChain(db, requestedDestination) : Promise.resolve([]),
+ ])
+ if (initialChains.flat().some(row => row.drive !== drive))
+ throw new ResourcePatchError(412, 'precondition_failed')
+ await lockRows(db, [
+ resourceId,
+ ...(observedResource.parent_resource_id ? [observedResource.parent_resource_id] : []),
+ ...(requestedDestination ? [requestedDestination] : []),
+ ...initialChains.flat().map(row => row.resource_id),
+ ])
+
+ const resource = await loadResource(db, resourceId)
+ if (!resource || resource.deleted_at !== null || resource.drive !== drive)
+ throw new ResourcePatchError(412, 'precondition_failed')
+ if (
+ resource.parent_resource_id !== observedResource.parent_resource_id ||
+ resource.version !== observedResource.version
+ )
+ throw new ResourcePatchError(412, 'precondition_failed')
+ if (resource.parent_resource_id === null) throw new ResourcePatchError(400, 'path_invalid')
+ if (ifMatch !== undefined && ifMatch !== resource.version)
+ throw new ResourcePatchError(412, 'precondition_failed')
+
+ const sourceChain = await loadAncestorChain(db, resource.parent_resource_id)
+ assertLiveDirectoryChain(sourceChain, drive)
- if (!sameChain(sourceChain, initialChains[0])) throw new ResourcePatchError(412, 'precondition_failed')
++ if (!sameChain(sourceChain, initialChains[0]))
++ throw new ResourcePatchError(412, 'precondition_failed')
+ const name = wantsRename ? requestedName : resource.name
+ let newParentId: string | null = resource.parent_resource_id
+ let parentChain = sourceChain
+
const requireAccess = async (
bit: 'read' | 'write' | 'delete' | 'manage_acl' | 'share',
rid: string
@@@ -145,20 -262,23 +289,25 @@@
}
if (wantsMove) {
- const dest = String(patch.newParentId)
- if (!UUID_RE.test(dest)) throw new ResourcePatchError(400, 'path_invalid')
- if (resource.parent_resource_id === null) throw new ResourcePatchError(400, 'path_invalid')
+ const dest = requestedDestination!
const destRow = await loadResource(db, dest)
- if (!destRow) throw new ResourcePatchError(404, 'not_found')
- if (destRow.drive !== resource.drive) throw new ResourcePatchError(403, 'cross_boundary')
- if (destRow.kind !== 'directory') throw new ResourcePatchError(400, 'not_a_directory')
- // Cycle guard: never move a resource into itself or one of its descendants
- // (would orphan the subtree and loop ancestor traversal).
- const destAncestors = await ancestorsOf(db, drive, dest)
- if (dest === resourceId || destAncestors.includes(resourceId)) {
+ const observedDest = observedDestination!
+ if (
+ !destRow ||
+ destRow.deleted_at !== null ||
+ destRow.drive !== observedDest.drive ||
+ destRow.kind !== observedDest.kind ||
+ destRow.parent_resource_id !== observedDest.parent_resource_id ||
+ destRow.version !== observedDest.version
- ) throw new ResourcePatchError(412, 'precondition_failed')
++ )
++ throw new ResourcePatchError(412, 'precondition_failed')
+ const destinationChain = await loadAncestorChain(db, dest)
+ assertLiveDirectoryChain(destinationChain, drive)
- if (!sameChain(destinationChain, initialChains[1])) throw new ResourcePatchError(412, 'precondition_failed')
++ if (!sameChain(destinationChain, initialChains[1]))
++ throw new ResourcePatchError(412, 'precondition_failed')
+ if (dest === resourceId || destinationChain.some(row => row.resource_id === resourceId)) {
throw new ResourcePatchError(400, 'path_invalid')
}
- // move authority: write+delete on source parent, write on destination parent.
await requireAccess('write', resource.parent_resource_id)
await requireAccess('delete', resource.parent_resource_id)
await requireAccess('write', dest)
@@@ -182,19 -300,13 +329,20 @@@
}
throw err
}
- if (updated.rows.length === 0) {
- throw new ResourcePatchError(412, 'precondition_failed')
- }
+ if (updated.rows.length === 0) throw new ResourcePatchError(412, 'precondition_failed')
const version = Number((updated.rows[0] as { version: number }).version)
+ const parentPath = directoryPath(parentChain)
+ const rootPath = parentPath === '/' ? `/${name}` : `${parentPath}/${name}`
+ await refreshSubtreePaths(db, drive, resourceId, rootPath)
- await audit({ actorKey: caller.actorKey, targetKey: caller.actorKey, op, drive, resourceId, outcome: 'allowed' })
+ await audit({
+ actorKey: caller.actorKey,
+ targetKey: caller.actorKey,
+ op,
+ drive,
+ resourceId,
+ outcome: 'allowed',
+ })
return { version }
}
diff --cc control-api/src/routes/gfs/seed.ts
index 7041cf500,9479a1ed3..8ee6d00c2
--- a/control-api/src/routes/gfs/seed.ts
+++ b/control-api/src/routes/gfs/seed.ts
@@@ -30,17 -31,28 +31,24 @@@ export async function seedRootDirectori
if (!Array.isArray(b.rootDirectories) || b.rootDirectories.some(d => typeof d !== 'string')) {
return { status: 400, body: { error: 'invalid_rootDirectories' } }
}
- const result = await seedRootDirectories(store, b.drive, b.rootDirectories as string[])
- return { status: 200, body: result }
+ try {
+ const result = await seedRootDirectories(store, b.drive, b.rootDirectories as string[])
+ return { status: 200, body: result }
+ } catch (error) {
+ if (error instanceof InvalidRootDirectoriesError) {
+ return { status: 400, body: { error: 'invalid_rootDirectories' } }
+ }
+ throw error
+ }
}
- export function registerGfsSeedRoute(router: Router): void {
- router.post(
- '/gfs/seed',
- requireInternalControlJwt,
- asyncHandler(async (req, res) => {
- const result = await seedRootDirectoriesToHttp(new DbSeedResourceStore(pool), req.body)
- res.status(result.status).json(result.body)
- })
+ export async function handleSeed(req: Request, res: Response): Promise<void> {
+ const result = await withTransaction(db =>
+ seedRootDirectoriesToHttp(new DbSeedResourceStore(db), req.body)
)
+ res.status(result.status).json(result.body)
+ }
+
+ export function registerGfsSeedRoute(router: Router): void {
- router.post(
- '/gfs/seed',
- requireInternalControlJwt,
- asyncHandler(handleSeed)
- )
++ router.post('/gfs/seed', requireInternalControlJwt, asyncHandler(handleSeed))
}
diff --cc control-api/src/services/access/mcpInvocable.ts
index 59b40f90a,b8dc38219..53e36db5b
--- a/control-api/src/services/access/mcpInvocable.ts
+++ b/control-api/src/services/access/mcpInvocable.ts
@@@ -13,10 -13,15 +13,15 @@@
* - `spec.enabled !== false`
* - `spec.auth.type` is absent or equals `"none"`
* - `spec.transport.url` is a non-empty string
- * - Session catalog returns **names only**; RPC catalog additionally returns
- * the transport URL.
+ * - Session catalog preserves names-only compatibility while enriching each
+ * authorized agent with its canonical directory identity; RPC catalog
+ * additionally returns the transport URL.
*/
import type { K8sGateway } from '../../k8s.js'
+ import {
- buildAgentDirectoryEntry,
+ type AgentDirectoryEntry,
++ buildAgentDirectoryEntry,
+ } from '../directory/accessReconciliation.js'
export interface InvocableMcpServer {
name: string
@@@ -185,22 -222,54 +222,48 @@@ export async function resolveMcpServers
const { mcpServersNamespace, hostsNamespace, agentNames } = opts
if (agentNames.length === 0) return []
- const [hosts, mcpServers] = await Promise.all([
- gateway.listResource('hosts', hostsNamespace),
- gateway.listResource('mcpservers', mcpServersNamespace),
- ])
- const hostList = asArray<HostCR>(hosts)
- const serverList = asArray<McpServerCR>(mcpServers)
+ const resolvedHosts = await Promise.all(
+ agentNames.map(async requestedName => {
+ try {
- const host = (await gateway.getResource(
- 'hosts',
- requestedName,
- hostsNamespace
- )) as HostCR
++ const host = (await gateway.getResource('hosts', requestedName, hostsNamespace)) as HostCR
+ const directoryEntry = buildAgentDirectoryEntry(host, hostsNamespace)
+ if (!directoryEntry || directoryEntry.name !== requestedName) return null
+ return { host, directoryEntry }
+ } catch (error) {
+ if (isK8sResourceNotFound(error)) return null
+ // A non-404 failure says nothing about whether this already-authorized
+ // Host still exists. Propagate it so callers can preserve their
+ // names-only compatibility field instead of silently revoking access.
+ throw error
+ }
+ })
+ )
- const hostByName = new Map<string, HostCR>()
- for (const h of hostList) {
- const n = h.metadata?.name
- if (n) hostByName.set(n, h)
+ let serverList: McpServerCR[] = []
+ try {
- serverList = asArray<McpServerCR>(
- await gateway.listResource('mcpservers', mcpServersNamespace)
- )
++ serverList = asArray<McpServerCR>(await gateway.listResource('mcpservers', mcpServersNamespace))
+ } catch (err) {
+ // Directory identity remains useful when optional MCP catalog enrichment
+ // is temporarily unavailable — but the degradation must be observable, or
+ // a broken mcpservers list path reads as "this agent has no tools".
+ console.error(
+ '[mcpInvocable] mcpservers list failed; directory served without MCP catalog:',
+ err instanceof Error ? err.message : String(err)
+ )
}
+ const visibleHosts = resolvedHosts.filter(
+ (
+ item
+ ): item is {
+ host: HostCR
+ directoryEntry: AgentDirectoryEntry
+ } => item !== null
+ )
+
const scopedContextIds = new Set<string>()
- for (const agentName of agentNames) {
- const contextRef = hostByName.get(agentName)?.spec?.contextRef
+ for (const { host } of visibleHosts) {
+ const contextRef = host.spec?.contextRef
if (contextRef) scopedContextIds.add(contextRef)
}
diff --cc control-api/src/services/directory/accessReconciliation.ts
index 4d1bda4ad,60b77d793..e019fbeb1
--- a/control-api/src/services/directory/accessReconciliation.ts
+++ b/control-api/src/services/directory/accessReconciliation.ts
@@@ -16,6 -21,53 +21,50 @@@ export type AccessPartition =
deleted: string[]
}
+ export type AgentDirectoryEntry = {
+ name: string
+ namespace: string
+ displayName: string
+ active: true
+ gfsSubject: {
+ type: 'host'
+ id: string
+ }
+ }
+
+ // The legacy shared credential was never an individual Host identity. Keeping
+ // it out of the directory prevents callers from turning fleet-wide history into
+ // a selectable per-agent grant target.
+ const LEGACY_FLEET_WIDE_HOST_SENTINEL = 'standalone'
+
+ export function buildAgentDirectoryEntry(
+ value: unknown,
+ trustedNamespace: string
+ ): AgentDirectoryEntry | null {
+ if (!value || typeof value !== 'object') return null
+ const host = value as HostResource
+ const name = typeof host.metadata?.name === 'string' ? host.metadata.name : ''
+ const reportedNamespace = host.metadata?.namespace
+
- if (
- !name ||
- (trustedNamespace === 'mcp-host' && name === LEGACY_FLEET_WIDE_HOST_SENTINEL)
- ) return null
++ if (!name || (trustedNamespace === 'mcp-host' && name === LEGACY_FLEET_WIDE_HOST_SENTINEL))
++ return null
+ if (reportedNamespace !== trustedNamespace) return null
+ if (host.metadata?.deletionTimestamp) return null
+ if (host.spec?.enabled === false) return null
+
+ const subjectId = makeHostSubjectId('1st', trustedNamespace, name)
+ if (!subjectId) return null
+
- const configuredDisplayName =
- typeof host.spec?.host === 'string' ? host.spec.host.trim() : ''
++ const configuredDisplayName = typeof host.spec?.host === 'string' ? host.spec.host.trim() : ''
+ return {
+ name,
+ namespace: trustedNamespace,
+ displayName: configuredDisplayName || name,
+ active: true,
+ gfsSubject: { type: 'host', id: subjectId },
+ }
+ }
+
export const MAX_DELETED_ACCESS_HISTORY = 200
export class DeletedAgentHistoryLimitError extends Error {
diff --cc control-api/test/accessReconciliation.test.ts
index bf0d6bce8,0a995ad59..ea2783d0d
--- a/control-api/test/accessReconciliation.test.ts
+++ b/control-api/test/accessReconciliation.test.ts
@@@ -33,14 -36,98 +36,105 @@@ describe('access reconciliation helpers
expect(merged).not.toContain(`deleted-${MAX_DELETED_ACCESS_HISTORY + 1}`)
})
+ it('compares complete snapshots as normalized sets', () => {
+ expect(accessValueSetsEqual([' agent-a ', 'agent-b', 'agent-a'], ['agent-b', 'agent-a'])).toBe(
+ true
+ )
+ expect(accessValueSetsEqual(['agent-a'], ['agent-b'])).toBe(false)
+ })
+
- it('retains all deleted agent history at the limit and rejects overflow', () => {
+ it('builds the opaque subject from trusted metadata, never display text', () => {
+ expect(
+ buildAgentDirectoryEntry(
+ {
+ metadata: { name: 'trading-agent', namespace: 'mcp-host' },
+ spec: { enabled: true, host: 'Trading Agent / Europe' },
+ },
+ 'mcp-host'
+ )
+ ).toEqual({
+ name: 'trading-agent',
+ namespace: 'mcp-host',
+ displayName: 'Trading Agent / Europe',
+ active: true,
+ gfsSubject: { type: 'host', id: '1st:mcp-host/trading-agent' },
+ })
+ })
+
+ it('excludes disabled, deleted, malformed, non-first-party, and legacy sentinel hosts', () => {
+ const hosts = [
+ { metadata: { name: 'visible', namespace: 'mcp-host' }, spec: { host: 'Visible' } },
+ { metadata: { name: 'disabled', namespace: 'mcp-host' }, spec: { enabled: false } },
+ {
+ metadata: {
+ name: 'deleted',
+ namespace: 'mcp-host',
+ deletionTimestamp: '2026-07-17T12:00:00Z',
+ },
+ spec: {},
+ },
+ { metadata: { name: '../invalid', namespace: 'mcp-host' }, spec: {} },
+ { metadata: { name: ' padded ', namespace: 'mcp-host' }, spec: {} },
+ { metadata: { name: 'missing-namespace' }, spec: {} },
+ { metadata: { name: 'third-party', namespace: 'sandbox-recipes' }, spec: {} },
+ { metadata: { name: 'standalone', namespace: 'mcp-host' }, spec: {} },
+ ]
+
+ const entries = hosts
+ .map(host => buildAgentDirectoryEntry(host, 'mcp-host'))
+ .filter(entry => entry !== null)
+ expect(entries).toEqual([
+ {
+ name: 'visible',
+ namespace: 'mcp-host',
+ displayName: 'Visible',
+ active: true,
+ gfsSubject: { type: 'host', id: '1st:mcp-host/visible' },
+ },
+ ])
+ })
+
+ it('keeps standalone as an individual Host outside the reserved mcp-host namespace', () => {
+ expect(
+ buildAgentDirectoryEntry(
+ { metadata: { name: 'standalone', namespace: 'custom-hosts' }, spec: {} },
+ 'custom-hosts'
+ )
+ ).toEqual({
+ name: 'standalone',
+ namespace: 'custom-hosts',
+ displayName: 'standalone',
+ active: true,
+ gfsSubject: { type: 'host', id: '1st:custom-hosts/standalone' },
+ })
+ })
+
+ it('lists only the canonical active trusted first-party Host names in source order', async () => {
+ const listResource = vi.fn().mockResolvedValue([
+ { metadata: { name: 'active-b', namespace: 'mcp-host' }, spec: { enabled: true } },
+ { metadata: { name: 'disabled', namespace: 'mcp-host' }, spec: { enabled: false } },
+ {
+ metadata: {
+ name: 'deleting',
+ namespace: 'mcp-host',
+ deletionTimestamp: '2026-07-18T00:00:00Z',
+ },
+ spec: {},
+ },
+ { metadata: { name: '../malformed', namespace: 'mcp-host' }, spec: {} },
+ { metadata: { name: 'wrong-namespace', namespace: 'sandbox-recipes' }, spec: {} },
+ { metadata: { name: 'standalone', namespace: 'mcp-host' }, spec: {} },
+ { metadata: { name: 'active-a', namespace: 'mcp-host' }, spec: {} },
+ { metadata: { name: 'active-b', namespace: 'mcp-host' }, spec: {} },
+ ])
+ const gateway = { listResource } as unknown as K8sGateway
+
+ await expect(listActiveAgentNames(gateway)).resolves.toEqual(['active-b', 'active-a'])
+ expect(listResource).toHaveBeenCalledOnce()
+ expect(listResource).toHaveBeenCalledWith('hosts', 'mcp-host')
+ })
+
+ it('preserves every deleted agent at the limit and rejects overflow without truncation', () => {
const atLimit = Array.from(
{ length: MAX_DELETED_ACCESS_HISTORY },
(_value, index) => `deleted-${index}`
diff --cc control-api/test/db.gfsAuditDecisionEvidenceMigration.test.ts
index 000000000,eeae409c4..edf8e6da5
mode 000000,100644..100644
--- a/control-api/test/db.gfsAuditDecisionEvidenceMigration.test.ts
+++ b/control-api/test/db.gfsAuditDecisionEvidenceMigration.test.ts
@@@ -1,0 -1,30 +1,30 @@@
-import { readFileSync } from 'node:fs'
+ import { describe, expect, it } from 'vitest'
++import { readFileSync } from 'node:fs'
+
+ describe('0073_gfs_audit_decision_evidence', () => {
+ it('adds constrained decision evidence without rewriting existing audit rows', () => {
+ const source = readFileSync(new URL('../src/db.ts', import.meta.url), 'utf8')
+ const previous = source.indexOf("version: '0072_gfs_reader_database_role'")
+ const start = source.indexOf("version: '0073_gfs_audit_decision_evidence'")
+ const sql = source.slice(start, source.indexOf('\n },\n]', start))
+
+ expect(previous).toBeGreaterThan(-1)
+ expect(start).toBeGreaterThan(previous)
+ expect(sql).toContain("ADD COLUMN IF NOT EXISTS record_type TEXT NOT NULL DEFAULT 'legacy'")
+ expect(sql).toContain('ADD COLUMN IF NOT EXISTS matched_subject TEXT NULL')
+ expect(sql).toContain('ADD COLUMN IF NOT EXISTS authorization_source TEXT NULL')
+ expect(sql).toContain('ADD COLUMN IF NOT EXISTS cached_authorization_source TEXT NULL')
+ expect(sql).toContain('ADD COLUMN IF NOT EXISTS mutation_outcome TEXT NULL')
+ expect(sql).toContain("'direct_grant', 'inherited_grant', 'direct_share'")
+ expect(sql).toContain("'inherited_share', 'operator', 'cache'")
+ expect(sql).toContain("mutation_outcome IN ('succeeded', 'failed')")
+ expect(sql).toContain("record_type = 'authorization_decision' AND mutation_outcome IS NULL")
+ expect(sql).toContain("record_type = 'mutation_outcome' AND mutation_outcome IS NOT NULL")
+ expect(sql).toContain('GRANT INSERT ON gfs_audit TO gfs_controller, gfs_controller_reader')
+ expect(sql).toContain(
+ 'REVOKE UPDATE, DELETE, TRUNCATE ON gfs_audit\n FROM gfs_controller, gfs_controller_reader'
+ )
+ expect(sql).not.toMatch(/UPDATE\s+gfs_audit|DELETE\s+FROM\s+gfs_audit/i)
+ expect(sql).not.toMatch(/DROP\s+(TABLE|COLUMN|CONSTRAINT)/i)
+ })
+ })
diff --cc control-api/test/db.gfsBlobGenerationMigration.test.ts
index 000000000,1c6619078..03aac15e3
mode 000000,100644..100644
--- a/control-api/test/db.gfsBlobGenerationMigration.test.ts
+++ b/control-api/test/db.gfsBlobGenerationMigration.test.ts
@@@ -1,0 -1,21 +1,21 @@@
-import { readFileSync } from 'node:fs'
+ import { describe, expect, it } from 'vitest'
++import { readFileSync } from 'node:fs'
+
+ describe('0071_gfs_immutable_blob_generations', () => {
+ it('is one additive migration with generation pointers, cleanup state, and path invalidation', () => {
+ const source = readFileSync(new URL('../src/db.ts', import.meta.url), 'utf8')
+ expect(source.match(/version: '0071_gfs_immutable_blob_generations'/g)).toHaveLength(1)
+ const start = source.indexOf("version: '0071_gfs_immutable_blob_generations'")
- const sql = source.slice(start, source.indexOf("\n },\n]", start))
++ const sql = source.slice(start, source.indexOf('\n },\n]', start))
+
+ expect(sql).toContain('ADD COLUMN IF NOT EXISTS blob_key TEXT NULL')
+ expect(sql).toContain('ADD COLUMN IF NOT EXISTS content_sha256 TEXT NULL')
+ expect(sql).toContain("split_part(blob_key, '/', 1) = replace(resource_id::text, '-', '')")
+ expect(sql).toContain('CREATE TABLE IF NOT EXISTS gfs_blob_manifests')
+ expect(sql).toContain('request_id UUID NOT NULL')
+ expect(sql).toContain("state IN ('staged', 'committed', 'deleting')")
+ expect(sql).toContain('UPDATE OF parent_resource_id, name, path_cache, deleted_at')
+ expect(sql).toContain('GRANT SELECT, INSERT, UPDATE, DELETE ON gfs_blob_manifests')
+ expect(sql).not.toMatch(/DROP\s+(TABLE|COLUMN)/i)
+ })
+ })
diff --cc control-api/test/db.gfsReaderRoleMigration.test.ts
index 000000000,ba420391b..1ec5c2b7a
mode 000000,100644..100644
--- a/control-api/test/db.gfsReaderRoleMigration.test.ts
+++ b/control-api/test/db.gfsReaderRoleMigration.test.ts
@@@ -1,0 -1,34 +1,34 @@@
-import { readFileSync } from 'node:fs'
+ import { describe, expect, it } from 'vitest'
++import { readFileSync } from 'node:fs'
+
+ describe('0072_gfs_reader_database_role', () => {
+ it('adds a NOLOGIN least-privilege reader after immutable blob generations', () => {
+ const source = readFileSync(new URL('../src/db.ts', import.meta.url), 'utf8')
+ const previous = source.indexOf("version: '0071_gfs_immutable_blob_generations'")
+ const start = source.indexOf("version: '0072_gfs_reader_database_role'")
+ const sql = source.slice(
+ start,
+ source.indexOf("version: '0073_gfs_audit_decision_evidence'", start)
+ )
+
+ expect(previous).toBeGreaterThan(-1)
+ expect(start).toBeGreaterThan(previous)
+ expect(sql).toContain('CREATE ROLE gfs_controller_reader NOLOGIN')
+ expect(sql).toContain(
+ 'NOLOGIN NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS'
+ )
+ expect(sql).toContain("WHERE member_role.rolname = 'gfs_controller_reader'")
- expect(sql).toContain("REVOKE %I FROM gfs_controller_reader")
++ expect(sql).toContain('REVOKE %I FROM gfs_controller_reader')
+ expect(sql).toContain(
+ 'GRANT SELECT ON gfs_resources, gfs_grants, gfs_shares TO gfs_controller_reader'
+ )
+ expect(sql).toContain('GRANT SELECT (id, status) ON control_admin_users')
+ expect(sql).toContain('GRANT SELECT (team_id, user_id, status) ON team_members')
+ expect(sql).toContain('GRANT INSERT ON gfs_audit TO gfs_controller_reader')
+ expect(sql).toContain('REVOKE ALL PRIVILEGES ON gfs_blob_manifests FROM gfs_controller_reader')
+ expect(sql).toContain('REVOKE INSERT, UPDATE, DELETE, TRUNCATE ON gfs_resources')
+ expect(sql).toContain('REVOKE UPDATE, DELETE, TRUNCATE ON gfs_audit')
+ expect(sql).not.toMatch(/ALTER ROLE gfs_controller\s/)
+ expect(sql).not.toMatch(/DROP\s+(ROLE|TABLE|COLUMN)/i)
+ })
+ })
diff --cc control-api/test/db.gfsRuntimeRoleContractMigration.test.ts
index 000000000,6d114ca47..ca8590d44
mode 000000,100644..100644
--- a/control-api/test/db.gfsRuntimeRoleContractMigration.test.ts
+++ b/control-api/test/db.gfsRuntimeRoleContractMigration.test.ts
@@@ -1,0 -1,47 +1,47 @@@
-import { readFileSync } from 'node:fs'
+ import { describe, expect, it } from 'vitest'
++import { readFileSync } from 'node:fs'
+
+ describe('0074_gfs_runtime_role_exact_contract', () => {
+ it('normalizes both roles without changing credential state', () => {
+ const source = readFileSync(new URL('../src/db.ts', import.meta.url), 'utf8')
+ const previous = source.indexOf("version: '0073_gfs_audit_decision_evidence'")
+ const start = source.indexOf("version: '0074_gfs_runtime_role_exact_contract'")
+ const sql = source.slice(start, source.indexOf('\n },\n]', start))
+
+ expect(start).toBeGreaterThan(previous)
+ expect(sql).toContain(
+ 'ALTER ROLE gfs_controller\n NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS'
+ )
+ expect(sql).toContain(
+ 'ALTER ROLE gfs_controller_reader\n NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS'
+ )
+ expect(sql).not.toMatch(/ALTER ROLE gfs_controller(?:_reader)?\s+(?:NO)?LOGIN/)
+ expect(sql).not.toMatch(/ALTER\s+ROLE[^;]*PASSWORD|DROP\s+ROLE/i)
+ expect(sql).toContain("ARRAY['gfs_controller', 'gfs_controller_reader']")
+ expect(sql).toContain("EXECUTE format('REVOKE %I FROM %I'")
+ })
+
+ it('rebuilds exact table, sequence, audit, and subject-column grants', () => {
+ const source = readFileSync(new URL('../src/db.ts', import.meta.url), 'utf8')
+ const start = source.indexOf("version: '0074_gfs_runtime_role_exact_contract'")
+ const sql = source.slice(start, source.indexOf('\n },\n]', start))
+
+ expect(sql).toContain(
+ 'gfs_blob_manifests, gfs_audit FROM gfs_controller, gfs_controller_reader, PUBLIC'
+ )
+ expect(sql).toContain('GRANT SELECT, INSERT, UPDATE ON gfs_resources TO gfs_controller')
+ expect(sql).toContain(
+ 'GRANT SELECT, INSERT, UPDATE, DELETE ON gfs_blob_manifests TO gfs_controller'
+ )
+ expect(sql).toContain(
+ 'GRANT SELECT ON gfs_resources, gfs_grants, gfs_shares TO gfs_controller_reader'
+ )
+ expect(sql).toContain('GRANT INSERT ON gfs_audit TO gfs_controller_reader')
+ expect(sql).toContain(
+ 'GRANT SELECT (id, status) ON control_admin_users\n TO gfs_controller, gfs_controller_reader'
+ )
+ expect(sql).toContain(
+ 'GRANT SELECT (team_id, user_id, status) ON team_members\n TO gfs_controller, gfs_controller_reader'
+ )
+ })
+ })
diff --cc control-api/test/deploy.gfsProvisioning.test.ts
index 748844875,ad629cbd9..587291b33
--- a/control-api/test/deploy.gfsProvisioning.test.ts
+++ b/control-api/test/deploy.gfsProvisioning.test.ts
@@@ -1,5 -1,7 +1,7 @@@
import { describe, expect, it } from 'vitest'
-import { readFileSync } from 'node:fs'
+ import { spawnSync } from 'node:child_process'
+import { readFileSync } from 'node:fs'
+ import { fileURLToPath } from 'node:url'
function read(relativeFromRepoRoot: string): string {
return readFileSync(new URL(relativeFromRepoRoot, import.meta.url), 'utf-8')
@@@ -7,22 -9,162 +9,219 @@@
describe('deploy/scripts/provision-gfs-db.sh', () => {
const script = read('../../deploy/scripts/provision-gfs-db.sh')
+ const verifier = read('../../scripts/minikube/verify-gfs.sh')
+ const probe = read('../../deploy/scripts/lib/gfs-dsn-probe.sh')
+ const transitions = read('../../deploy/scripts/lib/gfs-credential-secret.sh')
+ const rollout = read('../../deploy/scripts/lib/gfs-credential-rollout.sh')
+ const recovery = read('../../deploy/scripts/lib/gfs-credential-recovery.sh')
- const probePath = fileURLToPath(new URL('../../deploy/scripts/lib/gfs-dsn-probe.sh', import.meta.url))
++ const probePath = fileURLToPath(
++ new URL('../../deploy/scripts/lib/gfs-dsn-probe.sh', import.meta.url)
++ )
+ const role = 'gfs_controller'
+ const host = 'control-postgres.control-plane.svc.cluster.local'
+ const password = 'a'.repeat(48)
+ const uri = (endpoint: string) => ['postgresql', '://', role, ':', password, endpoint].join('')
- it('keeps process argv free of generated connection material', () => {
- expect(script).toContain('exec -i "$PG_DEPLOY" -- psql')
- expect(script).toContain('-f - <<SQL')
- expect(script).toContain('--patch-file=/dev/stdin')
- expect(script).not.toContain(' -c \\')
- expect(script).not.toContain('-p "$patch"')
- expect(script).not.toContain(`CONN="$${'D'}${'SN'}"`)
+ it('requires an explicit mode and contains no broad rollout', () => {
+ expect(script).toContain('stage-writer|stage-reader|rotate-reader|rotate-writer')
+ expect(script).not.toContain('rollout restart deployment -l')
+ expect(script).not.toContain('rollout status deployment -l')
+ expect(script).not.toContain('base64 -d 2>/dev/null || true')
})
- it('fails loud when gfsc rollout status fails', () => {
- const rolloutLine = script
- .split('\n')
- .find(line => line.includes('rollout status deployment -l "$GFS_DEPLOY_SELECTOR"'))
+ it('keeps reader and writer rotations independent', () => {
- const reader = script.slice(script.lastIndexOf('rotate-reader)'), script.lastIndexOf('rotate-writer)'))
++ const reader = script.slice(
++ script.lastIndexOf('rotate-reader)'),
++ script.lastIndexOf('rotate-writer)')
++ )
+ const writer = script.slice(script.lastIndexOf('rotate-writer)'))
- expect(reader).toContain('reconcile_credential gfs_controller_reader reader "$READER_SECRET" gfsc-reader true')
++ expect(reader).toContain(
++ 'reconcile_credential gfs_controller_reader reader "$READER_SECRET" gfsc-reader true'
++ )
+ expect(reader).not.toContain('gfsc-writer')
- expect(writer).toContain('reconcile_credential gfs_controller writer "$WRITER_SECRET" gfsc-writer true')
++ expect(writer).toContain(
++ 'reconcile_credential gfs_controller writer "$WRITER_SECRET" gfsc-writer true'
++ )
+ expect(writer).not.toContain('gfsc-reader')
- const reconciliation = script.slice(script.indexOf('reconcile_credential()'), script.lastIndexOf('case "$MODE"'))
- expect(reconciliation.indexOf('ensure_pending_candidate')).toBeLessThan(reconciliation.indexOf('set_role_password'))
- expect(reconciliation.indexOf('claim_secret_candidate')).toBeLessThan(reconciliation.indexOf('set_role_password'))
- expect(reconciliation.indexOf('set_role_password')).toBeLessThan(reconciliation.indexOf('promote_candidate'))
- expect(reconciliation.indexOf('promote_candidate')).toBeLessThan(reconciliation.lastIndexOf('complete_rollout'))
++ const reconciliation = script.slice(
++ script.indexOf('reconcile_credential()'),
++ script.lastIndexOf('case "$MODE"')
++ )
++ expect(reconciliation.indexOf('ensure_pending_candidate')).toBeLessThan(
++ reconciliation.indexOf('set_role_password')
++ )
++ expect(reconciliation.indexOf('claim_secret_candidate')).toBeLessThan(
++ reconciliation.indexOf('set_role_password')
++ )
++ expect(reconciliation.indexOf('set_role_password')).toBeLessThan(
++ reconciliation.indexOf('promote_candidate')
++ )
++ expect(reconciliation.indexOf('promote_candidate')).toBeLessThan(
++ reconciliation.lastIndexOf('complete_rollout')
++ )
+ })
+
+ it('adopts legacy writer state without rotating or restarting it', () => {
- const adoption = script.slice(script.indexOf('stage_writer()'), script.lastIndexOf('case "$MODE"'))
++ const adoption = script.slice(
++ script.indexOf('stage_writer()'),
++ script.lastIndexOf('case "$MODE"')
++ )
+ expect(adoption).toContain('load_secret_snapshot "$WRITER_SECRET"')
+ expect(adoption).toContain('dsn_has_role "$GFS_SNAPSHOT_ACTIVE" gfs_controller')
- expect(adoption).toContain('authenticate_or_restore_nologin gfs_controller writer "$GFS_SNAPSHOT_ACTIVE"')
++ expect(adoption).toContain(
++ 'authenticate_or_restore_nologin gfs_controller writer "$GFS_SNAPSHOT_ACTIVE"'
++ )
+ expect(adoption).toContain('verify_role_contract gfs_controller writer')
+ expect(adoption).toContain('credential_adoption_timestamp gfsc-writer')
- expect(adoption).toContain('adopt_legacy_secret_state "$WRITER_SECRET" "$GFS_SNAPSHOT_RV" "$GFS_SNAPSHOT_ANNOTATIONS"')
++ expect(adoption).toContain(
++ 'adopt_legacy_secret_state "$WRITER_SECRET" "$GFS_SNAPSHOT_RV" "$GFS_SNAPSHOT_ANNOTATIONS"'
++ )
+ expect(adoption).toContain('[ "$(secret_dsn "$WRITER_SECRET")" = "$GFS_SNAPSHOT_ACTIVE" ]')
+ expect(adoption).not.toContain('set_role_password')
+ expect(adoption).not.toContain('complete_rollout')
- expect(transitions).toContain('{"op": "test", "path": "/metadata/resourceVersion", "value": rv}')
++ expect(transitions).toContain(
++ '{"op": "test", "path": "/metadata/resourceVersion", "value": rv}'
++ )
+ expect(transitions).toContain('get secret "$secret" -o json')
+ expect(transitions).toContain('GFS_SNAPSHOT_ROTATED_AT=')
+ expect(rollout).toContain('input === process.env.GFS_PG_CONNECTION_STRING')
+ })
+
+ it('checks table, sequence, and membership boundaries explicitly', () => {
- expect(script).toContain("has_sequence_privilege(:'role_name', 'gfs_audit_sequence_no_seq', 'USAGE')")
- expect(script).toContain("has_sequence_privilege(:'role_name', 'gfs_audit_sequence_no_seq', 'SELECT')")
- expect(script).toContain("NOT has_sequence_privilege(:'role_name', 'gfs_audit_sequence_no_seq', 'UPDATE')")
++ expect(script).toContain(
++ "has_sequence_privilege(:'role_name', 'gfs_audit_sequence_no_seq', 'USAGE')"
++ )
++ expect(script).toContain(
++ "has_sequence_privilege(:'role_name', 'gfs_audit_sequence_no_seq', 'SELECT')"
++ )
++ expect(script).toContain(
++ "NOT has_sequence_privilege(:'role_name', 'gfs_audit_sequence_no_seq', 'UPDATE')"
++ )
+ expect(script).toContain('NOT rolinherit')
+ expect(script).toContain('pg_auth_members')
+ expect(script).toContain("has_table_privilege(:'role_name', 'gfs_resources', 'INSERT')")
+ expect(script).toContain("has_table_privilege(:'role_name', 'gfs_blob_manifests', 'DELETE')")
+ expect(script).toContain(
+ "has_column_privilege(:'role_name', 'control_admin_users', 'id', 'SELECT')"
+ )
+ expect(script).toContain(
+ "has_column_privilege(:'role_name', 'team_members', 'status', 'SELECT')"
+ )
+ expect(script).toContain("column_name NOT IN ('id', 'status')")
+ expect(script).toContain("column_name NOT IN ('team_id', 'user_id', 'status')")
+ expect(script).toContain("'INSERT,UPDATE,REFERENCES'")
+ expect(script).toContain("'DELETE,TRUNCATE,TRIGGER'")
+ })
+
+ it('fails API and decoding errors instead of treating them as absence', () => {
+ expect(script).toContain('cannot read ${GFS_NS}/$secret')
+ expect(script).toContain('contains an invalid $key encoding')
+ expect(script).toContain('[ -n "$encoded" ] || return 0')
+ })
+
+ it('probes preserved reader authentication without exposing connection material', () => {
- const stage = script.slice(script.lastIndexOf('stage-reader)'), script.lastIndexOf('rotate-reader)'))
- expect(stage).toContain('reconcile_credential gfs_controller_reader reader "$READER_SECRET" gfsc-reader false')
++ const stage = script.slice(
++ script.lastIndexOf('stage-reader)'),
++ script.lastIndexOf('rotate-reader)')
++ )
++ expect(stage).toContain(
++ 'reconcile_credential gfs_controller_reader reader "$READER_SECRET" gfsc-reader false'
++ )
+ expect(script).toContain('gfs_dsn_authenticates_as "$1" "$2"')
+ expect(probe).toContain('kc -n "$PG_NS" exec -i "$PG_PROBE_DEPLOY" -- node -e')
+ expect(probe).toContain('await client.query("SELECT current_user")')
+ expect(probe).toContain('[ "$actual" = "$expected_role" ]')
+ expect(probe).toContain('error.code === "28P01" || error.code === "28000"')
+ expect(probe).toContain('[ "$rc" -eq 41 ] && [ "$actual" = GFS_DSN_AUTH_REJECTED ]')
- const roleCheck = script.slice(script.indexOf('verify_role()'), script.indexOf('set_role_password()'))
++ const roleCheck = script.slice(
++ script.indexOf('verify_role()'),
++ script.indexOf('set_role_password()')
++ )
+ expect(roleCheck).toContain('persisted="$(secret_dsn "${!ref_name}")"')
- expect(roleCheck.indexOf('dsn_has_role "$persisted"')).toBeLessThan(roleCheck.indexOf('require_authenticated_dsn "$persisted"'))
- expect(roleCheck.indexOf('require_authenticated_dsn "$persisted"')).toBeLessThan(roleCheck.indexOf('verify_role_contract "$role" "$kind"'))
++ expect(roleCheck.indexOf('dsn_has_role "$persisted"')).toBeLessThan(
++ roleCheck.indexOf('require_authenticated_dsn "$persisted"')
++ )
++ expect(roleCheck.indexOf('require_authenticated_dsn "$persisted"')).toBeLessThan(
++ roleCheck.indexOf('verify_role_contract "$role" "$kind"')
++ )
+ expect(recovery).toContain('die "$3 authentication probe unavailable"')
+ expect(recovery).toContain('authentication probe unavailable; refusing credential mutation')
+ expect(recovery).toContain('disable_role_login "$role"')
+ expect(script).not.toContain('DSN_TO_CHECK=')
+ expect(script).not.toContain('-v role_secret="$password"')
+ expect(script).not.toContain('PGPASSWORD=')
+ expect(script).not.toContain('psql "$dsn"')
+ expect(script).not.toContain('psql "$probe_dsn"')
+ expect(script).not.toContain('-c "SELECT rolcanlogin')
+ expect(script).toContain('-v role_name="$1" -f -')
+ expect(probe).toContain('if not raw or "\\\\" in raw')
+ expect(probe).toContain('ch.isspace() or unicodedata.category(ch).startswith("C")')
+ expect(probe).toContain('parsed.hostname == expected_host')
+ expect(probe).toContain('and not parsed.query')
+ expect(probe).toContain('and not parsed.fragment')
+ expect(probe).toContain('re.fullmatch(r"[0-9a-f]{48}", password)')
+ expect(verifier).toContain('gfs_dsn_authenticates_as "$dsn" "$role"')
+ expect(verifier).not.toContain('psql "$connection"')
+ expect(verifier).toContain('clerum\\.io/gfs-dsn-rotated-at')
+ expect(verifier).toContain('GlobalFileSystem/gfs is not adopted; no GFS instance to verify')
+ expect(verifier).toContain('cannot determine whether GlobalFileSystem/gfs is adopted')
+ expect(verifier).toContain('credential lifecycle is ${lifecycle:-unset}, not ready')
+ expect(verifier).toContain('retains an unfinished credential candidate')
+ expect(script).toContain('pending-connection-string')
+ expect(script).toContain('Resuming persisted pending candidate')
+ expect(script).toContain('Resuming incomplete ${deployment} rollout without rotating again')
+ expect(script).toContain('rollback_uncommitted_candidate')
+ expect(script).toContain('staged credential state was superseded; refusing a stale completion')
+ expect(script).not.toContain('Adopting concurrently staged candidate')
+ expect(script).toContain('GFS_RECOVER_ABANDONED_STATE')
+ expect(recovery).toContain('role_can_login "$role"')
+ expect(recovery).toContain('release_abandoned_candidate "$secret"')
+ expect(transitions).toContain('{"op": "test", "path": state_path, "value": "pending"}')
+ expect(transitions).toContain('{"op": "replace", "path": state_path, "value": "applying"}')
+ expect(transitions).toContain('{"op": "test", "path": state_path, "value": "applying"}')
- expect(transitions).toContain('{"op": "replace", "path": state_path, "value": "rollout-pending"}')
++ expect(transitions).toContain(
++ '{"op": "replace", "path": state_path, "value": "rollout-pending"}'
++ )
+ expect(transitions).toContain('{"op": "test", "path": pending_path, "value": candidate}')
+ expect(rollout).toContain('rollout-running')
+ expect(script).not.toContain('\\quit 1')
+ expect(script.match(/SELECT 1\/0;/g)).toHaveLength(4)
+ })
- expect(rolloutLine).toBeDefined()
- expect(rolloutLine).not.toContain('|| true')
+ it('accepts only the exact persisted endpoint and rejects URI overrides', () => {
- const run = (input: string) => spawnSync(
- 'bash',
- ['-c', 'source "$1"; gfs_dsn_validate "$2" "$3" 5432 profiles', 'bash', probePath, role, host],
- { input, encoding: 'utf8' }
- )
++ const run = (input: string) =>
++ spawnSync(
++ 'bash',
++ [
++ '-c',
++ 'source "$1"; gfs_dsn_validate "$2" "$3" 5432 profiles',
++ 'bash',
++ probePath,
++ role,
++ host,
++ ],
++ { input, encoding: 'utf8' }
++ )
+ const accepted = run(uri(`@${host}:5432/profiles`))
+ expect(accepted.status).toBe(0)
+ expect(accepted.stdout).toBe('')
+ for (const endpoint of [
+ '@wrong.example:5432/profiles',
+ '@[::1]:5432/profiles',
+ `@${host}:5433/profiles`,
+ `@${host}/profiles`,
+ `@${host}:5432/wrong`,
+ `@${host}:5432/profiles?host=example.invalid`,
+ `@${host}:5432/profiles#override`,
+ `@${host}:not-a-port/profiles`,
+ ]) {
+ expect(run(uri(endpoint)).status).not.toBe(0)
+ }
+ expect(run(`postgresql://other:${password}@${host}:5432/profiles`).status).not.toBe(0)
+ expect(run(`postgresql://${role}:@${host}:5432/profiles`).status).not.toBe(0)
+ expect(run(`postgresql://${role}:short@${host}:5432/profiles`).status).not.toBe(0)
+ expect(run(`postgresql://${role}:${'A'.repeat(48)}@${host}:5432/profiles`).status).not.toBe(0)
+ expect(run(`postgresql://${role}:${'%3B'.repeat(48)}@${host}:5432/profiles`).status).not.toBe(0)
+ expect(run(`${uri(`@${host}:5432/profiles`)}\n`).status).not.toBe(0)
})
})
diff --cc control-api/test/gfs.seedResources.test.ts
index bdfddd3bc,45bf57b17..6f31d07d5
--- a/control-api/test/gfs.seedResources.test.ts
+++ b/control-api/test/gfs.seedResources.test.ts
@@@ -139,7 -189,7 +189,13 @@@ describe('DbSeedResourceStore.ensureDir
it('fails loud if neither insert nor select yields a row (no silent empty id)', async () => {
const db = new FakeDb()
- db.responses = [{ rows: [] }, { rows: [] }]
- db.responses = [{ rows: [root] }, { rows: [root] }, { rows: [root] }, { rows: [] }, { rows: [] }]
++ db.responses = [
++ { rows: [root] },
++ { rows: [root] },
++ { rows: [root] },
++ { rows: [] },
++ { rows: [] },
++ ]
await expect(
new DbSeedResourceStore(db).ensureDirectory({
drive: 'main',
diff --cc control-api/test/gfs.seedRouteTransaction.test.ts
index 000000000,759f03668..7fa87145e
mode 000000,100644..100644
--- a/control-api/test/gfs.seedRouteTransaction.test.ts
+++ b/control-api/test/gfs.seedRouteTransaction.test.ts
@@@ -1,0 -1,85 +1,84 @@@
+ import { beforeEach, describe, expect, it, vi } from 'vitest'
++import { handleSeed } from '../src/routes/gfs/seed.js'
+
+ const state = vi.hoisted(() => {
+ const events: string[] = []
+ const db = {
+ query: vi.fn(async (text: string) => {
+ if (text.includes('pg_advisory_xact_lock')) {
+ events.push('advisory')
+ return { rows: [] }
+ }
+ if (text.includes('ORDER BY resource_id FOR UPDATE')) {
+ events.push('root-lock')
+ return { rows: [] }
+ }
+ if (text.includes('INSERT INTO gfs_resources')) {
+ events.push('insert')
+ if (state.failInsert) throw new Error('insert_failed')
+ return { rows: [{ resource_id: 'root-1' }] }
+ }
+ return { rows: [] }
+ }),
+ }
+ return { db, events, failInsert: false }
+ })
+
+ vi.mock('../src/db.js', () => ({
+ withTransaction: vi.fn(async (work: (db: typeof state.db) => Promise<unknown>) => {
+ state.events.push('begin')
+ try {
+ const result = await work(state.db)
+ state.events.push('commit')
+ return result
+ } catch (error) {
+ state.events.push('rollback')
+ throw error
+ }
+ }),
+ }))
+
+ vi.mock('../src/middleware/internalControlJwt.js', () => ({
+ requireInternalControlJwt: (_req: unknown, _res: unknown, next: () => void) => next(),
+ }))
+
-import { handleSeed } from '../src/routes/gfs/seed.js'
-
+ function response() {
+ return {
+ code: 0,
+ body: undefined as unknown,
+ status(code: number) {
+ this.code = code
+ return this
+ },
+ json(body: unknown) {
+ this.body = body
+ return this
+ },
+ }
+ }
+
+ describe('gfs seed route transaction boundary', () => {
+ beforeEach(() => {
+ state.events.length = 0
+ state.failInsert = false
+ state.db.query.mockClear()
+ })
+
+ it('uses one transaction client for lock and seed publication', async () => {
+ const res = response()
+ await handleSeed({ body: { drive: 'main', rootDirectories: [] } } as never, res as never)
+ expect(res.code).toBe(200)
+ expect(state.events).toEqual(['begin', 'advisory', 'root-lock', 'insert', 'commit'])
+ expect(state.db.query).toHaveBeenCalledTimes(3)
+ })
+
+ it('rolls back when seed publication fails', async () => {
+ state.failInsert = true
+ const res = response()
+ await expect(
+ handleSeed({ body: { drive: 'main', rootDirectories: [] } } as never, res as never)
+ ).rejects.toThrow('insert_failed')
+ expect(state.events).toEqual(['begin', 'advisory', 'root-lock', 'insert', 'rollback'])
+ expect(res.code).toBe(0)
+ })
+ })
diff --cc control-api/test/gfsAuditDecisionEvidence.realPostgres.integration.test.ts
index 000000000,0e5168b45..8ed4db116
mode 000000,100644..100644
--- a/control-api/test/gfsAuditDecisionEvidence.realPostgres.integration.test.ts
+++ b/control-api/test/gfsAuditDecisionEvidence.realPostgres.integration.test.ts
@@@ -1,0 -1,187 +1,189 @@@
-import { randomBytes } from 'node:crypto'
+ import { afterAll, beforeAll, describe, expect, it } from 'vitest'
++import { randomBytes } from 'node:crypto'
+ import { Pool, type PoolClient } from 'pg'
+ import { CONTROL_API_MIGRATIONS, initDb } from '../src/db.js'
+
+ const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
+ const describeRealPostgres = adminUrl ? describe : describe.skip
+
+ function databaseUrl(baseUrl: string, database: string): string {
+ const url = new URL(baseUrl)
+ url.pathname = `/${database}`
+ return url.toString()
+ }
+
+ function quoteIdent(value: string): string {
+ return `"${value.replace(/"/g, '""')}"`
+ }
+
+ async function asRole<T>(pool: Pool, role: string, run: (client: PoolClient) => Promise<T>) {
+ const client = await pool.connect()
+ try {
+ await client.query('BEGIN')
+ await client.query(`SET LOCAL ROLE ${quoteIdent(role)}`)
+ const result = await run(client)
+ await client.query('COMMIT')
+ return result
+ } catch (error) {
+ await client.query('ROLLBACK').catch(() => undefined)
+ throw error
+ } finally {
+ client.release()
+ }
+ }
+
+ describeRealPostgres('GFS typed audit decision evidence', () => {
+ const database = `gfs_audit_evidence_${randomBytes(6).toString('hex')}`
+ const connectionString = databaseUrl(
+ adminUrl ?? 'postgresql://[email protected]/postgres',
+ database
+ )
+ let adminPool: Pool
+ let pool: Pool
+
+ beforeAll(async () => {
+ adminPool = new Pool({ connectionString: adminUrl })
+ await adminPool.query(`CREATE DATABASE ${quoteIdent(database)}`)
+ pool = new Pool({ connectionString })
+ await initDb({ connect: () => pool.connect() })
+ }, 60_000)
+
+ afterAll(async () => {
+ await pool?.end()
+ if (!adminPool) return
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ await adminPool.end()
+ })
+
+ it('is additive, idempotent, and constrains the evidence vocabulary', async () => {
+ const migration = CONTROL_API_MIGRATIONS.find(
+ candidate => candidate.version === '0073_gfs_audit_decision_evidence'
+ )
+ expect(migration).toBeDefined()
+ await migration!.apply(pool)
+
+ const columns = await pool.query(
+ `SELECT column_name, is_nullable, column_default
+ FROM information_schema.columns
+ WHERE table_schema = 'public'
+ AND table_name = 'gfs_audit'
+ AND column_name = ANY($1::text[])
+ ORDER BY column_name`,
- [[
- 'record_type',
- 'matched_subject',
- 'authorization_source',
- 'cached_authorization_source',
- 'mutation_outcome',
- ]]
++ [
++ [
++ 'record_type',
++ 'matched_subject',
++ 'authorization_source',
++ 'cached_authorization_source',
++ 'mutation_outcome',
++ ],
++ ]
+ )
+ expect(columns.rows).toHaveLength(5)
+ expect(columns.rows.find(row => row.column_name === 'record_type')).toMatchObject({
+ is_nullable: 'NO',
+ column_default: "'legacy'::text",
+ })
+
+ const constraints = await pool.query(
+ `SELECT conname
+ FROM pg_constraint
+ WHERE conrelid = 'gfs_audit'::regclass
+ AND conname LIKE 'gfs_audit_%_valid'`
+ )
+ expect(new Set(constraints.rows.map(row => row.conname))).toEqual(
+ new Set([
+ 'gfs_audit_record_type_valid',
+ 'gfs_audit_authorization_source_valid',
+ 'gfs_audit_cached_authorization_source_valid',
+ 'gfs_audit_mutation_outcome_valid',
+ 'gfs_audit_record_type_fields_valid',
+ ])
+ )
+
+ await pool.query(
+ `INSERT INTO gfs_audit (subject, op, outcome, row_hash)
+ VALUES ('host:legacy', 'read', 'allow', 'legacy-hash')`
+ )
+ const legacy = await pool.query(
+ `SELECT record_type, matched_subject, authorization_source,
+ cached_authorization_source, mutation_outcome
+ FROM gfs_audit WHERE row_hash = 'legacy-hash'`
+ )
+ expect(legacy.rows[0]).toEqual({
+ record_type: 'legacy',
+ matched_subject: null,
+ authorization_source: null,
+ cached_authorization_source: null,
+ mutation_outcome: null,
+ })
+
+ await expect(
+ pool.query(
+ `INSERT INTO gfs_audit
+ (subject, op, outcome, row_hash, record_type, authorization_source)
+ VALUES ('host:bad', 'read', 'allow', 'bad-source',
+ 'authorization_decision', 'standalone')`
+ )
+ ).rejects.toMatchObject({ code: '23514' })
+ await expect(
+ pool.query(
+ `INSERT INTO gfs_audit
+ (subject, op, outcome, row_hash, record_type, authorization_source)
+ VALUES ('host:bad', 'read', 'allow', 'cache-without-source',
+ 'authorization_decision', 'cache')`
+ )
+ ).rejects.toMatchObject({ code: '23514' })
+ })
+
+ it.each(['gfs_controller', 'gfs_controller_reader'])(
+ '%s can append typed evidence but cannot update or delete it',
+ async role => {
+ const rowHash = `${role}-decision-${randomBytes(4).toString('hex')}`
+ await asRole(pool, role, client =>
+ client.query(
+ `INSERT INTO gfs_audit
+ (subject, op, outcome, row_hash, record_type, matched_subject,
+ authorization_source, cached_authorization_source)
+ VALUES ('host:actor', 'read', 'allow', $1, 'authorization_decision',
+ 'host:actor', 'cache', 'direct_grant')`,
+ [rowHash]
+ )
+ )
+
+ await expect(
+ asRole(pool, role, client =>
+ client.query(`UPDATE gfs_audit SET outcome = 'deny' WHERE false`)
+ )
+ ).rejects.toMatchObject({ code: '42501' })
+ await expect(
+ asRole(pool, role, client => client.query(`DELETE FROM gfs_audit WHERE false`))
+ ).rejects.toMatchObject({ code: '42501' })
+ }
+ )
+
+ it('records actual mutation outcome separately from the authorization decision', async () => {
+ await asRole(pool, 'gfs_controller', client =>
+ client.query(
+ `INSERT INTO gfs_audit
+ (subject, op, outcome, row_hash, record_type, matched_subject,
+ authorization_source, mutation_outcome)
+ VALUES ('host:actor', 'copy', 'error', 'mutation-failed', 'mutation_outcome',
+ 'host:actor', 'direct_grant', 'failed')`
+ )
+ )
+ await expect(
+ pool.query(
+ `INSERT INTO gfs_audit
+ (subject, op, outcome, row_hash, record_type, mutation_outcome)
+ VALUES ('host:bad', 'copy', 'allow', 'decision-with-mutation',
+ 'authorization_decision', 'succeeded')`
+ )
+ ).rejects.toMatchObject({ code: '23514' })
+ })
+ })
diff --cc control-api/test/gfsBlobMigration.realPostgres.integration.test.ts
index 000000000,1d9bea0e4..20eea0d10
mode 000000,100644..100644
--- a/control-api/test/gfsBlobMigration.realPostgres.integration.test.ts
+++ b/control-api/test/gfsBlobMigration.realPostgres.integration.test.ts
@@@ -1,0 -1,139 +1,159 @@@
-import { randomBytes, randomUUID } from 'node:crypto'
+ import { afterAll, beforeAll, describe, expect, it } from 'vitest'
++import { randomBytes, randomUUID } from 'node:crypto'
+ import { Pool } from 'pg'
+ import { initDb } from '../src/db.js'
+
+ const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
+ const describeRealPostgres = adminUrl ? describe : describe.skip
+
+ function databaseUrl(baseUrl: string, database: string): string {
+ const url = new URL(baseUrl)
+ url.pathname = `/${database}`
+ return url.toString()
+ }
+
+ function quoteIdent(value: string): string {
+ return `"${value.replace(/"/g, '""')}"`
+ }
+
+ describeRealPostgres('GFS immutable blob migration on real PostgreSQL', () => {
+ const database = `gfs_blob_migration_${randomBytes(6).toString('hex')}`
+ const connectionString = databaseUrl(
+ adminUrl ?? 'postgresql://[email protected]/postgres',
+ database
+ )
+ let adminPool: Pool
+ let pool: Pool
+
+ beforeAll(async () => {
+ adminPool = new Pool({ connectionString: adminUrl })
+ await adminPool.query(`CREATE DATABASE ${quoteIdent(database)}`)
+ pool = new Pool({ connectionString })
+ const connector = { connect: () => pool.connect() }
+ await initDb(connector)
+ await initDb(connector)
+ }, 60_000)
+
+ afterAll(async () => {
+ await pool?.end()
+ if (!adminPool) return
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ await adminPool.end()
+ })
+
+ it('applies 0068 exactly once with named constraints, indexes, and writer ACL', async () => {
+ const versions = await pool.query<{ count: string }>(
+ `SELECT count(*)::text AS count FROM schema_migrations
+ WHERE version = '0071_gfs_immutable_blob_generations'`
+ )
+ expect(versions.rows).toEqual([{ count: '1' }])
+
+ const columns = await pool.query<{ column_name: string; is_nullable: string }>(
+ `SELECT column_name,is_nullable FROM information_schema.columns
+ WHERE table_schema='public' AND table_name='gfs_blob_manifests'
+ ORDER BY ordinal_position`
+ )
+ expect(columns.rows.map(row => row.column_name)).toEqual([
- 'blob_key', 'request_id', 'resource_id', 'candidate_kind', 'content_sha256',
- 'bytes', 'state', 'created_at', 'updated_at',
++ 'blob_key',
++ 'request_id',
++ 'resource_id',
++ 'candidate_kind',
++ 'content_sha256',
++ 'bytes',
++ 'state',
++ 'created_at',
++ 'updated_at',
+ ])
+ expect(columns.rows.find(row => row.column_name === 'content_sha256')?.is_nullable).toBe('YES')
+
+ const constraints = await pool.query<{ conname: string; definition: string }>(
+ `SELECT conname,pg_get_constraintdef(oid) AS definition FROM pg_constraint
+ WHERE conrelid IN ('gfs_resources'::regclass,'gfs_blob_manifests'::regclass)
+ AND conname IN ('gfs_resources_blob_metadata_pair','gfs_blob_manifests_blob_key_valid')
+ ORDER BY conname`
+ )
+ expect(constraints.rows.map(row => row.conname)).toEqual([
- 'gfs_blob_manifests_blob_key_valid', 'gfs_resources_blob_metadata_pair',
++ 'gfs_blob_manifests_blob_key_valid',
++ 'gfs_resources_blob_metadata_pair',
+ ])
+ expect(constraints.rows.map(row => row.definition).join(' ')).toMatch(
+ /generation.*legacy_flat.*content_sha256 IS NULL/s
+ )
+
+ const indexes = await pool.query<{ indexname: string; indexdef: string }>(
+ `SELECT indexname,indexdef FROM pg_indexes WHERE schemaname='public'
+ AND indexname IN ('gfs_resources_blob_key_uniq','gfs_blob_manifests_cleanup_idx')
+ ORDER BY indexname`
+ )
+ expect(indexes.rows.map(row => row.indexname)).toEqual([
- 'gfs_blob_manifests_cleanup_idx', 'gfs_resources_blob_key_uniq',
++ 'gfs_blob_manifests_cleanup_idx',
++ 'gfs_resources_blob_key_uniq',
+ ])
+ expect(indexes.rows[0]?.indexdef).toContain('(state, updated_at, blob_key)')
+ expect(indexes.rows[1]?.indexdef).toContain('WHERE (blob_key IS NOT NULL)')
+
+ const acl = await pool.query<Record<string, boolean>>(`
+ SELECT has_table_privilege('gfs_controller','gfs_resources','SELECT') AS resource_read,
+ has_table_privilege('gfs_controller','gfs_resources','INSERT') AS resource_insert,
+ has_table_privilege('gfs_controller','gfs_resources','UPDATE') AS resource_update,
+ has_table_privilege('gfs_controller','gfs_resources','DELETE') AS resource_delete,
+ has_table_privilege('gfs_controller','gfs_blob_manifests','SELECT') AS manifest_read,
+ has_table_privilege('gfs_controller','gfs_blob_manifests','INSERT') AS manifest_insert,
+ has_table_privilege('gfs_controller','gfs_blob_manifests','UPDATE') AS manifest_update,
+ has_table_privilege('gfs_controller','gfs_blob_manifests','DELETE') AS manifest_delete`)
+ expect(acl.rows[0]).toEqual({
- resource_read: true, resource_insert: true, resource_update: true, resource_delete: false,
- manifest_read: true, manifest_insert: true, manifest_update: true, manifest_delete: true,
++ resource_read: true,
++ resource_insert: true,
++ resource_update: true,
++ resource_delete: false,
++ manifest_read: true,
++ manifest_insert: true,
++ manifest_update: true,
++ manifest_delete: true,
+ })
+ })
+
+ it('enforces generation ownership and permits only typed legacy cleanup candidates', async () => {
+ const rootId = randomUUID()
+ const resourceId = randomUUID()
+ const drive = `blob-shape-${randomBytes(4).toString('hex')}`
+ await pool.query(
+ `INSERT INTO gfs_resources(resource_id,drive,parent_resource_id,name,kind,path_cache)
+ VALUES ($1,$3,NULL,'','directory','/'),($2,$3,$1,'file.txt','file','/file.txt')`,
+ [rootId, resourceId, drive]
+ )
+ const compactId = resourceId.replaceAll('-', '')
+ const generationKey = `${compactId}/${randomUUID()}`
+ await pool.query(
+ `UPDATE gfs_resources SET blob_key=$2,content_sha256=$3 WHERE resource_id=$1`,
+ [resourceId, generationKey, 'a'.repeat(64)]
+ )
- await expect(pool.query(
- `UPDATE gfs_resources SET blob_key=$2,content_sha256=$3 WHERE resource_id=$1`,
- [resourceId, `${rootId.replaceAll('-', '')}/${randomUUID()}`, 'a'.repeat(64)]
- )).rejects.toMatchObject({ code: '23514' })
++ await expect(
++ pool.query(`UPDATE gfs_resources SET blob_key=$2,content_sha256=$3 WHERE resource_id=$1`, [
++ resourceId,
++ `${rootId.replaceAll('-', '')}/${randomUUID()}`,
++ 'a'.repeat(64),
++ ])
++ ).rejects.toMatchObject({ code: '23514' })
+ await pool.query(
+ `INSERT INTO gfs_blob_manifests
+ (blob_key,request_id,resource_id,candidate_kind,content_sha256,bytes,state)
+ VALUES ($1,$2,$3,'generation',$4,1,'staged'),
+ ($5,$6,$3,'legacy_flat',NULL,1,'deleting')`,
+ [generationKey, randomUUID(), resourceId, 'a'.repeat(64), compactId, randomUUID()]
+ )
- await expect(pool.query(
- `INSERT INTO gfs_blob_manifests
++ await expect(
++ pool.query(
++ `INSERT INTO gfs_blob_manifests
+ (blob_key,request_id,resource_id,candidate_kind,content_sha256,bytes,state)
+ VALUES ($1,$2,$3,'legacy_flat',$4,1,'deleting')`,
- [rootId.replaceAll('-', ''), randomUUID(), rootId, 'b'.repeat(64)]
- )).rejects.toMatchObject({ code: '23514' })
++ [rootId.replaceAll('-', ''), randomUUID(), rootId, 'b'.repeat(64)]
++ )
++ ).rejects.toMatchObject({ code: '23514' })
+ })
+ })
diff --cc control-api/test/gfsBlobReconciliation.realPostgres.integration.test.ts
index 000000000,5007419cf..9b66ae892
mode 000000,100644..100644
--- a/control-api/test/gfsBlobReconciliation.realPostgres.integration.test.ts
+++ b/control-api/test/gfsBlobReconciliation.realPostgres.integration.test.ts
@@@ -1,0 -1,229 +1,234 @@@
++import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'
+ import { randomBytes, randomUUID } from 'node:crypto'
+ import { existsSync } from 'node:fs'
+ import { mkdtemp, rm, writeFile } from 'node:fs/promises'
+ import { tmpdir } from 'node:os'
+ import { join } from 'node:path'
+ import { Pool } from 'pg'
-import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'
-import { initDb } from '../src/db.js'
-import { PgBlobStagingStore } from '../../gfs-controller/src/db/blobStaging.js'
+ import { reconcileExpiredBlobs } from '../../gfs-controller/src/db/blobReconciliation.js'
++import { PgBlobStagingStore } from '../../gfs-controller/src/db/blobStaging.js'
++import type { GfsMetrics } from '../../gfs-controller/src/metrics.js'
+ import { BlobStore } from '../../gfs-controller/src/storage/blobStore.js'
+ import { resolveBlobKeyPath, resolveBlobPath } from '../../gfs-controller/src/storage/paths.js'
-import type { GfsMetrics } from '../../gfs-controller/src/metrics.js'
++import { initDb } from '../src/db.js'
+
+ // This suite closes the reconciler's HIGH coverage gap: reconcileExpiredBlobs is
+ // the sole backstop for the write/copy paths' swallowed cleanup errors, yet its
+ // orphan-vs-referenced predicate and its real byte deletion were only ever
+ // exercised against a FakeDb with a stubbed deleteByKey. Here it runs against a
+ // real Postgres schema + a real on-disk BlobStore, asserting business-truth:
+ // actual bytes on the PVC and actual manifest rows.
+ const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
+ const describeRealPostgres = adminUrl ? describe : describe.skip
+
+ function databaseUrl(baseUrl: string, database: string): string {
+ const url = new URL(baseUrl)
+ url.pathname = `/${database}`
+ return url.toString()
+ }
+
+ function quoteIdent(value: string): string {
+ return `"${value.replace(/"/g, '""')}"`
+ }
+
+ // reconcileExpiredBlobs only calls setOrphanCandidates + recordBlobCleanupFailure;
+ // a minimal recording stub keeps the test off prom-client while still proving the
+ // failure counter is never touched on the happy paths.
+ function metricsStub(): { metrics: GfsMetrics; failures: number } {
+ const state = { failures: 0 }
+ const metrics = {
+ setOrphanCandidates: () => undefined,
+ recordBlobCleanupFailure: () => {
+ state.failures += 1
+ },
+ } as unknown as GfsMetrics
+ return {
+ metrics,
+ get failures() {
+ return state.failures
+ },
+ }
+ }
+
+ describeRealPostgres('GFS blob reconciliation on real PostgreSQL + on-disk BlobStore', () => {
+ const database = `gfs_recon_${randomBytes(6).toString('hex')}`
- const connectionString = databaseUrl(adminUrl ?? 'postgresql://[email protected]/postgres', database)
++ const connectionString = databaseUrl(
++ adminUrl ?? 'postgresql://[email protected]/postgres',
++ database
++ )
+ let adminPool: Pool
+ let pool: Pool
+ let blobRoot: string
+ let blobs: BlobStore
+ let manifests: PgBlobStagingStore
+
+ // Age a just-staged manifest so it clears the reconciler's `updated_at <
+ // now() - olderThanMs` gate deterministically (no sleep, no flake).
+ async function ageCandidate(blobKey: string): Promise<void> {
+ await pool.query(
+ `UPDATE gfs_blob_manifests SET updated_at = now() - interval '1 hour' WHERE blob_key = $1`,
+ [blobKey]
+ )
+ }
+
+ async function manifestExists(blobKey: string): Promise<boolean> {
+ const res = await pool.query('SELECT 1 FROM gfs_blob_manifests WHERE blob_key = $1', [blobKey])
+ return (res.rowCount ?? 0) > 0
+ }
+
+ async function manifestState(blobKey: string): Promise<string | null> {
- const res = await pool.query('SELECT state FROM gfs_blob_manifests WHERE blob_key = $1', [blobKey])
++ const res = await pool.query('SELECT state FROM gfs_blob_manifests WHERE blob_key = $1', [
++ blobKey,
++ ])
+ return res.rows[0]?.state ?? null
+ }
+
+ beforeAll(async () => {
+ adminPool = new Pool({ connectionString: adminUrl })
+ await adminPool.query(`CREATE DATABASE ${quoteIdent(database)}`)
+ pool = new Pool({ connectionString })
+ await initDb({ connect: () => pool.connect() })
+ blobRoot = await mkdtemp(join(tmpdir(), 'gfs-recon-real-pg-'))
+ blobs = new BlobStore(blobRoot, 'writer')
+ manifests = new PgBlobStagingStore(pool)
+ }, 60_000)
+
+ afterEach(async () => {
+ // Reconciliation scans the whole table; isolate each case's business-truth by
+ // clearing manifests + resources between cases (orphaned bytes with unique
+ // UUIDs left on disk cannot collide with the next case's assertions).
+ await pool.query('TRUNCATE gfs_blob_manifests, gfs_resources CASCADE')
+ })
+
+ afterAll(async () => {
+ await pool?.end()
+ await rm(blobRoot, { recursive: true, force: true }).catch(() => undefined)
+ if (!adminPool) return
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ await adminPool.end()
+ })
+
+ it('reaps an orphaned generation blob: deletes the real bytes AND removes the manifest row', async () => {
+ const resourceId = randomUUID()
+ const payload = randomBytes(96)
+ const written = await blobs.writeImmutable(resourceId, randomUUID(), payload)
+ await manifests.recordStaged({
+ blobKey: written.blobKey,
+ requestId: randomUUID(),
+ resourceId,
+ candidateKind: 'generation',
+ contentSha256: written.contentSha256,
+ bytes: written.bytes,
+ })
+ await ageCandidate(written.blobKey)
+
+ // Precondition: real bytes on disk, manifest row present, NO gfs_resources
+ // row references this blob_key (it is a genuine orphan).
+ const blobPath = resolveBlobKeyPath(blobRoot, written.blobKey)
+ expect(existsSync(blobPath)).toBe(true)
+ expect(await manifestExists(written.blobKey)).toBe(true)
+
+ const recorder = metricsStub()
+ const result = await reconcileExpiredBlobs(manifests, blobs, recorder.metrics, {
+ olderThanMs: 1000,
+ limit: 16,
+ })
+
+ expect(result.deleted).toBe(1)
+ expect(result.failures).toBe(0)
+ // Read the recording stub too: the reconciler's failure metric must stay
+ // untouched, not just its returned tally.
+ expect(recorder.failures).toBe(0)
+ // Business-truth: the bytes are gone from the PVC and the manifest row is gone.
+ expect(existsSync(blobPath)).toBe(false)
+ expect(await manifestExists(written.blobKey)).toBe(false)
+ })
+
+ it('never deletes a generation blob still referenced by a live resource', async () => {
+ const rootId = randomUUID()
+ const fileId = randomUUID()
+ const drive = `recon-ref-${randomBytes(4).toString('hex')}`
+ const payload = randomBytes(96)
+ const written = await blobs.writeImmutable(fileId, randomUUID(), payload)
+ await manifests.recordStaged({
+ blobKey: written.blobKey,
+ requestId: randomUUID(),
+ resourceId: fileId,
+ candidateKind: 'generation',
+ contentSha256: written.contentSha256,
+ bytes: written.bytes,
+ })
+ // A live gfs_resources row references the blob_key — this must protect it.
+ await pool.query(
+ `INSERT INTO gfs_resources
+ (resource_id, drive, parent_resource_id, name, kind, path_cache, version, bytes, blob_key, content_sha256)
+ VALUES
+ ($1,$3,NULL,'','directory','/',0,0,NULL,NULL),
+ ($2,$3,$1,'ref.txt','file','/ref.txt',1,$4,$5,$6)`,
+ [rootId, fileId, drive, written.bytes, written.blobKey, written.contentSha256]
+ )
+ await ageCandidate(written.blobKey)
+
+ const blobPath = resolveBlobKeyPath(blobRoot, written.blobKey)
+ const recorder = metricsStub()
+ const result = await reconcileExpiredBlobs(manifests, blobs, recorder.metrics, {
+ olderThanMs: 1000,
+ limit: 16,
+ })
+
+ // The real NOT EXISTS predicate must exclude the referenced blob from the
+ // delete claim, so no bytes are deleted and the bytes survive on the PVC.
+ expect(result.deleted).toBe(0)
+ expect(result.failures).toBe(0)
+ // Read the recording stub too: the reconciler's failure metric must stay
+ // untouched, not just its returned tally.
+ expect(recorder.failures).toBe(0)
+ // Business-truth that matters: the bytes are protected.
+ expect(existsSync(blobPath)).toBe(true)
+ // The now-redundant staged manifest IS metadata-GC'd by removeCommittedMetadata
+ // (the gfs_resources.blob_key reference is the source of truth) — only the
+ // bytes are protected, never re-deleted. This asserts the GC does NOT touch bytes.
+ expect(await manifestExists(written.blobKey)).toBe(false)
+ })
+
+ it('reaps a legacy_flat orphan through the legacy predicate and deletes the flat bytes', async () => {
+ const resourceId = randomUUID()
+ const legacyPath = resolveBlobPath(blobRoot, resourceId)
+ // A legacy_flat blob's manifest key IS the dash-stripped resource id (the
+ // blob_key_valid CHECK: `blob_key = replace(resource_id,'-','')`); legacy
+ // candidates carry no committed digest (content_sha256 IS NULL).
+ const legacyBlobKey = resourceId.replace(/-/g, '')
+ await writeFile(legacyPath, randomBytes(48), { mode: 0o600 })
+ await manifests.recordStaged({
+ blobKey: legacyBlobKey,
+ requestId: randomUUID(),
+ resourceId,
+ candidateKind: 'legacy_flat',
+ contentSha256: null,
+ bytes: 48,
+ })
+ await ageCandidate(legacyBlobKey)
+
+ expect(existsSync(legacyPath)).toBe(true)
+ const recorder = metricsStub()
+ const result = await reconcileExpiredBlobs(manifests, blobs, recorder.metrics, {
+ olderThanMs: 1000,
+ limit: 16,
+ })
+
+ expect(result.deleted).toBe(1)
+ expect(result.failures).toBe(0)
+ // Read the recording stub too: the reconciler's failure metric must stay
+ // untouched, not just its returned tally.
+ expect(recorder.failures).toBe(0)
+ // Business-truth: the flat legacy bytes are gone and the manifest row is gone.
+ expect(existsSync(legacyPath)).toBe(false)
+ expect(await manifestExists(legacyBlobKey)).toBe(false)
+ expect(await manifestState(legacyBlobKey)).toBeNull()
+ })
+ })
diff --cc control-api/test/gfsCopy.realPostgres.integration.test.ts
index 000000000,710a2463a..50a7399a0
mode 000000,100644..100644
--- a/control-api/test/gfsCopy.realPostgres.integration.test.ts
+++ b/control-api/test/gfsCopy.realPostgres.integration.test.ts
@@@ -1,0 -1,374 +1,408 @@@
++import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+ import { randomBytes, randomUUID } from 'node:crypto'
+ import { mkdtemp, rm } from 'node:fs/promises'
+ import { tmpdir } from 'node:os'
+ import { join } from 'node:path'
-import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+ import { Pool } from 'pg'
-import { initDb } from '../src/db.js'
+ import { preflightCopy } from '../../gfs-controller/src/api/copy.js'
+ import { DbAuditSink } from '../../gfs-controller/src/authz/audit.js'
+ import { PgBlobStagingStore } from '../../gfs-controller/src/db/blobStaging.js'
+ import { PgResourceStore } from '../../gfs-controller/src/db/resourceStore.js'
+ import { GfsWriteService, PgTransactor } from '../../gfs-controller/src/db/writeStore.js'
+ import { BlobStore } from '../../gfs-controller/src/storage/blobStore.js'
++import { initDb } from '../src/db.js'
+
+ const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
+ const describeRealPostgres = adminUrl ? describe : describe.skip
+
+ function databaseUrl(baseUrl: string, database: string): string {
+ const url = new URL(baseUrl)
+ url.pathname = `/${database}`
+ return url.toString()
+ }
+
+ function quoteIdent(value: string): string {
+ return `"${value.replace(/"/g, '""')}"`
+ }
+
+ function compact(id: string): string {
+ return id.replaceAll('-', '').toLowerCase()
+ }
+
+ async function readAll(stream: NodeJS.ReadableStream): Promise<Buffer> {
+ const chunks: Buffer[] = []
+ for await (const chunk of stream) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))
+ return Buffer.concat(chunks)
+ }
+
+ interface SeededTree {
+ drive: string
+ rootId: string
+ sourceId: string
+ nestedId: string
+ firstFileId: string
+ secondFileId: string
+ destinationId: string
+ files: Map<string, Buffer>
+ }
+
+ describeRealPostgres('GFS Copy publication on real PostgreSQL and filesystem blobs', () => {
+ const database = `gfs_copy_${randomBytes(6).toString('hex')}`
+ const connectionString = databaseUrl(
+ adminUrl ?? 'postgresql://[email protected]/postgres',
+ database
+ )
+ let adminPool: Pool
+ let pool: Pool
+ let blobRoot: string
+ let blobs: BlobStore
+ let resources: PgResourceStore
+ let writes: GfsWriteService
+ let audit: DbAuditSink
+
+ async function seedTree(label: string): Promise<SeededTree> {
+ const tree: SeededTree = {
+ drive: `copy-${label}-${randomBytes(4).toString('hex')}`,
+ rootId: randomUUID(),
+ sourceId: randomUUID(),
+ nestedId: randomUUID(),
+ firstFileId: randomUUID(),
+ secondFileId: randomUUID(),
+ destinationId: randomUUID(),
+ files: new Map([
+ ['first', Buffer.from(`first-${label}`)],
+ ['second', Buffer.from(`second-${label}-payload`)],
+ ]),
+ }
- const firstBlob = await blobs.writeImmutable(tree.firstFileId, randomUUID(), tree.files.get('first')!)
- const secondBlob = await blobs.writeImmutable(tree.secondFileId, randomUUID(), tree.files.get('second')!)
++ const firstBlob = await blobs.writeImmutable(
++ tree.firstFileId,
++ randomUUID(),
++ tree.files.get('first')!
++ )
++ const secondBlob = await blobs.writeImmutable(
++ tree.secondFileId,
++ randomUUID(),
++ tree.files.get('second')!
++ )
+ await pool.query(
+ `INSERT INTO gfs_resources
+ (resource_id, drive, parent_resource_id, name, kind, path_cache, version,
+ bytes, blob_key, content_sha256)
+ VALUES
+ ($1,$7,NULL,'','directory','/',0,0,NULL,NULL),
+ ($2,$7,$1,'source','directory','/source',3,0,NULL,NULL),
+ ($3,$7,$2,'nested','directory','/source/nested',0,0,NULL,NULL),
+ ($4,$7,$2,'first.txt','file','/source/first.txt',1,$8,$9,$10),
+ ($5,$7,$3,'second.txt','file','/source/nested/second.txt',2,$11,$12,$13),
+ ($6,$7,$1,'archive','directory','/archive',0,0,NULL,NULL)`,
+ [
+ tree.rootId,
+ tree.sourceId,
+ tree.nestedId,
+ tree.firstFileId,
+ tree.secondFileId,
+ tree.destinationId,
+ tree.drive,
+ firstBlob.bytes,
+ firstBlob.blobKey,
+ firstBlob.contentSha256,
+ secondBlob.bytes,
+ secondBlob.blobKey,
+ secondBlob.contentSha256,
+ ]
+ )
+ return tree
+ }
+
+ async function planFor(tree: SeededTree, newName?: string) {
+ const snapshot = await resources.loadCopySnapshot(tree.drive, tree.sourceId, 1_001n)
+ const rootName = newName ?? snapshot.find(node => node.depth === 0)!.name
- const destination = await resources.loadCopyDestination(tree.drive, tree.destinationId, rootName)
++ const destination = await resources.loadCopyDestination(
++ tree.drive,
++ tree.destinationId,
++ rootName
++ )
+ return {
+ snapshot,
+ destination,
+ plan: preflightCopy({
+ drive: tree.drive,
+ sourceResourceId: tree.sourceId,
+ destinationParentId: tree.destinationId,
+ newName,
+ ifMatch: 3,
+ snapshot,
+ destination,
+ maxObjects: 1_000,
+ maxBytes: 1_073_741_824,
+ deadlineAtMs: Date.now() + 30_000,
+ nowMs: Date.now(),
+ }),
+ }
+ }
+
+ beforeAll(async () => {
+ adminPool = new Pool({ connectionString: adminUrl })
+ await adminPool.query(`CREATE DATABASE ${quoteIdent(database)}`)
+ pool = new Pool({ connectionString })
+ await initDb({ connect: () => pool.connect() })
+ blobRoot = await mkdtemp(join(tmpdir(), 'gfs-copy-real-pg-'))
+ blobs = new BlobStore(blobRoot, 'writer')
+ resources = new PgResourceStore(pool)
+ audit = new DbAuditSink(pool)
+ writes = new GfsWriteService(new PgTransactor(pool), blobs, new PgBlobStagingStore(pool))
+ }, 60_000)
+
+ afterAll(async () => {
+ await pool?.end()
+ await rm(blobRoot, { recursive: true, force: true }).catch(() => undefined)
+ if (!adminPool) return
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ await adminPool.end()
+ })
+
+ it('publishes a recursive copy atomically, preserves the source, and records success in the publication transaction', async () => {
+ const tree = await seedTree('success')
+ const before = await pool.query(
+ `SELECT resource_id, parent_resource_id, path_cache, version, bytes, blob_key, content_sha256
+ FROM gfs_resources WHERE drive=$1 ORDER BY resource_id`,
+ [tree.drive]
+ )
+ const frozen = await planFor(tree, 'source-copy')
+ const requestId = randomUUID()
+ const result = await writes.copy({
+ requestId,
+ subject: 'host:sandbox-recipes/copy-real-pg',
+ audit,
+ drive: tree.drive,
+ destinationParentId: tree.destinationId,
+ plan: frozen.plan,
+ destination: frozen.destination,
+ deadlineAtMs: Date.now() + 30_000,
+ })
+
+ expect(result).toMatchObject({ objectCount: 4, fileCount: 2, folderCount: 2 })
+ expect(result.totalBytes).toBe(
+ BigInt(tree.files.get('first')!.length + tree.files.get('second')!.length)
+ )
+ const sourceAfter = await pool.query(
+ `SELECT resource_id, parent_resource_id, path_cache, version, bytes, blob_key, content_sha256
+ FROM gfs_resources WHERE drive=$1 AND path_cache NOT LIKE '/archive/source-copy%' ORDER BY resource_id`,
+ [tree.drive]
+ )
+ expect(sourceAfter.rows).toEqual(before.rows)
+
+ const copied = await pool.query(
+ `SELECT resource_id, parent_resource_id, path_cache, kind, bytes, blob_key, content_sha256, xmin::text AS txid
+ FROM gfs_resources WHERE drive=$1 AND path_cache LIKE '/archive/source-copy%'
+ ORDER BY path_cache`,
+ [tree.drive]
+ )
+ expect(copied.rows.map(row => row.path_cache)).toEqual([
+ '/archive/source-copy',
+ '/archive/source-copy/first.txt',
+ '/archive/source-copy/nested',
+ '/archive/source-copy/nested/second.txt',
+ ])
- const sourceIds = new Set([tree.sourceId, tree.nestedId, tree.firstFileId, tree.secondFileId].map(compact))
- expect(copied.rows.every(row => !sourceIds.has(compact(String(row.resource_id))))).toBe(true)
- expect(copied.rows.filter(row => row.kind === 'file').map(row => Number(row.bytes)).sort((a, b) => a - b)).toEqual(
- [...tree.files.values()].map(value => value.length).sort((a, b) => a - b)
++ const sourceIds = new Set(
++ [tree.sourceId, tree.nestedId, tree.firstFileId, tree.secondFileId].map(compact)
+ )
++ expect(copied.rows.every(row => !sourceIds.has(compact(String(row.resource_id))))).toBe(true)
++ expect(
++ copied.rows
++ .filter(row => row.kind === 'file')
++ .map(row => Number(row.bytes))
++ .sort((a, b) => a - b)
++ ).toEqual([...tree.files.values()].map(value => value.length).sort((a, b) => a - b))
+
+ const copiedFiles = copied.rows.filter(row => row.kind === 'file')
+ const copiedPayloads = await Promise.all(
- copiedFiles.map(async row => readAll(await blobs.read(String(row.resource_id), String(row.blob_key))))
++ copiedFiles.map(async row =>
++ readAll(await blobs.read(String(row.resource_id), String(row.blob_key)))
++ )
+ )
+ expect(copiedPayloads.map(value => value.toString()).sort()).toEqual(
+ [...tree.files.values()].map(value => value.toString()).sort()
+ )
+
+ const outcome = await pool.query(
+ `SELECT op, record_type, mutation_outcome, request_id, xmin::text AS txid
+ FROM gfs_audit WHERE request_id=$1`,
+ [requestId]
+ )
+ expect(outcome.rows).toHaveLength(1)
+ expect(outcome.rows[0]).toMatchObject({
+ op: 'copy',
+ record_type: 'mutation_outcome',
+ mutation_outcome: 'succeeded',
+ request_id: requestId,
+ })
+ expect(new Set(copied.rows.map(row => row.txid))).toEqual(new Set([outcome.rows[0]?.txid]))
+ })
+
+ it('rejects a destination collision before staging or publishing any node', async () => {
+ const tree = await seedTree('collision')
+ await pool.query(
+ `INSERT INTO gfs_resources(resource_id,drive,parent_resource_id,name,kind,path_cache,version,bytes)
+ VALUES ($1,$2,$3,'source','directory','/archive/source',0,0)`,
+ [randomUUID(), tree.drive, tree.destinationId]
+ )
- const before = await pool.query(`SELECT count(*)::integer AS count FROM gfs_resources WHERE drive=$1`, [tree.drive])
++ const before = await pool.query(
++ `SELECT count(*)::integer AS count FROM gfs_resources WHERE drive=$1`,
++ [tree.drive]
++ )
+ const snapshot = await resources.loadCopySnapshot(tree.drive, tree.sourceId, 1_001n)
- const destination = await resources.loadCopyDestination(tree.drive, tree.destinationId, 'source')
- expect(() => preflightCopy({
- drive: tree.drive,
- sourceResourceId: tree.sourceId,
- destinationParentId: tree.destinationId,
- ifMatch: 3,
- snapshot,
- destination,
- maxObjects: 1_000,
- maxBytes: 1_073_741_824,
- deadlineAtMs: Date.now() + 30_000,
- nowMs: Date.now(),
- })).toThrow(expect.objectContaining({ code: 'already_exists' }))
- const after = await pool.query(`SELECT count(*)::integer AS count FROM gfs_resources WHERE drive=$1`, [tree.drive])
++ const destination = await resources.loadCopyDestination(
++ tree.drive,
++ tree.destinationId,
++ 'source'
++ )
++ expect(() =>
++ preflightCopy({
++ drive: tree.drive,
++ sourceResourceId: tree.sourceId,
++ destinationParentId: tree.destinationId,
++ ifMatch: 3,
++ snapshot,
++ destination,
++ maxObjects: 1_000,
++ maxBytes: 1_073_741_824,
++ deadlineAtMs: Date.now() + 30_000,
++ nowMs: Date.now(),
++ })
++ ).toThrow(expect.objectContaining({ code: 'already_exists' }))
++ const after = await pool.query(
++ `SELECT count(*)::integer AS count FROM gfs_resources WHERE drive=$1`,
++ [tree.drive]
++ )
+ const manifests = await pool.query(
+ `SELECT count(*)::integer AS count FROM gfs_blob_manifests WHERE resource_id IN
+ (SELECT resource_id FROM gfs_resources WHERE drive=$1)`,
+ [tree.drive]
+ )
+ expect(after.rows).toEqual(before.rows)
+ expect(manifests.rows[0]?.count).toBe(0)
+ })
+
+ it('fails on a changed source version and leaves no copied metadata or staged blobs', async () => {
+ const tree = await seedTree('version-change')
+ const frozen = await planFor(tree, 'stale-copy')
+ const requestId = randomUUID()
- await pool.query('UPDATE gfs_resources SET version=version+1 WHERE resource_id=$1', [tree.secondFileId])
++ await pool.query('UPDATE gfs_resources SET version=version+1 WHERE resource_id=$1', [
++ tree.secondFileId,
++ ])
+
- await expect(writes.copy({
- requestId,
- subject: 'host:sandbox-recipes/copy-real-pg',
- audit,
- drive: tree.drive,
- destinationParentId: tree.destinationId,
- plan: frozen.plan,
- destination: frozen.destination,
- deadlineAtMs: Date.now() + 30_000,
- })).rejects.toMatchObject({ code: 'precondition_failed' })
++ await expect(
++ writes.copy({
++ requestId,
++ subject: 'host:sandbox-recipes/copy-real-pg',
++ audit,
++ drive: tree.drive,
++ destinationParentId: tree.destinationId,
++ plan: frozen.plan,
++ destination: frozen.destination,
++ deadlineAtMs: Date.now() + 30_000,
++ })
++ ).rejects.toMatchObject({ code: 'precondition_failed' })
+
+ const copied = await pool.query(
+ `SELECT count(*)::integer AS count FROM gfs_resources
+ WHERE drive=$1 AND path_cache LIKE '/archive/stale-copy%'`,
+ [tree.drive]
+ )
+ const manifests = await pool.query(
+ `SELECT count(*)::integer AS count FROM gfs_blob_manifests WHERE request_id=$1`,
+ [requestId]
+ )
- const outcome = await pool.query(
- `SELECT mutation_outcome FROM gfs_audit WHERE request_id=$1`,
- [requestId]
- )
++ const outcome = await pool.query(`SELECT mutation_outcome FROM gfs_audit WHERE request_id=$1`, [
++ requestId,
++ ])
+ expect(copied.rows[0]?.count).toBe(0)
+ expect(manifests.rows[0]?.count).toBe(0)
+ expect(outcome.rows).toEqual([{ mutation_outcome: 'failed' }])
+ })
+
+ // Concurrency — the optimistic If-Match path. replace() locks the row and
+ // re-checks the version inside the writer transaction; two replaces of the
+ // same file racing with the SAME If-Match can only be adjudicated by real row
+ // locks, so this belongs in the real-PG suite, not the scripted-client unit.
+ it('serializes two concurrent replaces of the same file: one version bump, the loser is precondition_failed', async () => {
+ const tree = await seedTree('race-replace')
+ // first.txt was seeded at version 1. Each replace runs on its own pooled
+ // connection: the writer that locks the row first bumps version 1->2 and
+ // commits; the other then sees version 2 != If-Match 1 and must fail.
+ const fileId = tree.firstFileId
+ const contentA = Buffer.from('replacement-A-payload')
+ const contentB = Buffer.from('replacement-B-different-length')
+ const attempt = (content: Buffer) =>
+ writes.replace({ drive: tree.drive, resourceId: fileId, ifMatch: 1, content })
+
+ const results = await Promise.allSettled([attempt(contentA), attempt(contentB)])
+ const fulfilled = results.filter(
+ (r): r is PromiseFulfilledResult<Awaited<ReturnType<typeof writes.replace>>> =>
+ r.status === 'fulfilled'
+ )
+ const rejected = results.filter((r): r is PromiseRejectedResult => r.status === 'rejected')
+ expect(fulfilled).toHaveLength(1)
+ expect(rejected).toHaveLength(1)
+ expect(rejected[0]!.reason).toMatchObject({ code: 'precondition_failed' })
+
+ // Business truth: version bumped exactly once (1->2), and the bytes served
+ // from the real blob store are the winner's — never a torn blend.
+ const row = await pool.query(
+ `SELECT version, bytes, blob_key FROM gfs_resources WHERE drive=$1 AND resource_id=$2`,
+ [tree.drive, fileId]
+ )
+ expect(Number(row.rows[0]?.version)).toBe(2)
+ const served = await readAll(await blobs.read(fileId, String(row.rows[0]?.blob_key)))
+ expect([contentA, contentB].some(candidate => candidate.equals(served))).toBe(true)
+ expect(Number(row.rows[0]?.bytes)).toBe(served.length)
+ })
+
+ // Concurrency — the per-drive advisory lock + destination re-check. Two copies
+ // into the SAME destination name, both passing preflight before either
+ // publishes, must not both land.
+ it('serializes two concurrent copies into the same destination name: one wins, the loser is already_exists', async () => {
+ const tree = await seedTree('race-copy')
+ // Independent frozen plans for the same '/archive/dup' name. Under the
+ // per-drive advisory lock the first copy inserts the subtree; the second
+ // re-checks the destination name inside the writer txn, finds it taken, and
+ // fails already_exists — the loser inserts nothing.
+ const planA = await planFor(tree, 'dup')
+ const planB = await planFor(tree, 'dup')
+ const attempt = (plan: Awaited<ReturnType<typeof planFor>>, tag: string) =>
+ writes.copy({
+ requestId: randomUUID(),
+ subject: `host:sandbox-recipes/copy-race-${tag}`,
+ audit,
+ drive: tree.drive,
+ destinationParentId: tree.destinationId,
+ plan: plan.plan,
+ destination: plan.destination,
+ deadlineAtMs: Date.now() + 30_000,
+ })
+
+ const results = await Promise.allSettled([attempt(planA, 'a'), attempt(planB, 'b')])
+ const fulfilled = results.filter(
+ (r): r is PromiseFulfilledResult<Awaited<ReturnType<typeof writes.copy>>> =>
+ r.status === 'fulfilled'
+ )
+ const rejected = results.filter((r): r is PromiseRejectedResult => r.status === 'rejected')
+ expect(fulfilled).toHaveLength(1)
+ expect(rejected).toHaveLength(1)
+ expect(rejected[0]!.reason).toMatchObject({ code: 'already_exists' })
+
+ // Business truth: exactly ONE copied subtree root exists at the contended
+ // destination name.
+ const roots = await pool.query(
+ `SELECT count(*)::integer AS n FROM gfs_resources WHERE drive=$1 AND path_cache='/archive/dup'`,
+ [tree.drive]
+ )
+ expect(roots.rows[0]?.n).toBe(1)
+ })
+ })
diff --cc control-api/test/gfsGrants.test.ts
index 728e658ad,93781d5fc..4a8f0bdc1
--- a/control-api/test/gfsGrants.test.ts
+++ b/control-api/test/gfsGrants.test.ts
@@@ -642,6 -770,31 +770,33 @@@ describe('assertMayGrant — agent (hos
).resolves.toBeUndefined()
})
+ it('preserves the existing folder-owner manager restriction for third-party hosts', async () => {
+ const db = mockDb({
+ ancestors: { [R]: [R] },
- grants: [{
- subject_type: 'user',
- subject_id: 'owner',
- resource_id: R,
- permissions: ['read', 'manage_acl'],
- inherit: true,
- }],
++ grants: [
++ {
++ subject_type: 'user',
++ subject_id: 'owner',
++ resource_id: R,
++ permissions: ['read', 'manage_acl'],
++ inherit: true,
++ },
++ ],
+ })
+
+ await expect(
+ assertMayGrant(
+ db,
+ user('owner'),
+ 'main',
+ R,
+ perms('manage_acl'),
+ { type: 'host', id: '3rd:sandbox-recipes/plugin-a' },
+ { isShare: false }
+ )
+ ).rejects.toMatchObject({ status: 403, code: 'agent_manager_forbidden' })
+ })
+
it('forbids sharing to an agent (share targets users/teams only)', async () => {
const db = mockDb({
ancestors: { [R]: [R] },
diff --cc control-api/test/gfsHostSubject.test.ts
index 2e7973c02,c73c4206e..3afbcf71b
--- a/control-api/test/gfsHostSubject.test.ts
+++ b/control-api/test/gfsHostSubject.test.ts
@@@ -1,4 -1,5 +1,5 @@@
-import { readFileSync } from 'node:fs'
import { describe, expect, it } from 'vitest'
++import { readFileSync } from 'node:fs'
import { makeHostSubjectId } from '../src/gfs/hostSubject.js'
import { parseSubject } from '../src/routes/gfs/grants.js'
diff --cc control-api/test/gfsLegacyStandaloneGrantMigration.test.ts
index 000000000,7595abf12..1cb159132
mode 000000,100644..100644
--- a/control-api/test/gfsLegacyStandaloneGrantMigration.test.ts
+++ b/control-api/test/gfsLegacyStandaloneGrantMigration.test.ts
@@@ -1,0 -1,234 +1,245 @@@
-import { readFile } from 'node:fs/promises'
+ import { describe, expect, it, vi } from 'vitest'
++import { readFile } from 'node:fs/promises'
+ import {
+ LEGACY_STANDALONE_SUBJECT_KEY,
+ applyReviewedLegacyGrantMigration,
+ buildLegacyGrantMigrationReport,
+ validateReviewedLegacyGrantMapping,
+ } from '../src/gfs/legacyStandaloneGrantMigration.js'
+ import { createGfsRouter } from '../src/routes/gfs/index.js'
+ import { listLegacyStandaloneGrants } from '../src/routes/gfs/legacyStandaloneGrants.js'
+
+ const SOURCE_ID = '10000000-0000-4000-8000-000000000001'
+ const RESOURCE_ID = '20000000-0000-4000-8000-000000000001'
+ const SOURCE_GRANT = {
+ id: SOURCE_ID,
+ drive: 'main',
+ resourceId: RESOURCE_ID,
+ permissions: ['write', 'read'],
+ inherit: true,
+ }
+ const HOST_A = {
+ name: 'agent-a',
+ namespace: 'mcp-host',
+ displayName: 'Agent A',
+ active: true,
+ gfsSubject: { type: 'host', id: '1st:mcp-host/agent-a' },
+ }
+ const HOST_B = {
+ name: 'agent-b',
+ namespace: 'mcp-host',
+ displayName: 'Agent B',
+ active: true,
+ gfsSubject: { type: 'host', id: '1st:mcp-host/agent-b' },
+ }
+
+ function makeApi(hosts = [HOST_A, HOST_B]) {
+ return {
+ getLegacyGrants: vi.fn(async () => ({
+ sourceSubject: LEGACY_STANDALONE_SUBJECT_KEY,
+ grants: [SOURCE_GRANT],
+ })),
+ getTrustedHostDirectory: vi.fn(async () => ({ agents: hosts })),
+ putGrant: vi.fn(async () => ({ ok: true, status: 200 })),
+ }
+ }
+
+ async function reviewedMapping(api: ReturnType<typeof makeApi>, targets: string[]) {
+ const report = await buildLegacyGrantMigrationReport(api)
+ return {
+ ...report.mappingTemplate,
+ mappings: [{ sourceGrantId: SOURCE_ID, targets }],
+ }
+ }
+
+ describe('legacy standalone GFS grant migration', () => {
+ it('registers the authenticated legacy inventory endpoint exactly once', () => {
+ const router = createGfsRouter() as unknown as {
+ stack: Array<{ route?: { path: string; methods: Record<string, boolean> } }>
+ }
+ const registrations = router.stack.filter(
+ layer =>
- layer.route?.path === '/gfs/grants/legacy-standalone' &&
- layer.route.methods.get === true
++ layer.route?.path === '/gfs/grants/legacy-standalone' && layer.route.methods.get === true
+ )
+
+ expect(registrations).toHaveLength(1)
+ expect(registrations[0]?.route).toMatchObject({
+ path: '/gfs/grants/legacy-standalone',
+ methods: { get: true },
+ })
+ })
+
+ it('reports deterministic legacy grants and valid candidates without inferring assignments', async () => {
+ const api = makeApi([
+ HOST_B,
+ { ...HOST_A, active: false },
+ HOST_A,
+ {
+ name: 'standalone',
+ namespace: 'mcp-host',
+ displayName: 'Standalone',
+ active: true,
+ gfsSubject: { type: 'host', id: '1st:mcp-host/standalone' },
+ },
+ ])
+ const report = await buildLegacyGrantMigrationReport(api)
+
+ expect(report.sourceGrants).toEqual([{ ...SOURCE_GRANT, permissions: ['read', 'write'] }])
- expect(report.validIndividualHostCandidates.map(item => item.name)).toEqual(['agent-a', 'agent-b'])
++ expect(report.validIndividualHostCandidates.map(item => item.name)).toEqual([
++ 'agent-a',
++ 'agent-b',
++ ])
+ expect(report.mappingTemplate.mappings).toEqual([{ sourceGrantId: SOURCE_ID, targets: [] }])
+ expect(api.putGrant).not.toHaveBeenCalled()
+ })
+
+ it('requires an explicit exact canonical Host mapping and preserves the source row', async () => {
+ const api = makeApi()
+ const mapping = await reviewedMapping(api, ['host:1st:mcp-host/agent-a'])
+ api.getLegacyGrants.mockClear()
+ api.getTrustedHostDirectory.mockClear()
+
+ const result = await applyReviewedLegacyGrantMigration(api, mapping)
+
+ expect(api.getLegacyGrants).toHaveBeenCalledTimes(1)
+ expect(api.getTrustedHostDirectory).toHaveBeenCalledTimes(1)
+ expect(api.putGrant).toHaveBeenCalledWith({
+ drive: 'main',
+ resourceId: RESOURCE_ID,
+ subject: { type: 'host', id: '1st:mcp-host/agent-a' },
+ permissions: ['read', 'write'],
+ inherit: true,
+ })
+ expect(result).toMatchObject({
+ allApprovedIndividualGrantsSucceeded: true,
+ legacyGrantsDeleted: false,
+ sources: [{ legacyGrantPreserved: true, readyForRetirement: true }],
+ })
+ })
+
+ it('reports partial failure and supports an idempotent retry through the same audited API', async () => {
+ const api = makeApi()
+ const mapping = await reviewedMapping(api, [
+ 'host:1st:mcp-host/agent-a',
+ 'host:1st:mcp-host/agent-b',
+ ])
+ let failB = true
+ api.putGrant.mockImplementation(async body => ({
+ ok: !(failB && JSON.stringify(body).includes('agent-b')),
+ status: failB && JSON.stringify(body).includes('agent-b') ? 503 : 200,
+ }))
+
+ const first = await applyReviewedLegacyGrantMigration(api, mapping)
+ expect(first.sources[0]).toMatchObject({
+ legacyGrantPreserved: true,
+ readyForRetirement: false,
+ })
+ expect(api.putGrant).toHaveBeenCalledTimes(2)
+
+ failB = false
+ api.putGrant.mockClear()
+ const retry = await applyReviewedLegacyGrantMigration(api, mapping)
+ expect(api.putGrant).toHaveBeenCalledTimes(2)
+ expect(retry).toMatchObject({
+ allApprovedIndividualGrantsSucceeded: true,
+ legacyGrantsDeleted: false,
+ })
+ })
+
+ it('rejects a stale trusted directory before any apply request', async () => {
+ const api = makeApi()
+ const mapping = await reviewedMapping(api, ['host:1st:mcp-host/agent-a'])
+ api.getTrustedHostDirectory.mockResolvedValue({ agents: [HOST_B] })
+
+ await expect(applyReviewedLegacyGrantMigration(api, mapping)).rejects.toThrow(
+ 'trusted_host_directory_changed'
+ )
+ expect(api.putGrant).not.toHaveBeenCalled()
+ })
+
+ it('rejects duplicate targets and broad or sentinel subjects', async () => {
+ const api = makeApi()
+ const report = await buildLegacyGrantMigrationReport(api)
+ const duplicate = {
+ ...report.mappingTemplate,
- mappings: [{
- sourceGrantId: SOURCE_ID,
- targets: ['host:1st:mcp-host/agent-a', 'host:1st:mcp-host/agent-a'],
- }],
++ mappings: [
++ {
++ sourceGrantId: SOURCE_ID,
++ targets: ['host:1st:mcp-host/agent-a', 'host:1st:mcp-host/agent-a'],
++ },
++ ],
+ }
+ expect(() => validateReviewedLegacyGrantMapping(report, duplicate)).toThrow(
+ 'mapping_target_duplicate'
+ )
+
+ for (const target of [
+ LEGACY_STANDALONE_SUBJECT_KEY,
+ 'team:all-agents',
+ 'host:1st:mcp-host/all-agents',
+ ]) {
- expect(() => validateReviewedLegacyGrantMapping(report, {
- ...report.mappingTemplate,
- mappings: [{ sourceGrantId: SOURCE_ID, targets: [target] }],
- })).toThrow('mapping_target_not_current_trusted_host')
++ expect(() =>
++ validateReviewedLegacyGrantMapping(report, {
++ ...report.mappingTemplate,
++ mappings: [{ sourceGrantId: SOURCE_ID, targets: [target] }],
++ })
++ ).toThrow('mapping_target_not_current_trusted_host')
+ }
+ })
+
+ it('uses a bounded read-only query for inventory and no direct grant-row SQL in apply', async () => {
- const query = vi.fn(async () => ({ rows: [
- {
- id: SOURCE_ID,
- drive: 'main',
- resource_id: RESOURCE_ID,
- permissions: ['write', 'read'],
- inherit: true,
- },
- ] }))
++ const query = vi.fn(async () => ({
++ rows: [
++ {
++ id: SOURCE_ID,
++ drive: 'main',
++ resource_id: RESOURCE_ID,
++ permissions: ['write', 'read'],
++ inherit: true,
++ },
++ ],
++ }))
+ await expect(listLegacyStandaloneGrants({ query })).resolves.toEqual([
+ { ...SOURCE_GRANT, permissions: ['read', 'write'] },
+ ])
+ expect(query.mock.calls[0][0]).toMatch(/^SELECT[\s\S]+WHERE subject_type = 'host'/)
+ expect(query.mock.calls[0][0]).toContain('LIMIT $2')
+ expect(query.mock.calls[0][1]).toEqual(['1st:mcp-host/standalone', 1001])
+
- const script = await readFile(new URL('../../scripts/gfs-legacy-standalone-grants.mjs', import.meta.url), 'utf8')
++ const script = await readFile(
++ new URL('../../scripts/gfs-legacy-standalone-grants.mjs', import.meta.url),
++ 'utf8'
++ )
+ expect(script).not.toMatch(/INSERT\s+INTO|UPDATE\s+gfs_grants|DELETE\s+FROM/i)
+ expect(script).toContain("'/api/v1/gfs/grants'")
+ })
+
+ it('rejects legacy inventory when the bounded query detects row 1001', async () => {
+ const query = vi.fn(async () => ({
+ rows: Array.from({ length: 1001 }, (_, index) => ({ id: String(index) })),
+ }))
+
+ await expect(listLegacyStandaloneGrants({ query })).rejects.toThrow(
+ 'legacy_grant_report_limit_exceeded'
+ )
+ expect(query).toHaveBeenCalledWith(expect.stringContaining('LIMIT $2'), [
+ '1st:mcp-host/standalone',
+ 1001,
+ ])
+ })
+
+ it('fails closed instead of copying or silently reducing forbidden legacy permissions', async () => {
+ for (const permission of ['delete', 'manage_acl', 'share']) {
+ const api = makeApi()
+ api.getLegacyGrants.mockResolvedValue({
+ sourceSubject: LEGACY_STANDALONE_SUBJECT_KEY,
+ grants: [{ ...SOURCE_GRANT, permissions: ['read', permission] }],
+ })
+
+ await expect(buildLegacyGrantMigrationReport(api)).rejects.toThrow(
+ 'legacy_grant_permissions_forbidden'
+ )
+ expect(api.putGrant).not.toHaveBeenCalled()
+ }
+ })
+ })
diff --cc control-api/test/gfsLegacyStandaloneGrantsRateLimit.test.ts
index 000000000,55a244c1a..e234d4568
mode 000000,100644..100644
--- a/control-api/test/gfsLegacyStandaloneGrantsRateLimit.test.ts
+++ b/control-api/test/gfsLegacyStandaloneGrantsRateLimit.test.ts
@@@ -1,0 -1,139 +1,138 @@@
+ import { beforeEach, describe, expect, it, vi } from 'vitest'
+ import express from 'express'
+ import request from 'supertest'
+
+ // Route-level regression guard for the rate limiter on the legacy-standalone
+ // grant report (CodeQL #795 fix). The limiter service itself is covered
+ // elsewhere; what was untested is the WIRING — that this specific route still
+ // runs the limiter, keyed per-admin on its own bucket, before doing any
+ // database work. Dropping `legacyGrantReportRateLimit` from the route would
+ // leave every assertion here failing rather than silently un-limiting an
+ // authenticated endpoint.
+ const ADMIN_SUB = vi.hoisted(() => 'admin-42')
+ const mockQuery = vi.hoisted(() => vi.fn())
+ const mockCheckAndIncrement = vi.hoisted(() => vi.fn())
+
+ vi.mock('../src/db.js', () => ({
+ pool: { query: (...args: unknown[]) => mockQuery(...args) },
+ withTransaction: vi.fn(),
+ }))
+
+ vi.mock('../src/services/rateLimiterService.js', () => ({
+ checkAndIncrement: (...args: unknown[]) => mockCheckAndIncrement(...args),
+ }))
+
+ // Mirrors the real middleware's contract: it authenticates and publishes the
+ // admin claims on the request. The limiter keys on `adminAuth.sub`, so the
+ // stub must populate it exactly like `requireAuthForControlUI` does.
+ vi.mock('../src/middleware/controlUIAuth.js', () => ({
+ requireAuthForControlUI: (
+ req: express.Request,
+ res: express.Response,
+ next: express.NextFunction
+ ) => {
+ if (req.header('x-test-auth') !== 'operator') {
+ res.status(401).json({ error: 'Unauthorized' })
+ return
+ }
+ ;(req as express.Request & { adminAuth?: { sub: string } }).adminAuth = { sub: ADMIN_SUB }
+ next()
+ },
+ }))
+
+ const RESOURCE_ID = '20000000-0000-4000-8000-000000000001'
+
+ function allowed(remaining = 29) {
+ return {
+ allowed: true,
+ remaining,
+ resetMs: Date.now() + 60_000,
+ windowStartMs: Date.now(),
+ count: 30 - remaining,
+ }
+ }
+
+ function denied() {
+ return {
+ allowed: false,
+ remaining: 0,
+ resetMs: Date.now() + 30_000,
+ windowStartMs: Date.now(),
+ count: 31,
+ }
+ }
+
+ async function buildApp() {
- const { registerLegacyStandaloneGrantReportRoute } = await import(
- '../src/routes/gfs/legacyStandaloneGrants.js'
- )
++ const { registerLegacyStandaloneGrantReportRoute } =
++ await import('../src/routes/gfs/legacyStandaloneGrants.js')
+ const router = express.Router()
+ registerLegacyStandaloneGrantReportRoute(router)
+ const app = express()
+ app.use(express.json())
+ app.use(router)
+ return app
+ }
+
+ describe('GET /gfs/grants/legacy-standalone rate limiting', () => {
+ beforeEach(() => {
+ mockQuery.mockReset()
+ mockCheckAndIncrement.mockReset()
+ })
+
+ it('serves the report and consumes its own per-admin bucket when under the limit', async () => {
+ mockCheckAndIncrement.mockResolvedValue(allowed())
+ mockQuery.mockResolvedValue({
+ rows: [
+ {
+ id: '10000000-0000-4000-8000-000000000001',
+ drive: 'main',
+ resource_id: RESOURCE_ID,
+ permissions: ['read'],
+ inherit: true,
+ },
+ ],
+ })
+
+ const response = await request(await buildApp())
+ .get('/gfs/grants/legacy-standalone')
+ .set('x-test-auth', 'operator')
+
+ // Operability: the limiter must not stand between an operator and a
+ // legitimate report — the normal path still returns the inventory.
+ expect(response.status).toBe(200)
+ expect(response.body.grants).toHaveLength(1)
+ // Wiring proof: the route consumed the DEDICATED bucket key at the
+ // documented 30/min ceiling, not the grant-mutation bucket and not some
+ // shared/unkeyed budget.
+ expect(mockCheckAndIncrement).toHaveBeenCalledTimes(1)
+ expect(mockCheckAndIncrement).toHaveBeenCalledWith(`gfsgrants-legacy:${ADMIN_SUB}`, 30)
+ })
+
+ it('returns 429 with Retry-After and never reaches the database once the bucket is exhausted', async () => {
+ mockCheckAndIncrement.mockResolvedValue(denied())
+
+ const response = await request(await buildApp())
+ .get('/gfs/grants/legacy-standalone')
+ .set('x-test-auth', 'operator')
+
+ expect(response.status).toBe(429)
+ expect(response.body).toMatchObject({ error: 'Too Many Requests' })
+ expect(response.body.retryAfterSeconds).toBeGreaterThan(0)
+ expect(response.headers['retry-after']).toBeDefined()
+ expect(response.headers['x-ratelimit-limit']).toBe('30')
+ expect(response.headers['x-ratelimit-remaining']).toBe('0')
+ // The property that makes this a DoS control rather than a cosmetic header:
+ // the request is rejected BEFORE the handler runs its Postgres query.
+ expect(mockQuery).not.toHaveBeenCalled()
+ })
+
+ it('rejects unauthenticated callers before the limiter spends a token', async () => {
+ const response = await request(await buildApp()).get('/gfs/grants/legacy-standalone')
+
+ expect(response.status).toBe(401)
+ // Auth precedes the limiter, so an anonymous flood cannot drain a real
+ // admin's bucket (and the limiter's key is never null in practice).
+ expect(mockCheckAndIncrement).not.toHaveBeenCalled()
+ expect(mockQuery).not.toHaveBeenCalled()
+ })
+ })
diff --cc control-api/test/gfsReaderRole.realPostgres.integration.test.ts
index 000000000,245b7c028..0844d4a38
mode 000000,100644..100644
--- a/control-api/test/gfsReaderRole.realPostgres.integration.test.ts
+++ b/control-api/test/gfsReaderRole.realPostgres.integration.test.ts
@@@ -1,0 -1,257 +1,269 @@@
-import { randomBytes } from 'node:crypto'
+ import { afterAll, beforeAll, describe, expect, it } from 'vitest'
++import { randomBytes } from 'node:crypto'
+ import { Pool } from 'pg'
-import { CONTROL_API_MIGRATIONS, initDb } from '../src/db.js'
+ import { createPermissionStoreProbe } from '../../gfs-controller/src/authz/storeProbe.js'
++import { CONTROL_API_MIGRATIONS, initDb } from '../src/db.js'
+
+ const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
+ const describeRealPostgres = adminUrl ? describe : describe.skip
+
+ function databaseUrl(baseUrl: string, database: string, user?: string, password?: string): string {
+ const url = new URL(baseUrl)
+ url.pathname = `/${database}`
+ if (user !== undefined) url.username = user
+ if (password !== undefined) url.password = password
+ return url.toString()
+ }
+
+ function quoteIdent(value: string): string {
+ return `"${value.replace(/"/g, '""')}"`
+ }
+
+ describeRealPostgres('GFS reader and writer login isolation', () => {
+ const database = `gfs_reader_role_${randomBytes(6).toString('hex')}`
+ const connectionString = databaseUrl(
+ adminUrl ?? 'postgresql://[email protected]/postgres',
+ database
+ )
+ const writerPassword = randomBytes(24).toString('hex')
+ const readerPassword = randomBytes(24).toString('hex')
+ const inheritedRole = `gfs_drift_${randomBytes(6).toString('hex')}`
+ const writerUrl = databaseUrl(connectionString, database, 'gfs_controller', writerPassword)
+ const readerUrl = databaseUrl(connectionString, database, 'gfs_controller_reader', readerPassword)
+ let adminPool: Pool
+ let pool: Pool
+ let writerPool: Pool
+ let readerPool: Pool
+
+ const readiness = (runtimePool: Pool, dsn: string, storageRole: 'writer' | 'reader') =>
+ createPermissionStoreProbe({
+ pool: runtimePool,
+ connectionString: dsn,
+ intervalMs: 0,
+ storageRole,
+ connectTimeoutMs: 2_000,
+ })
+
+ beforeAll(async () => {
+ adminPool = new Pool({ connectionString: adminUrl })
+ await adminPool.query(`CREATE DATABASE ${quoteIdent(database)}`)
+ pool = new Pool({ connectionString })
+ await initDb({ connect: () => pool.connect() })
+
+ // Match the production provisioning contract: the two runtime identities
+ // authenticate directly with independent secrets. NOINHERIT prevents an
+ // accidental membership from widening either direct-login envelope.
+ await pool.query(`ALTER ROLE gfs_controller LOGIN NOINHERIT PASSWORD '${writerPassword}'`)
- await pool.query(`ALTER ROLE gfs_controller_reader LOGIN NOINHERIT PASSWORD '${readerPassword}'`)
++ await pool.query(
++ `ALTER ROLE gfs_controller_reader LOGIN NOINHERIT PASSWORD '${readerPassword}'`
++ )
+ writerPool = new Pool({ connectionString: writerUrl })
+ readerPool = new Pool({ connectionString: readerUrl })
+ }, 60_000)
+
+ afterAll(async () => {
+ await readerPool?.end()
+ await writerPool?.end()
+ await pool?.query('ALTER ROLE gfs_controller NOLOGIN NOINHERIT').catch(() => undefined)
+ await pool?.query('ALTER ROLE gfs_controller_reader NOLOGIN NOINHERIT').catch(() => undefined)
+ await pool?.query(`DROP ROLE IF EXISTS ${quoteIdent(inheritedRole)}`).catch(() => undefined)
+ await pool?.end()
+ if (!adminPool) return
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ await adminPool.end()
+ })
+
+ it('authenticates distinct DSNs as the exact NOINHERIT runtime identities', async () => {
+ expect(readerPassword).not.toBe(writerPassword)
+ const [writerIdentity, readerIdentity, attributes] = await Promise.all([
+ writerPool.query('SELECT current_user'),
+ readerPool.query('SELECT current_user'),
+ pool.query(
+ `SELECT rolname, rolcanlogin, rolinherit
+ FROM pg_roles
+ WHERE rolname = ANY($1::text[])
+ ORDER BY rolname`,
+ [['gfs_controller', 'gfs_controller_reader']]
+ ),
+ ])
+ expect(writerIdentity.rows[0]?.current_user).toBe('gfs_controller')
+ expect(readerIdentity.rows[0]?.current_user).toBe('gfs_controller_reader')
+ expect(attributes.rows).toEqual([
+ { rolname: 'gfs_controller', rolcanlogin: true, rolinherit: false },
+ { rolname: 'gfs_controller_reader', rolcanlogin: true, rolinherit: false },
+ ])
+ })
+
+ it('repairs existing-role drift without changing LOGIN or passwords', async () => {
+ await pool.query(`CREATE ROLE ${quoteIdent(inheritedRole)} NOLOGIN`)
+ await pool.query(`GRANT ${quoteIdent(inheritedRole)} TO gfs_controller, gfs_controller_reader`)
+ await pool.query('ALTER ROLE gfs_controller INHERIT')
+ await pool.query('ALTER ROLE gfs_controller_reader INHERIT')
+ await pool.query('GRANT DELETE ON gfs_resources TO gfs_controller')
+ await pool.query('GRANT SELECT ON gfs_blob_manifests TO gfs_controller_reader')
+ await pool.query('GRANT SELECT (email), UPDATE ON control_admin_users TO gfs_controller')
+ await pool.query('GRANT SELECT (role), UPDATE ON team_members TO gfs_controller_reader')
+ await pool.query('GRANT UPDATE ON SEQUENCE gfs_audit_sequence_no_seq TO gfs_controller_reader')
+
+ const migration = CONTROL_API_MIGRATIONS.find(
+ candidate => candidate.version === '0074_gfs_runtime_role_exact_contract'
+ )
+ expect(migration).toBeDefined()
+ await migration!.apply(pool)
+
+ const attributes = await pool.query(
+ `SELECT rolname, rolcanlogin, rolinherit, rolsuper, rolcreatedb, rolcreaterole,
+ rolreplication, rolbypassrls
+ FROM pg_roles
+ WHERE rolname = ANY($1::text[])
+ ORDER BY rolname`,
+ [['gfs_controller', 'gfs_controller_reader']]
+ )
+ expect(attributes.rows).toEqual([
+ {
+ rolname: 'gfs_controller',
+ rolcanlogin: true,
+ rolinherit: false,
+ rolsuper: false,
+ rolcreatedb: false,
+ rolcreaterole: false,
+ rolreplication: false,
+ rolbypassrls: false,
+ },
+ {
+ rolname: 'gfs_controller_reader',
+ rolcanlogin: true,
+ rolinherit: false,
+ rolsuper: false,
+ rolcreatedb: false,
+ rolcreaterole: false,
+ rolreplication: false,
+ rolbypassrls: false,
+ },
+ ])
+ const memberships = await pool.query(
+ `SELECT member_role.rolname
+ FROM pg_auth_members membership
+ JOIN pg_roles member_role ON member_role.oid = membership.member
+ WHERE member_role.rolname = ANY($1::text[])`,
+ [['gfs_controller', 'gfs_controller_reader']]
+ )
+ expect(memberships.rows).toEqual([])
+
+ const [freshWriter, freshReader] = [
+ new Pool({ connectionString: writerUrl }),
+ new Pool({ connectionString: readerUrl }),
+ ]
+ try {
+ await expect(freshWriter.query('SELECT current_user')).resolves.toMatchObject({
+ rows: [{ current_user: 'gfs_controller' }],
+ })
+ await expect(freshReader.query('SELECT current_user')).resolves.toMatchObject({
+ rows: [{ current_user: 'gfs_controller_reader' }],
+ })
+ } finally {
+ await Promise.all([freshWriter.end(), freshReader.end()])
+ }
+ })
+
+ it('passes reader readiness without any manifest privilege and passes writer readiness with it', async () => {
- await expect(readerPool.query('SELECT 1 FROM gfs_blob_manifests')).rejects.toMatchObject({ code: '42501' })
++ await expect(readerPool.query('SELECT 1 FROM gfs_blob_manifests')).rejects.toMatchObject({
++ code: '42501',
++ })
+ await expect(readiness(readerPool, readerUrl, 'reader')()).resolves.toBeUndefined()
+ await expect(readiness(writerPool, writerUrl, 'writer')()).resolves.toBeUndefined()
+ })
+
+ it.each([
- ['SELECT on resources', 'REVOKE SELECT ON gfs_resources FROM gfs_controller_reader', 'GRANT SELECT ON gfs_resources TO gfs_controller_reader'],
- ['INSERT on audit', 'REVOKE INSERT ON gfs_audit FROM gfs_controller_reader', 'GRANT INSERT ON gfs_audit TO gfs_controller_reader'],
++ [
++ 'SELECT on resources',
++ 'REVOKE SELECT ON gfs_resources FROM gfs_controller_reader',
++ 'GRANT SELECT ON gfs_resources TO gfs_controller_reader',
++ ],
++ [
++ 'INSERT on audit',
++ 'REVOKE INSERT ON gfs_audit FROM gfs_controller_reader',
++ 'GRANT INSERT ON gfs_audit TO gfs_controller_reader',
++ ],
+ ])('fails reader readiness after revoking %s', async (_label, revokeSql, restoreSql) => {
+ await pool.query(revokeSql)
+ try {
+ await expect(readiness(readerPool, readerUrl, 'reader')()).rejects.toThrow(
+ /coherence check failed|permission denied/i
+ )
+ } finally {
+ await pool.query(restoreSql)
+ }
+ })
+
+ it('cannot mutate metadata, inherit the writer, or read manifests', async () => {
+ const membership = await pool.query(
+ `SELECT pg_has_role('gfs_controller_reader', 'gfs_controller', 'MEMBER') AS member`
+ )
+ expect(membership.rows[0]?.member).toBe(false)
+
+ const privileges = await readerPool.query(`
+ SELECT
+ has_table_privilege(current_user, 'gfs_resources', 'SELECT') AS can_read_resources,
+ has_table_privilege(current_user, 'gfs_audit', 'INSERT') AS can_insert_audit,
+ has_table_privilege(current_user, 'gfs_resources', 'INSERT') AS can_insert_resources,
+ has_table_privilege(current_user, 'gfs_resources', 'UPDATE') AS can_update_resources,
+ has_table_privilege(current_user, 'gfs_grants', 'INSERT') AS can_insert_grants,
+ has_table_privilege(current_user, 'gfs_shares', 'INSERT') AS can_insert_shares,
+ has_table_privilege(current_user, 'gfs_blob_manifests', 'SELECT') AS can_read_manifests
+ `)
+ expect(privileges.rows[0]).toEqual({
+ can_read_resources: true,
+ can_insert_audit: true,
+ can_insert_resources: false,
+ can_update_resources: false,
+ can_insert_grants: false,
+ can_insert_shares: false,
+ can_read_manifests: false,
+ })
+ await expect(
+ readerPool.query('UPDATE gfs_resources SET bytes = bytes WHERE false')
+ ).rejects.toMatchObject({ code: '42501' })
+ })
+
+ it.each([
+ ['writer', () => writerPool],
+ ['reader', () => readerPool],
+ ] as const)('%s has only the approved subject-table columns', async (_kind, runtimePool) => {
+ await expect(
+ runtimePool().query('SELECT id, status FROM control_admin_users WHERE false')
+ ).resolves.toMatchObject({ rowCount: 0 })
+ await expect(
+ runtimePool().query('SELECT team_id, user_id, status FROM team_members WHERE false')
+ ).resolves.toMatchObject({ rowCount: 0 })
+ await expect(
+ runtimePool().query('SELECT email FROM control_admin_users WHERE false')
+ ).rejects.toMatchObject({ code: '42501' })
+ await expect(
+ runtimePool().query('SELECT role FROM team_members WHERE false')
+ ).rejects.toMatchObject({ code: '42501' })
+ await expect(
+ runtimePool().query('UPDATE control_admin_users SET status = status WHERE false')
+ ).rejects.toMatchObject({ code: '42501' })
- await expect(
- runtimePool().query('DELETE FROM team_members WHERE false')
- ).rejects.toMatchObject({ code: '42501' })
++ await expect(runtimePool().query('DELETE FROM team_members WHERE false')).rejects.toMatchObject(
++ { code: '42501' }
++ )
+ })
+
+ it('preserves required writer mutation privileges but denies hard deletion', async () => {
+ await expect(
+ writerPool.query('UPDATE gfs_resources SET bytes = bytes WHERE false')
+ ).resolves.toMatchObject({ rowCount: 0 })
- await expect(
- writerPool.query('DELETE FROM gfs_resources WHERE false')
- ).rejects.toMatchObject({ code: '42501' })
++ await expect(writerPool.query('DELETE FROM gfs_resources WHERE false')).rejects.toMatchObject({
++ code: '42501',
++ })
+ await expect(
+ writerPool.query('UPDATE gfs_blob_manifests SET updated_at = updated_at WHERE false')
+ ).resolves.toMatchObject({ rowCount: 0 })
+ })
+ })
diff --cc control-api/test/gfsReadiness.realPostgres.integration.test.ts
index 000000000,1b676e21e..b12f2eeab
mode 000000,100644..100644
--- a/control-api/test/gfsReadiness.realPostgres.integration.test.ts
+++ b/control-api/test/gfsReadiness.realPostgres.integration.test.ts
@@@ -1,0 -1,134 +1,134 @@@
-import { randomBytes } from 'node:crypto'
+ import { afterAll, beforeAll, describe, expect, it } from 'vitest'
++import { randomBytes } from 'node:crypto'
+ import { Pool } from 'pg'
-import { assertDbReady, initDb } from '../src/db.js'
-import { createPermissionStoreProbe } from '../../gfs-controller/src/authz/storeProbe.js'
+ import type { PoolClient } from 'pg'
++import { createPermissionStoreProbe } from '../../gfs-controller/src/authz/storeProbe.js'
++import { assertDbReady, initDb } from '../src/db.js'
+
+ const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
+ const describeRealPostgres = adminUrl ? describe : describe.skip
+
+ function databaseUrl(baseUrl: string, database: string): string {
+ const url = new URL(baseUrl)
+ url.pathname = `/${database}`
+ return url.toString()
+ }
+
+ function quoteIdent(value: string): string {
+ return `"${value.replace(/"/g, '""')}"`
+ }
+
+ describeRealPostgres('GFS Phase 0 real PostgreSQL readiness', () => {
+ const database = `gfs_readiness_${randomBytes(6).toString('hex')}`
+ const connectionString = databaseUrl(
+ adminUrl ?? 'postgresql://[email protected]/postgres',
+ database
+ )
+ let adminPool: Pool
+ let pool: Pool
+
+ function probeAs(client: PoolClient) {
+ return createPermissionStoreProbe({
+ pool: {
+ connect: async () => {
+ const pingClient = await pool.connect()
+ return {
+ query: (sql: string) => pingClient.query(sql),
+ release: (error?: Error) => pingClient.release(error),
+ }
+ },
+ },
+ connectionString,
+ intervalMs: 0,
+ storageRole: 'writer',
+ connectTimeoutMs: 2_000,
+ clientFactory: () => ({
+ connect: async () => undefined,
+ query: (sql: string) => client.query(sql),
+ end: async () => undefined,
+ }),
+ })
+ }
+
+ beforeAll(async () => {
+ adminPool = new Pool({ connectionString: adminUrl })
+ await adminPool.query(`CREATE DATABASE ${quoteIdent(database)}`)
+ pool = new Pool({ connectionString })
+ await initDb({ connect: () => pool.connect() })
+ }, 60_000)
+
+ afterAll(async () => {
+ await pool?.end()
+ if (!adminPool) return
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ await adminPool.end()
+ })
+
+ it('fails Control API readiness while the latest migration is absent', async () => {
+ const client = await pool.connect()
+ try {
+ await client.query('BEGIN')
+ await client.query(
+ `DELETE FROM schema_migrations WHERE version='0074_gfs_runtime_role_exact_contract'`
+ )
+ await expect(assertDbReady(client)).rejects.toThrow(/0074_gfs_runtime_role_exact_contract/)
+ } finally {
+ await client.query('ROLLBACK').catch(() => undefined)
+ client.release()
+ }
+ })
+
+ it('fails GFSC readiness while the immutable blob schema is absent', async () => {
+ const client = await pool.connect()
+ try {
+ await client.query('BEGIN')
+ await client.query('DROP TABLE gfs_blob_manifests')
+ await client.query('SET LOCAL ROLE gfs_controller')
+ await expect(probeAs(client)()).rejects.toThrow(/gfs_blob_manifests|0068/i)
+ } finally {
+ await client.query('ROLLBACK').catch(() => undefined)
+ client.release()
+ }
+ })
+
+ it('passes GFSC writer readiness under the migrated runtime role', async () => {
+ const client = await pool.connect()
+ try {
+ await client.query('BEGIN')
+ await client.query('SET LOCAL ROLE gfs_controller')
+ await expect(probeAs(client)()).resolves.toBeUndefined()
+ } finally {
+ await client.query('ROLLBACK').catch(() => undefined)
+ client.release()
+ }
+ })
+
+ it.each([
+ ['resource SELECT', 'REVOKE SELECT ON gfs_resources FROM gfs_controller'],
+ ['audit INSERT', 'REVOKE INSERT ON gfs_audit FROM gfs_controller'],
+ ['manifest SELECT', 'REVOKE SELECT ON gfs_blob_manifests FROM gfs_controller'],
+ ['manifest INSERT', 'REVOKE INSERT ON gfs_blob_manifests FROM gfs_controller'],
+ ['manifest UPDATE', 'REVOKE UPDATE ON gfs_blob_manifests FROM gfs_controller'],
+ ['manifest DELETE', 'REVOKE DELETE ON gfs_blob_manifests FROM gfs_controller'],
+ ['resource INSERT', 'REVOKE INSERT ON gfs_resources FROM gfs_controller'],
+ ['resource UPDATE', 'REVOKE UPDATE ON gfs_resources FROM gfs_controller'],
+ ])('fails GFSC writer readiness without only %s', async (_name, revokeSql) => {
+ const client = await pool.connect()
+ try {
+ await client.query('BEGIN')
+ await client.query(revokeSql)
+ await client.query('SET LOCAL ROLE gfs_controller')
+ await expect(probeAs(client)()).rejects.toThrow(
+ /coherence check failed|permission denied|0068|0048/i
+ )
+ } finally {
+ await client.query('ROLLBACK').catch(() => undefined)
+ client.release()
+ }
+ })
+ })
diff --cc control-api/test/gfsResources.routeTransaction.test.ts
index 000000000,b1f0e63a9..5d98181a6
mode 000000,100644..100644
--- a/control-api/test/gfsResources.routeTransaction.test.ts
+++ b/control-api/test/gfsResources.routeTransaction.test.ts
@@@ -1,0 -1,194 +1,222 @@@
+ import { beforeEach, describe, expect, it, vi } from 'vitest'
++import { handlePatch } from '../src/routes/gfs/resources.js'
+
+ const FILE = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'
+ const OTHER = 'dddddddd-dddd-dddd-dddd-dddddddddddd'
+
+ const state = vi.hoisted(() => {
+ const events: string[] = []
+ const file = {
+ resource_id: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
+ drive: 'main',
+ parent_resource_id: 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb',
+ name: 'a.md',
+ kind: 'file',
+ version: 2,
+ deleted_at: null,
+ }
+ const source = {
+ resource_id: 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb',
+ drive: 'main',
+ parent_resource_id: null,
+ name: '',
+ kind: 'directory',
+ version: 0,
+ deleted_at: null,
+ cycle: false,
+ }
+ const other = {
+ resource_id: 'dddddddd-dddd-dddd-dddd-dddddddddddd',
+ drive: 'other',
+ parent_resource_id: null,
+ name: '',
+ kind: 'directory',
+ version: 0,
+ deleted_at: null,
+ }
+ const db = {
+ query: vi.fn(async (text: string, values?: unknown[]) => {
+ if (text.includes('pg_advisory_xact_lock')) {
+ events.push('advisory')
+ return { rows: [] }
+ }
+ if (text.includes('ORDER BY resource_id') && text.includes('FOR UPDATE')) {
+ events.push('row-locks')
+ return { rows: [] }
+ }
+ if (text.includes('WITH RECURSIVE chain')) return { rows: [source] }
+ if (text.includes('WITH RECURSIVE subtree')) {
+ events.push('paths')
+ return {
+ rows: [
+ {
+ expected_count: '1',
+ updated_count: state.failPaths ? '0' : '1',
+ canonical_count: '1',
+ distinct_path_count: '1',
+ has_cycle: false,
+ },
+ ],
+ }
+ }
+ if (text.includes('UPDATE gfs_resources')) {
+ events.push('mutation')
+ return { rows: [{ version: 3 }] }
+ }
+ if (text.includes('FROM gfs_resources')) {
+ const id = String(values?.[0])
- return { rows: [id === source.resource_id ? source : id === other.resource_id ? other : file] }
++ return {
++ rows: [id === source.resource_id ? source : id === other.resource_id ? other : file],
++ }
+ }
+ return { rows: [] }
+ }),
+ }
- return { events, db, failPaths: false, operator: true, auditDb: undefined as unknown, audits: [] as unknown[] }
++ return {
++ events,
++ db,
++ failPaths: false,
++ operator: true,
++ auditDb: undefined as unknown,
++ audits: [] as unknown[],
++ }
+ })
+
+ vi.mock('../src/db.js', () => ({
+ withTransaction: vi.fn(async (work: (db: typeof state.db) => Promise<unknown>) => {
+ state.events.push('begin')
+ try {
+ const result = await work(state.db)
+ state.events.push('commit')
+ return result
+ } catch (error) {
+ state.events.push('rollback')
+ throw error
+ }
+ }),
+ }))
+
+ vi.mock('../src/middleware/controlUIAuth.js', () => ({
+ requireAuthForControlUI: (_req: unknown, _res: unknown, next: () => void) => next(),
+ }))
+
+ vi.mock('../src/routes/gfs/grants.js', () => ({
+ UUID_RE: /^[0-9a-f-]{36}$/,
+ resolveCaller: () => ({
+ isOperator: state.operator,
+ subjects: new Set([state.operator ? 'operator:' : 'user:blocked']),
+ actorKey: state.operator ? 'operator:' : 'user:blocked',
+ }),
+ driveOf: (value: unknown) => String(value),
+ requestIdOf: () => 'request-1',
+ checkAccess: async () => state.operator,
+ auditMutation: vi.fn(async (db: unknown, params: unknown) => {
+ state.auditDb = db
+ state.audits.push(params)
+ state.events.push('audit')
+ }),
+ }))
+
-import { handlePatch } from '../src/routes/gfs/resources.js'
-
+ function response() {
+ return {
+ code: 0,
+ body: undefined as unknown,
+ status(code: number) {
+ this.code = code
+ return this
+ },
+ json(body: unknown) {
+ this.body = body
+ return this
+ },
+ }
+ }
+
+ describe('gfs resource route transaction boundary', () => {
+ beforeEach(() => {
+ state.events.length = 0
+ state.failPaths = false
+ state.operator = true
+ state.auditDb = undefined
+ state.audits.length = 0
+ state.db.query.mockClear()
+ })
+
+ it('commits mutation, path refresh, and audit through the same transaction client', async () => {
+ const res = response()
+ await handlePatch(
- { params: { id: FILE }, body: { newName: 'b.md' }, query: { drive: 'main' }, ip: '127.0.0.1' } as never,
++ {
++ params: { id: FILE },
++ body: { newName: 'b.md' },
++ query: { drive: 'main' },
++ ip: '127.0.0.1',
++ } as never,
+ res as never
+ )
+ expect(res.code).toBe(200)
+ expect(state.auditDb).toBe(state.db)
+ expect(state.events).toEqual([
+ 'begin',
+ 'advisory',
+ 'row-locks',
+ 'mutation',
+ 'paths',
+ 'audit',
+ 'commit',
+ ])
+ })
+
+ it('rolls back before the allowed audit when canonical path publication fails', async () => {
+ state.failPaths = true
+ const res = response()
+ await handlePatch(
- { params: { id: FILE }, body: { newName: 'b.md' }, query: { drive: 'main' }, ip: '127.0.0.1' } as never,
++ {
++ params: { id: FILE },
++ body: { newName: 'b.md' },
++ query: { drive: 'main' },
++ ip: '127.0.0.1',
++ } as never,
+ res as never
+ )
+ expect(res.code).toBe(412)
+ expect(state.events).toContain('rollback')
+ expect(state.events).not.toContain('audit')
+ expect(state.events).not.toContain('commit')
+ })
+
+ it('commits an audited authorization denial without publishing a mutation', async () => {
+ state.operator = false
+ const res = response()
+ await handlePatch(
- { params: { id: FILE }, body: { newName: 'b.md' }, query: { drive: 'main' }, ip: '127.0.0.1' } as never,
++ {
++ params: { id: FILE },
++ body: { newName: 'b.md' },
++ query: { drive: 'main' },
++ ip: '127.0.0.1',
++ } as never,
+ res as never
+ )
+ expect(res.code).toBe(403)
+ expect(state.events).toContain('audit')
+ expect(state.events).toContain('commit')
+ expect(state.events).not.toContain('mutation')
+ })
+
+ it('commits exactly one cross-boundary denial audit and no mutation', async () => {
+ const res = response()
+ await handlePatch(
- { params: { id: FILE }, body: { newParentId: OTHER }, query: { drive: 'main' }, ip: '127.0.0.1' } as never,
++ {
++ params: { id: FILE },
++ body: { newParentId: OTHER },
++ query: { drive: 'main' },
++ ip: '127.0.0.1',
++ } as never,
+ res as never
+ )
+ expect(res.code).toBe(403)
+ expect(res.body).toMatchObject({ error: { code: 'cross_boundary' } })
+ expect(state.audits).toHaveLength(1)
+ expect(state.events).toEqual(['begin', 'advisory', 'audit', 'commit'])
+ expect(state.events).not.toContain('mutation')
+ })
+ })
diff --cc control-api/test/gfsResources.test.ts
index 81ab79e51,520e71daf..82fb92716
--- a/control-api/test/gfsResources.test.ts
+++ b/control-api/test/gfsResources.test.ts
@@@ -5,15 -5,6 +5,7 @@@ import
ResourcePatchError,
applyResourcePatch,
} from '../src/routes/gfs/resources.js'
+
- /**
- * P2-S05 — move/rename write path (control-api half). Drives applyResourcePatch
- * with a fake GrantsDb. Acceptance: rename → write on the resource; move →
- * write+delete on src parent + write on dest parent; cross-drive → cross_boundary;
- * stale If-Match → precondition_failed; no escalation (a caller without the bit
- * is forbidden).
- */
-
const FILE = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'
const SRC = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'
const DEST = 'cccccccc-cccc-cccc-cccc-cccccccccccc'
@@@ -239,6 -270,16 +271,23 @@@ describe('applyResourcePatch — concur
})
})
+ it('rejects destination live/kind/parent/version changes while acquiring row locks', async () => {
- const mutations = [(r: Record<string, ResRow>) => (r[DEST].version += 1), (r: Record<string, ResRow>) => (r[DEST].kind = 'file'), (r: Record<string, ResRow>) => (r[DEST].parent_resource_id = SRC), (r: Record<string, ResRow>) => (r[DEST].deleted_at = '2026-07-17')]
++ const mutations = [
++ (r: Record<string, ResRow>) => (r[DEST].version += 1),
++ (r: Record<string, ResRow>) => (r[DEST].kind = 'file'),
++ (r: Record<string, ResRow>) => (r[DEST].parent_resource_id = SRC),
++ (r: Record<string, ResRow>) => (r[DEST].deleted_at = '2026-07-17'),
++ ]
+ for (const afterLock of mutations) {
- await expect(patch(mockDb({ afterLock }), operator, FILE, { newParentId: DEST })).rejects.toMatchObject({
++ await expect(
++ patch(mockDb({ afterLock }), operator, FILE, { newParentId: DEST })
++ ).rejects.toMatchObject({
+ status: 412,
+ code: 'precondition_failed',
+ })
+ }
+ })
+
it('a sibling-name collision is already_exists', async () => {
await expect(
patch(mockDb({ update: 'conflict' }), operator, FILE, { newParentId: DEST })
@@@ -248,6 -289,34 +297,36 @@@
})
})
+ it('takes the drive advisory lock before deterministic row locks', async () => {
+ const db = mockDb()
+ await patch(db, operator, FILE, { newParentId: DEST })
+ const advisory = db.queries.findIndex(query => query.text.includes('pg_advisory_xact_lock'))
- const rows = db.queries.findIndex(query => query.text.includes('ORDER BY resource_id') && query.text.includes('FOR UPDATE'))
++ const rows = db.queries.findIndex(
++ query => query.text.includes('ORDER BY resource_id') && query.text.includes('FOR UPDATE')
++ )
+ expect(advisory).toBeGreaterThanOrEqual(0)
+ expect(rows).toBeGreaterThan(advisory)
+ expect(db.queries[rows].values?.[0]).toEqual([FILE, SRC, DEST].sort())
+ })
+
+ it('fails closed when the source parent is tombstoned while rows are acquired', async () => {
+ const db = mockDb({ afterLock: resources => (resources[SRC].deleted_at = '2026-07-17') })
+ await expect(patch(db, operator, FILE, { newName: 'b.md' })).rejects.toMatchObject({
+ status: 412,
+ code: 'precondition_failed',
+ })
+ })
+
+ it('recomputes the complete subtree path from parent/name rather than replacing text', async () => {
+ const db = mockDb()
+ await patch(db, operator, DIR, { newName: 'renamed' })
+ const refresh = db.queries.find(query => query.text.includes('WITH RECURSIVE subtree'))
+ expect(refresh?.text).toContain("parent.canonical_path || '/' || child.name")
+ expect(refresh?.text).toContain('UPDATE gfs_resources resource')
+ expect(refresh?.text.toLowerCase()).not.toContain('replace(')
+ expect(refresh?.values).toEqual(['main', DIR, '/renamed'])
+ })
+
it('a no-op patch is path_invalid', async () => {
await expect(patch(mockDb(), operator, FILE, {})).rejects.toBeInstanceOf(ResourcePatchError)
})
diff --cc control-api/test/gfsStructuralIntegrity.realPostgres.integration.test.ts
index 000000000,09a5fb963..8b09d1728
mode 000000,100644..100644
--- a/control-api/test/gfsStructuralIntegrity.realPostgres.integration.test.ts
+++ b/control-api/test/gfsStructuralIntegrity.realPostgres.integration.test.ts
@@@ -1,0 -1,349 +1,384 @@@
+ import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+ import { createHash, randomBytes, randomUUID } from 'node:crypto'
+ import type { Readable } from 'node:stream'
+ import { Pool, type PoolClient } from 'pg'
-import { initDb } from '../src/db.js'
-import { applyResourcePatch } from '../src/routes/gfs/resources.js'
-import type { GfsCaller } from '../src/routes/gfs/grants.js'
+ import { PgBlobStagingStore } from '../../gfs-controller/src/db/blobStaging.js'
+ import {
- GfsWriteService,
+ type BlobWriter,
++ GfsWriteService,
+ type Transactor,
+ } from '../../gfs-controller/src/db/writeStore.js'
++import { initDb } from '../src/db.js'
++import type { GfsCaller } from '../src/routes/gfs/grants.js'
++import { applyResourcePatch } from '../src/routes/gfs/resources.js'
+
+ const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
+ const describeRealPostgres = adminUrl ? describe : describe.skip
+ const operator: GfsCaller = {
+ isOperator: true,
+ subjects: new Set(['operator:']),
+ actorKey: 'operator:',
+ }
+
+ function databaseUrl(baseUrl: string, database: string): string {
+ const url = new URL(baseUrl)
+ url.pathname = `/${database}`
+ return url.toString()
+ }
+
+ function quoteIdent(value: string): string {
+ return `"${value.replace(/"/g, '""')}"`
+ }
+
+ async function begin(client: PoolClient): Promise<void> {
+ await client.query('BEGIN')
+ await client.query(`SET LOCAL lock_timeout = '5s'`)
+ await client.query(`SET LOCAL statement_timeout = '10s'`)
+ }
+
+ async function waitUntilBlocked(
+ pool: Pool,
+ blockedPid: number,
+ blockerPid: number,
+ label: string
+ ): Promise<void> {
+ const deadline = Date.now() + 5_000
+ while (Date.now() < deadline) {
+ const result = await pool.query<{ blocked: boolean }>(
+ `SELECT $2::integer = ANY(pg_blocking_pids($1::integer)) AS blocked`,
+ [blockedPid, blockerPid]
+ )
+ if (result.rows[0]?.blocked) return
+ await new Promise<void>(resolve => setImmediate(resolve))
+ }
+ throw new Error(`${label}: expected PostgreSQL blocker was not observed`)
+ }
+
+ interface Tree {
+ drive: string
+ root: string
+ source: string
+ destinationA: string
+ destinationB: string
+ child: string
+ }
+
+ async function seedTree(pool: Pool, label: string): Promise<Tree> {
+ const tree: Tree = {
+ drive: `real-pg-${label}-${randomBytes(4).toString('hex')}`,
+ root: randomUUID(),
+ source: randomUUID(),
+ destinationA: randomUUID(),
+ destinationB: randomUUID(),
+ child: randomUUID(),
+ }
+ await pool.query(
+ `INSERT INTO gfs_resources
+ (resource_id, drive, parent_resource_id, name, kind, path_cache, version, bytes)
+ VALUES ($1,$6,NULL,'','directory','/',0,0),
+ ($2,$6,$1,'source','directory','/source',0,0),
+ ($3,$6,$1,'destination-a','directory','/destination-a',0,0),
+ ($4,$6,$1,'destination-b','directory','/destination-b',0,0),
+ ($5,$6,$2,'child.txt','file','/source/child.txt',0,0)`,
+ [tree.root, tree.source, tree.destinationA, tree.destinationB, tree.child, tree.drive]
+ )
+ return tree
+ }
+
+ async function move(client: PoolClient, tree: Tree, destination: string): Promise<number> {
+ const result = await applyResourcePatch(
+ client,
+ operator,
+ tree.drive,
+ tree.child,
+ { newParentId: destination },
+ async () => undefined
+ )
+ return result.version
+ }
+
+ const blobs: BlobWriter = {
+ async writeImmutable(resourceId: string, generation: string, data: Readable | Buffer) {
+ if (!Buffer.isBuffer(data)) throw new Error('real-PG fixture expects buffered replacement')
+ return {
+ blobKey: `${resourceId.replaceAll('-', '')}/${generation}`,
+ bytes: data.length,
+ contentSha256: createHash('sha256').update(data).digest('hex'),
+ }
+ },
+ async verify() {},
+ async deleteByKey() {},
+ async deleteLegacyFlat() {},
+ }
+
+ function boundTransaction(client: PoolClient): Transactor {
+ return { transaction: work => work(client) }
+ }
+ function writer(client: PoolClient, manifests = new PgBlobStagingStore(client)): GfsWriteService {
+ return new GfsWriteService(boundTransaction(client), blobs, manifests)
+ }
+ function deferred(): { promise: Promise<void>; resolve: () => void } {
+ let resolve!: () => void
- const promise = new Promise<void>(done => { resolve = done })
++ const promise = new Promise<void>(done => {
++ resolve = done
++ })
+ return { promise, resolve }
+ }
+ async function expectNoLiveNodeBelowTombstone(pool: Pool): Promise<void> {
+ const result = await pool.query<{ violations: string }>(`WITH RECURSIVE ancestry AS (
+ SELECT resource_id AS live_id,parent_resource_id,ARRAY[resource_id]::uuid[] visited
+ FROM gfs_resources WHERE deleted_at IS NULL UNION ALL
+ SELECT a.live_id,p.parent_resource_id,a.visited||p.resource_id FROM ancestry a
+ JOIN gfs_resources p ON p.resource_id=a.parent_resource_id
+ WHERE NOT p.resource_id=ANY(a.visited))
+ SELECT count(*) violations FROM ancestry a JOIN gfs_resources p
+ ON p.resource_id=a.parent_resource_id WHERE p.deleted_at IS NOT NULL`)
+ expect(Number(result.rows[0]?.violations)).toBe(0)
+ }
+
+ describeRealPostgres('GFS Phase 0 real PostgreSQL integrity', () => {
+ const database = `gfs_phase0_${randomBytes(6).toString('hex')}`
+ const connectionString = databaseUrl(
+ adminUrl ?? 'postgresql://[email protected]/postgres',
+ database
+ )
+ let adminPool: Pool
+ let pool: Pool
+
+ beforeAll(async () => {
+ adminPool = new Pool({ connectionString: adminUrl })
+ await adminPool.query(`CREATE DATABASE ${quoteIdent(database)}`)
+ pool = new Pool({ connectionString })
+ await initDb({ connect: () => pool.connect() })
+ }, 60_000)
+
+ afterAll(async () => {
+ await pool?.end()
+ if (!adminPool) return
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ await adminPool.end()
+ })
+
+ it('serializes create/delete and makes delete observe the committed child', async () => {
+ const tree = await seedTree(pool, 'create-delete')
+ const creator = await pool.connect()
+ const deleter = await pool.connect()
+ try {
+ await Promise.all([begin(creator), begin(deleter)])
+ const creatorPid = Number((await creator.query('SELECT pg_backend_pid() pid')).rows[0]?.pid)
+ const deleterPid = Number((await deleter.query('SELECT pg_backend_pid() pid')).rows[0]?.pid)
+ await writer(creator).create({
+ drive: tree.drive,
+ parentId: tree.destinationA,
+ name: 'concurrent',
+ kind: 'directory',
+ })
- const deletion = writer(deleter).delete({
- drive: tree.drive,
- resourceId: tree.destinationA,
- ifMatch: 0,
- }).catch(error => error as { code?: string })
++ const deletion = writer(deleter)
++ .delete({
++ drive: tree.drive,
++ resourceId: tree.destinationA,
++ ifMatch: 0,
++ })
++ .catch(error => error as { code?: string })
+ await waitUntilBlocked(pool, deleterPid, creatorPid, 'create/delete')
+ await creator.query('COMMIT')
+ await expect(deletion).resolves.toMatchObject({ code: 'not_empty' })
+ await deleter.query('ROLLBACK')
+ } finally {
+ await creator.query('ROLLBACK').catch(() => undefined)
+ await deleter.query('ROLLBACK').catch(() => undefined)
+ for (const client of [creator, deleter]) client.release()
+ }
+ await expectNoLiveNodeBelowTombstone(pool)
+ }, 20_000)
+
+ it('serializes move/delete and prevents a half-observed destination', async () => {
+ const tree = await seedTree(pool, 'move-delete')
+ const [mover, deleter] = await Promise.all([pool.connect(), pool.connect()])
+ try {
+ await Promise.all([begin(mover), begin(deleter)])
+ const moverPid = Number((await mover.query('SELECT pg_backend_pid() pid')).rows[0]?.pid)
+ const deleterPid = Number((await deleter.query('SELECT pg_backend_pid() pid')).rows[0]?.pid)
+ expect(await move(mover, tree, tree.destinationA)).toBe(1)
- const deletion = writer(deleter).delete({
- drive: tree.drive,
- resourceId: tree.destinationA,
- ifMatch: 0,
- }).catch(error => error as { code?: string })
++ const deletion = writer(deleter)
++ .delete({
++ drive: tree.drive,
++ resourceId: tree.destinationA,
++ ifMatch: 0,
++ })
++ .catch(error => error as { code?: string })
+ await waitUntilBlocked(pool, deleterPid, moverPid, 'move/delete')
+ await mover.query('COMMIT')
+ await expect(deletion).resolves.toMatchObject({ code: 'not_empty' })
+ await deleter.query('ROLLBACK')
+ } finally {
+ await mover.query('ROLLBACK').catch(() => undefined)
+ await deleter.query('ROLLBACK').catch(() => undefined)
+ for (const client of [mover, deleter]) client.release()
+ }
+ await expectNoLiveNodeBelowTombstone(pool)
+ }, 20_000)
+
+ it('rejects moving a directory below its descendant', async () => {
+ const tree = await seedTree(pool, 'cycle')
+ const descendant = randomUUID()
- await pool.query(`INSERT INTO gfs_resources
++ await pool.query(
++ `INSERT INTO gfs_resources
+ (resource_id,drive,parent_resource_id,name,kind,path_cache,version,bytes)
+ VALUES ($1,$2,$3,'descendant','directory','/source/descendant',0,0)`,
- [descendant, tree.drive, tree.source])
++ [descendant, tree.drive, tree.source]
++ )
+ const client = await pool.connect()
+ try {
+ await begin(client)
- await expect(applyResourcePatch(
- client, operator, tree.drive, tree.source, { newParentId: descendant }, async () => undefined
- )).rejects.toMatchObject({ code: 'path_invalid' })
++ await expect(
++ applyResourcePatch(
++ client,
++ operator,
++ tree.drive,
++ tree.source,
++ { newParentId: descendant },
++ async () => undefined
++ )
++ ).rejects.toMatchObject({ code: 'path_invalid' })
+ } finally {
+ await client.query('ROLLBACK').catch(() => undefined)
+ client.release()
+ }
+ const source = await pool.query(
- 'SELECT parent_resource_id,path_cache,version FROM gfs_resources WHERE resource_id=$1', [tree.source])
- expect(source.rows).toEqual([{ parent_resource_id: tree.root, path_cache: '/source', version: 0 }])
++ 'SELECT parent_resource_id,path_cache,version FROM gfs_resources WHERE resource_id=$1',
++ [tree.source]
++ )
++ expect(source.rows).toEqual([
++ { parent_resource_id: tree.root, path_cache: '/source', version: 0 },
++ ])
+ })
+
+ it('atomically refreshes path_cache for every node in a moved subtree', async () => {
+ const tree = await seedTree(pool, 'subtree-paths')
+ const [nested, leaf] = [randomUUID(), randomUUID()]
+ await pool.query(
+ `INSERT INTO gfs_resources
+ (resource_id, drive, parent_resource_id, name, kind, path_cache, version, bytes)
+ VALUES ($1,$3,$4,'nested','directory','/source/nested',0,0),
+ ($2,$3,$1,'leaf.txt','file','/source/nested/leaf.txt',0,0)`,
+ [nested, leaf, tree.drive, tree.source]
+ )
+ const client = await pool.connect()
+ try {
+ await begin(client)
+ await applyResourcePatch(
- client, operator, tree.drive, tree.source, { newParentId: tree.destinationA }, async () => undefined
++ client,
++ operator,
++ tree.drive,
++ tree.source,
++ { newParentId: tree.destinationA },
++ async () => undefined
++ )
++ const beforeCommit = await pool.query(
++ `SELECT path_cache FROM gfs_resources
++ WHERE resource_id=ANY($1::uuid[]) ORDER BY path_cache`,
++ [[tree.source, tree.child, nested, leaf]]
+ )
- const beforeCommit = await pool.query(`SELECT path_cache FROM gfs_resources
- WHERE resource_id=ANY($1::uuid[]) ORDER BY path_cache`, [[tree.source, tree.child, nested, leaf]])
+ expect(beforeCommit.rows.map(row => row.path_cache)).toEqual([
- '/source', '/source/child.txt', '/source/nested', '/source/nested/leaf.txt',
++ '/source',
++ '/source/child.txt',
++ '/source/nested',
++ '/source/nested/leaf.txt',
+ ])
+ await client.query('COMMIT')
+ } finally {
+ await client.query('ROLLBACK').catch(() => undefined)
+ client.release()
+ }
- const paths = await pool.query(`SELECT name,path_cache FROM gfs_resources
- WHERE resource_id=ANY($1::uuid[]) ORDER BY path_cache`, [[tree.source, tree.child, nested, leaf]])
++ const paths = await pool.query(
++ `SELECT name,path_cache FROM gfs_resources
++ WHERE resource_id=ANY($1::uuid[]) ORDER BY path_cache`,
++ [[tree.source, tree.child, nested, leaf]]
++ )
+ expect(paths.rows).toEqual([
+ { name: 'source', path_cache: '/destination-a/source' },
+ { name: 'child.txt', path_cache: '/destination-a/source/child.txt' },
+ { name: 'nested', path_cache: '/destination-a/source/nested' },
+ { name: 'leaf.txt', path_cache: '/destination-a/source/nested/leaf.txt' },
+ ])
+ })
+
+ it('serializes two moves and leaves one coherent final parent and path', async () => {
+ const tree = await seedTree(pool, 'move-move')
+ const [first, second] = await Promise.all([pool.connect(), pool.connect()])
+ try {
+ await Promise.all([begin(first), begin(second)])
+ const firstPid = Number((await first.query('SELECT pg_backend_pid() pid')).rows[0]?.pid)
+ const secondPid = Number((await second.query('SELECT pg_backend_pid() pid')).rows[0]?.pid)
+ expect(await move(first, tree, tree.destinationA)).toBe(1)
+ const secondMove = move(second, tree, tree.destinationB)
+ await waitUntilBlocked(pool, secondPid, firstPid, 'move/move')
+ await first.query('COMMIT')
+ await expect(secondMove).resolves.toBe(2)
+ await second.query('COMMIT')
+ const final = await pool.query(
+ `SELECT parent_resource_id,path_cache,version FROM gfs_resources WHERE resource_id=$1`,
+ [tree.child]
+ )
- expect(final.rows).toEqual([{
- parent_resource_id: tree.destinationB,
- path_cache: '/destination-b/child.txt',
- version: 2,
- }])
++ expect(final.rows).toEqual([
++ {
++ parent_resource_id: tree.destinationB,
++ path_cache: '/destination-b/child.txt',
++ version: 2,
++ },
++ ])
+ } finally {
+ await first.query('ROLLBACK').catch(() => undefined)
+ await second.query('ROLLBACK').catch(() => undefined)
+ for (const client of [first, second]) client.release()
+ }
+ }, 20_000)
+
+ it('never lets cleanup claim a generation while publication holds its row lock', async () => {
+ const tree = await seedTree(pool, 'publish-cleanup')
+ const [publisher, cleanup] = await Promise.all([pool.connect(), pool.connect()])
+ const paused = deferred()
+ const resume = deferred()
+ try {
+ await begin(cleanup)
+ const transactor: Transactor = {
+ transaction: async work => {
+ await begin(publisher)
+ const result = await work(publisher)
+ paused.resolve()
+ await resume.promise
+ await publisher.query('COMMIT')
+ return result
+ },
+ }
+ const manifests = new PgBlobStagingStore(pool)
+ const replacement = new GfsWriteService(transactor, blobs, manifests).replace({
+ drive: tree.drive,
+ resourceId: tree.child,
+ ifMatch: 0,
+ content: Buffer.from('replacement'),
+ })
+ await paused.promise
+ const store = new PgBlobStagingStore(cleanup)
+ await expect(store.claimExpiredCandidate(0)).resolves.toBeNull()
+ resume.resolve()
+ const published = await replacement
+ const row = await pool.query<{ blob_key: string | null }>(
+ 'SELECT blob_key FROM gfs_resources WHERE resource_id=$1',
+ [tree.child]
+ )
+ expect(row.rows[0]?.blob_key).toBe(published.blobKey)
+ await cleanup.query('ROLLBACK')
+ } finally {
+ await publisher.query('ROLLBACK').catch(() => undefined)
+ await cleanup.query('ROLLBACK').catch(() => undefined)
+ for (const client of [publisher, cleanup]) client.release()
+ }
+ }, 20_000)
+ })
diff --cc control-api/test/routes.overview.test.ts
index 538f0edb9,797dff7fc..289cbf827
--- a/control-api/test/routes.overview.test.ts
+++ b/control-api/test/routes.overview.test.ts
@@@ -1,86 -1,135 +1,136 @@@
--import express from "express";
--import request from "supertest";
--import { describe, expect, it, vi } from "vitest";
--import { createAdminHostsOverviewRouter } from "../src/routes/admin/hostsOverview.js";
--import { MockGateway } from "./mockGateway.js";
--
--describe("routes/admin.hostsOverview", () => {
-- it("returns hosts overview list and single host overview", async () => {
-- const gateway = new MockGateway("mcp-server");
++import { describe, expect, it, vi } from 'vitest'
++import express from 'express'
++import request from 'supertest'
++import { createAdminHostsOverviewRouter } from '../src/routes/admin/hostsOverview.js'
++import { MockGateway } from './mockGateway.js'
++
++describe('routes/admin.hostsOverview', () => {
++ it('returns hosts overview list and single host overview', async () => {
++ const gateway = new MockGateway('mcp-server')
await gateway.createResource(
-- "hosts",
-- { metadata: { name: "host-a", namespace: "mcp-host" }, spec: { contextRef: "ctx-a" } },
-- "mcp-host"
-- );
++ 'hosts',
++ { metadata: { name: 'host-a', namespace: 'mcp-host' }, spec: { contextRef: 'ctx-a' } },
++ 'mcp-host'
++ )
await gateway.createResource(
-- "contexts",
-- { metadata: { name: "ctx-a", namespace: "mcp-server" }, spec: { contextId: "ctx-a", mcpServers: [] } },
-- "mcp-server"
-- );
++ 'contexts',
++ {
++ metadata: { name: 'ctx-a', namespace: 'mcp-server' },
++ spec: { contextId: 'ctx-a', mcpServers: [] },
++ },
++ 'mcp-server'
++ )
-- const app = express();
-- app.use(createAdminHostsOverviewRouter(gateway as never));
++ const app = express()
++ app.use(createAdminHostsOverviewRouter(gateway as never))
// Hardened: no ?namespace= on requests; route uses config.hostsNamespace internally.
-- const listRes = await request(app).get("/admin/hosts-overview").expect(200);
-- expect(listRes.body.items).toHaveLength(1);
-- expect(listRes.body.items[0].host.spec.contextRef).toBe("ctx-a");
++ const listRes = await request(app).get('/admin/hosts-overview').expect(200)
++ expect(listRes.body.items).toHaveLength(1)
++ expect(listRes.body.items[0].host.spec.contextRef).toBe('ctx-a')
+ expect(listRes.body.agents).toEqual([
+ {
- name: "host-a",
- namespace: "mcp-host",
- displayName: "host-a",
++ name: 'host-a',
++ namespace: 'mcp-host',
++ displayName: 'host-a',
+ active: true,
- gfsSubject: { type: "host", id: "1st:mcp-host/host-a" },
++ gfsSubject: { type: 'host', id: '1st:mcp-host/host-a' },
+ },
- ]);
++ ])
+
- const singleRes = await request(app).get("/admin/hosts/host-a/overview").expect(200);
- expect(singleRes.body.host.metadata.name).toBe("host-a");
- expect(singleRes.body.agent.gfsSubject.id).toBe("1st:mcp-host/host-a");
- });
++ const singleRes = await request(app).get('/admin/hosts/host-a/overview').expect(200)
++ expect(singleRes.body.host.metadata.name).toBe('host-a')
++ expect(singleRes.body.agent.gfsSubject.id).toBe('1st:mcp-host/host-a')
++ })
+
- it("keeps overview compatibility while directory excludes invalid Host identities", async () => {
++ it('keeps overview compatibility while directory excludes invalid Host identities', async () => {
+ const hosts = [
- { metadata: { name: "visible", namespace: "mcp-host" }, spec: { host: "Visible" } },
- { metadata: { name: "disabled", namespace: "mcp-host" }, spec: { enabled: false } },
++ { metadata: { name: 'visible', namespace: 'mcp-host' }, spec: { host: 'Visible' } },
++ { metadata: { name: 'disabled', namespace: 'mcp-host' }, spec: { enabled: false } },
+ {
+ metadata: {
- name: "deleted",
- namespace: "mcp-host",
- deletionTimestamp: "2026-07-17T12:00:00Z",
++ name: 'deleted',
++ namespace: 'mcp-host',
++ deletionTimestamp: '2026-07-17T12:00:00Z',
+ },
+ spec: {},
+ },
- { metadata: { name: "other", namespace: "sandbox-recipes" }, spec: {} },
- ];
++ { metadata: { name: 'other', namespace: 'sandbox-recipes' }, spec: {} },
++ ]
+ const gateway = {
+ listResource: vi.fn(async () => hosts),
+ getHostOverview: vi.fn(async (name: string, namespace: string) => ({
+ host: hosts.find(host => host.metadata.name === name),
+ namespace,
+ })),
- };
++ }
+
- const app = express();
- app.use(createAdminHostsOverviewRouter(gateway as never));
++ const app = express()
++ app.use(createAdminHostsOverviewRouter(gateway as never))
- const singleRes = await request(app).get("/admin/hosts/host-a/overview").expect(200);
- expect(singleRes.body.host.metadata.name).toBe("host-a");
- });
- const res = await request(app).get("/admin/hosts-overview").expect(200);
- expect(res.body.items).toHaveLength(4);
++ const res = await request(app).get('/admin/hosts-overview').expect(200)
++ expect(res.body.items).toHaveLength(4)
+ expect(res.body.agents).toEqual([
+ {
- name: "visible",
- namespace: "mcp-host",
- displayName: "Visible",
++ name: 'visible',
++ namespace: 'mcp-host',
++ displayName: 'Visible',
+ active: true,
- gfsSubject: { type: "host", id: "1st:mcp-host/visible" },
++ gfsSubject: { type: 'host', id: '1st:mcp-host/visible' },
+ },
- ]);
- });
++ ])
++ })
-- it("returns 500 when host overview fails", async () => {
++ it('returns 500 when host overview fails', async () => {
const gateway = {
-- listResource: vi.fn(async () => [{ metadata: { name: "host-a", namespace: "mcp-host" } }]),
++ listResource: vi.fn(async () => [{ metadata: { name: 'host-a', namespace: 'mcp-host' } }]),
getHostOverview: vi.fn(async () => {
-- throw new Error("overview-failed");
-- })
-- };
-
- const app = express();
- app.use(createAdminHostsOverviewRouter(gateway as never));
- app.use((err: unknown, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
- res.status(500).json({ error: err instanceof Error ? err.message : "unknown" });
- });
-
- const res = await request(app).get("/admin/hosts-overview").expect(500);
- expect(res.body.error).toBe("overview-failed");
- });
++ throw new Error('overview-failed')
++ }),
++ }
+
- const app = express();
- app.use(createAdminHostsOverviewRouter(gateway as never));
- app.use((err: unknown, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
- res.status(500).json({ error: err instanceof Error ? err.message : "unknown" });
- });
++ const app = express()
++ app.use(createAdminHostsOverviewRouter(gateway as never))
++ app.use(
++ (err: unknown, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
++ res.status(500).json({ error: err instanceof Error ? err.message : 'unknown' })
++ }
++ )
+
- const res = await request(app).get("/admin/hosts-overview").expect(500);
- expect(res.body.error).toBe("overview-failed");
- });
++ const res = await request(app).get('/admin/hosts-overview').expect(500)
++ expect(res.body.error).toBe('overview-failed')
++ })
// ── Namespace audit: caller namespace is silently ignored ────────────────
-- it("silently ignores ?namespace= query parameter and uses config namespace", async () => {
++ it('silently ignores ?namespace= query parameter and uses config namespace', async () => {
const gateway = {
listResource: vi.fn(async () => []),
getHostOverview: vi.fn(),
-- };
-- const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
-- const app = express();
-- app.use(createAdminHostsOverviewRouter(gateway as never));
++ }
++ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
++ const app = express()
++ app.use(createAdminHostsOverviewRouter(gateway as never))
// Namespace in query string is silently ignored — request succeeds (200, not 400)
const listRes = await request(app)
-- .get("/admin/hosts-overview?namespace=control-plane")
-- .expect(200);
-- expect(listRes.body.items).toEqual([]);
- expect(listRes.body.agents).toEqual([]);
++ .get('/admin/hosts-overview?namespace=control-plane')
++ .expect(200)
++ expect(listRes.body.items).toEqual([])
++ expect(listRes.body.agents).toEqual([])
const singleRes = await request(app)
-- .get("/admin/hosts/host-a/overview?namespace=control-plane")
-- .expect(200);
++ .get('/admin/hosts/host-a/overview?namespace=control-plane')
++ .expect(200)
// Gateway was called despite namespace in query (it's silently ignored)
-- expect(gateway.listResource).toHaveBeenCalled();
-- expect(gateway.getHostOverview).toHaveBeenCalled();
++ expect(gateway.listResource).toHaveBeenCalled()
++ expect(gateway.getHostOverview).toHaveBeenCalled()
// Security audit was logged
-- expect(warnSpy).toHaveBeenCalledWith(
-- expect.stringContaining('"alert":"SECURITY"'),
-- );
-- expect(warnSpy).toHaveBeenCalledWith(
-- expect.stringContaining('"vector":"query-param"'),
-- );
--
-- warnSpy.mockRestore();
-- });
--});
++ expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('"alert":"SECURITY"'))
++ expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('"vector":"query-param"'))
++
++ warnSpy.mockRestore()
++ })
++})
diff --cc control-api/test/routes.profileAdmin.test.ts
index d6a3f5592,483b6a66e..559e8cba5
--- a/control-api/test/routes.profileAdmin.test.ts
+++ b/control-api/test/routes.profileAdmin.test.ts
@@@ -187,6 -194,116 +187,66 @@@ describe('routes/profileAdmin', () =>
expect(svc.createInvitationForTeams).not.toHaveBeenCalled()
})
- it('returns deleted context history but active-only agent grants for admin user/team views', async () => {
++ it('returns deleted context history for admin user and team views', async () => {
+ ;(gatewayStub.listResource as any).mockImplementation(async (plural: string) => {
+ if (plural === 'contexts') {
+ return [{ metadata: { name: 'ctx-live' }, spec: { contextId: 'ctx-alias' } }]
+ }
- if (plural === 'hosts') {
- return [{ metadata: { name: 'agent-live', namespace: 'mcp-host' }, spec: { enabled: true } }]
- }
+ return []
+ })
+ svc.getUserContexts.mockResolvedValue({ userId: 'u1', contextIds: ['ctx-live', 'ctx-old'] })
- svc.getUserAgents.mockResolvedValue({
- userId: 'u1',
- agentNames: ['agent-live', 'agent-old'],
- })
+ svc.getTeamContexts.mockResolvedValue({ teamId: 't1', contextIds: ['ctx-live', 'ctx-old'] })
- svc.getTeamAgents.mockResolvedValue({
- teamId: 't1',
- agentNames: ['agent-live', 'agent-old'],
- })
+
+ const app = express()
+ app.use(express.json())
+ app.use(createAdminRouter(gatewayStub as unknown as K8sGateway))
+
+ await request(app)
+ .get('/admin/users/u1/contexts')
+ .expect(200)
+ .expect({ userId: 'u1', contextIds: ['ctx-live'], deletedContextIds: ['ctx-old'] })
- await request(app)
- .get('/admin/users/u1/agents')
- .expect(200)
- .expect({ userId: 'u1', agentNames: ['agent-live'] })
+ await request(app)
+ .get('/admin/teams/t1/contexts')
+ .expect(200)
+ .expect({ teamId: 't1', contextIds: ['ctx-live'], deletedContextIds: ['ctx-old'] })
- await request(app)
- .get('/admin/teams/t1/agents')
- .expect(200)
- .expect({ teamId: 't1', agentNames: ['agent-live'] })
+ })
+
- it('preserves deleted context history but drops stale agent grants on admin updates', async () => {
++ it('preserves deleted context history on admin updates', async () => {
+ ;(gatewayStub.listResource as any).mockImplementation(async (plural: string) => {
+ if (plural === 'contexts') {
+ return [{ metadata: { name: 'ctx-live' }, spec: { contextId: 'ctx-alias' } }]
+ }
- if (plural === 'hosts') {
- return [{ metadata: { name: 'agent-live', namespace: 'mcp-host' }, spec: { enabled: true } }]
- }
+ return []
+ })
+ svc.getUserContexts.mockResolvedValue({ userId: 'u1', contextIds: ['ctx-old'] })
+ svc.setUserContexts.mockResolvedValue({ userId: 'u1', contextIds: ['ctx-live', 'ctx-old'] })
- svc.setUserAgents.mockResolvedValue({
- userId: 'u1',
- agentNames: ['agent-live'],
- })
- svc.setTeamAgents.mockResolvedValue({
- teamId: 't1',
- agentNames: ['agent-live'],
- })
+
+ const app = express()
+ app.use(express.json())
+ app.use(createAdminRouter(gatewayStub as unknown as K8sGateway))
+
+ await request(app)
+ .put('/admin/users/u1/contexts')
+ .send({ contextIds: ['ctx-live', 'ctx-stale-submit'] })
+ .expect(200)
+ .expect({ userId: 'u1', contextIds: ['ctx-live'], deletedContextIds: ['ctx-old'] })
+ expect(svc.setUserContexts).toHaveBeenCalledWith('u1', ['ctx-live', 'ctx-old'], TEST_ADMIN_SUB)
-
- await request(app)
- .put('/admin/users/u1/agents')
- .send({ agentNames: ['agent-live', 'agent-stale-submit'] })
- .expect(200)
- .expect({ userId: 'u1', agentNames: ['agent-live'] })
- expect(svc.setUserAgents).toHaveBeenCalledWith('u1', ['agent-live'], TEST_ADMIN_SUB)
-
- await request(app)
- .put('/admin/teams/t1/agents')
- .send({ agentNames: ['agent-live', 'agent-stale-submit'] })
- .expect(200)
- .expect({ teamId: 't1', agentNames: ['agent-live'] })
- expect(svc.setTeamAgents).toHaveBeenCalledWith('t1', ['agent-live'], TEST_ADMIN_SUB)
+ })
+
- it('returns structured 503s when admin access reconciliation is unavailable', async () => {
++ it('returns a structured 503 when context reconciliation is unavailable', async () => {
+ ;(gatewayStub.listResource as any).mockRejectedValue(new Error('k8s unavailable'))
+ svc.getUserContexts.mockResolvedValue({ userId: 'u1', contextIds: ['ctx-live'] })
- svc.getTeamAgents.mockResolvedValue({ teamId: 't1', agentNames: ['agent-live'] })
+
+ const app = express()
+ app.use(express.json())
+ app.use(createAdminRouter(gatewayStub as unknown as K8sGateway))
+
+ await request(app)
+ .get('/admin/users/u1/contexts')
+ .expect(503)
+ .expect({ error: 'context_reconciliation_unavailable' })
- await request(app)
- .put('/admin/teams/t1/agents')
- .send({ agentNames: ['agent-live'] })
- .expect(503)
- .expect({ error: 'agent_reconciliation_unavailable' })
+ })
+
it('handles invalid payloads and not-found branches', async () => {
svc.renameTeam.mockResolvedValue(null)
svc.updateAdminUserContext.mockResolvedValue(null)
diff --cc desktop-app/src/__tests__/appService.gfs.test.ts
index a3955c0ad,7670eaa97..c0dc1fd0b
--- a/desktop-app/src/__tests__/appService.gfs.test.ts
+++ b/desktop-app/src/__tests__/appService.gfs.test.ts
@@@ -65,11 -91,11 +91,11 @@@ describe('AppService GFS delegation sub
async subjectKey => {
const service = gfsService()
- await expect(service.grantGfs(RESOURCE_ID, subjectKey, ['read'], 'main')).rejects.toThrow(
- 'subject must be user:<id> or team:<id>'
- await expect(
- service.grantGfs(RESOURCE_ID, [subjectKey], ['read'], 'main')
- ).rejects.toThrow('subject must be user:<id>, team:<id>, or host:<party>:<ns>/<name>')
++ await expect(service.grantGfs(RESOURCE_ID, [subjectKey], ['read'], 'main')).rejects.toThrow(
++ 'subject must be user:<id>, team:<id>, or host:<party>:<ns>/<name>'
+ )
- await expect(service.createGfsShare(RESOURCE_ID, subjectKey, 'main')).rejects.toThrow(
- 'subject must be user:<id> or team:<id>'
+ await expect(service.createGfsShare(RESOURCE_ID, [subjectKey], 'main')).rejects.toThrow(
+ 'subject must be user:<id>, team:<id>, or host:<party>:<ns>/<name>'
)
expect(service.gfsClient.grant).not.toHaveBeenCalled()
diff --cc desktop-app/test/e2e-playwright/gfs-agent-copy.test.ts
index 000000000,d00cfa1b7..47a40cc34
mode 000000,100644..100644
--- a/desktop-app/test/e2e-playwright/gfs-agent-copy.test.ts
+++ b/desktop-app/test/e2e-playwright/gfs-agent-copy.test.ts
@@@ -1,0 -1,462 +1,485 @@@
+ /**
+ * Issue #797 T2: real Desktop login -> exact Agent A -> native Copy/Rename ->
+ * exact Agent B denial -> audited revoke -> same-runtime Agent A denial.
+ * SQL/PVC and grant operations are named preconditions/assertions only; no
+ * fixture helper performs the agent mutations under test.
+ */
+ import { type Locator, type Page, expect, test } from '@playwright/test'
++import { exactNameFilter } from './helpers/agentLocators'
++import { getManagedAgentPodIdentity } from './helpers/gfsAgentDiscovery'
+ import {
+ type AgentGfsCopyFixtures,
+ assertGfsInfraHealthy,
+ countGfsLiveChildrenByName,
+ getGfsChildResourceSummary,
+ getGfsTreeAclShareCounts,
+ getGfsTreeAclShareRows,
+ getGfsTreeSnapshot,
+ gfsGrantRevokeAuditCount,
+ revokeGfsGrantViaControlApi,
+ seedAgentGfsCopyFixtures,
+ } from './helpers/gfsFixtures'
-import { exactNameFilter } from './helpers/agentLocators'
-import { getManagedAgentPodIdentity } from './helpers/gfsAgentDiscovery'
+ import { openAgentsPage, openResourcesNavItem } from './navigationHelpers'
+ import { launchAndLogin } from './workflowUi'
+
+ const OWNER_EMAIL = '[email protected]'
+ // Multi-tool turns (rename + recursive list + read-every-file) on the local
+ // glm profile routinely exceed the 180s single-turn calibration.
+ const RESPONSE_TIMEOUT_MS = 300_000
+ const SENSITIVE_OUTPUT =
+ /\/data\/gfs|\/mnt\/|\.generations|blob_key|blobKey|\bSQL\b|internal (?:path|error)|stack trace/i
+
+ async function openExactAgent(
+ page: Page,
+ agentName: string,
+ opts: { reuseThread?: boolean } = {}
+ ): Promise<void> {
+ await openAgentsPage(page)
+ await expect(page.getByRole('heading', { name: 'Agents', exact: true })).toBeVisible()
+ const row = page.getByLabel(`Open details for ${agentName}`, { exact: true })
+ await expect(row).toBeVisible({ timeout: 30_000 })
+ await row.click()
+ await expect(page.getByText(agentName, { exact: true }).first()).toBeVisible({ timeout: 15_000 })
+ await page.getByTestId('nav-chat').click()
+ await expect(page.getByTestId('chat-input')).toBeVisible({ timeout: 30_000 })
+ // Starting a new chat can reset the composer to the DEFAULT agent, so it
+ // must happen BEFORE the agent switch — never after, or the turn silently
+ // goes to the wrong agent.
+ if (!opts.reuseThread) {
+ const fresh = page.getByRole('button', { name: /new (?:chat|thread)/i }).first()
+ if (await fresh.isVisible().catch(() => false)) await fresh.click()
+ }
+ // The product binds the composer to an agent ONLY through the chat view's
+ // "Switch chat agent" selector — opening another agent's details page
+ // deliberately does not switch the chat. Drive exactly that user flow.
+ const switcher = page.getByRole('button', { name: 'Switch chat agent' })
+ const boundSwitcher = switcher.filter(exactNameFilter(agentName))
+ const breadcrumb = page
+ .getByRole('navigation', { name: 'Chat breadcrumb' })
+ .getByText(agentName, { exact: true })
- if (!(await boundSwitcher.or(breadcrumb).first().isVisible().catch(() => false))) {
++ if (
++ !(await boundSwitcher
++ .or(breadcrumb)
++ .first()
++ .isVisible()
++ .catch(() => false))
++ ) {
+ await switcher.first().click()
+ await page.getByRole('menuitem', { name: agentName, exact: true }).click()
+ }
+ // A stateless agent suspended at idle wakes through the rpc-proxy
+ // wake-and-hold path (up to ~90s of scale-up) before its chat shell binds;
+ // the binding element itself remains mandatory and is the LAST gate before
+ // any turn is sent.
+ await expect(boundSwitcher.or(breadcrumb).first()).toBeVisible({ timeout: 120_000 })
+ if (opts.reuseThread) {
+ // reuseThread continues the agent's MOST-RECENT session. Callers must drive
+ // purely by visible NAMES here (never resource identifiers), because which
+ // of the agent's threads is most-recent is not guaranteed: any earlier step
+ // that opens a fresh thread for this agent becomes the newest one, so the
+ // reused prompt must not presume a specific prior conversation history.
+ await page.locator('.agent-dedicated-session-title-btn').first().click()
+ await expect(page.getByTestId('agent-response').first()).toBeVisible({ timeout: 15_000 })
+ } else {
+ await expect(page.getByTestId('agent-response')).toHaveCount(0, { timeout: 10_000 })
+ }
+ }
+
+ async function sendAgentTurn(page: Page, prompt: string): Promise<Locator> {
+ const responseIndex = await page.getByTestId('agent-response').count()
+ const approvalIndex = await page.getByTestId('approval-approve-btn').count()
+ const progressIndex = await page.getByTestId('progress-expand-btn').count()
+ await expect(page.getByTestId('chat-input')).toBeEnabled()
+ await page.getByTestId('chat-input').fill(prompt)
+ await page.getByTestId('send-button').click()
+
+ const response = page.getByTestId('agent-response').nth(responseIndex)
+ const retrySend = page.getByRole('button', { name: 'Retry last send' })
+ let approvals = 0
+ let sendRetries = 0
+ const deadline = Date.now() + RESPONSE_TIMEOUT_MS
+ for (;;) {
+ const remaining = deadline - Date.now()
+ if (remaining <= 0) throw new Error('timed out waiting for the issue #797 agent turn')
+ // A just-restarted runtime can drop the send with a visible "Temporary
+ // connection issue" banner; a real user presses the product's own
+ // "Retry last send". Bounded — a persistent failure still fails the turn.
+ if (await retrySend.isVisible().catch(() => false)) {
+ if (sendRetries >= 3) throw new Error('agent send kept failing after 3 product retries')
+ sendRetries += 1
+ // An absorbed retry must be LOUD in a green run: warn on the console
+ // and annotate the test report, without changing pass/fail semantics.
+ const turnLabel = prompt.slice(0, 80)
+ console.warn(
+ `[gfs-agent-copy] "Retry last send" pressed (attempt ${sendRetries}/3) for turn: ${turnLabel}`
+ )
- test
- .info()
- .annotations.push({
- type: 'retry-last-send',
- description: `attempt ${sendRetries}/3 for turn: ${turnLabel}`,
- })
++ test.info().annotations.push({
++ type: 'retry-last-send',
++ description: `attempt ${sendRetries}/3 for turn: ${turnLabel}`,
++ })
+ await retrySend.click()
+ continue
+ }
+ const approval = page.getByTestId('approval-approve-btn').nth(approvalIndex + approvals)
+ const approvalWait = approval
+ .waitFor({ state: 'visible', timeout: Math.min(remaining, 10_000) })
+ .then(() => 'approval' as const)
+ const responseWait = response
+ .waitFor({ state: 'visible', timeout: Math.min(remaining, 10_000) })
+ .then(() => 'response' as const)
+ // The losing waitFor keeps its timer; silence its eventual rejection so a
+ // settled turn cannot surface a late "Target closed" unhandled rejection.
+ // .catch() returns a NEW promise, so the originals still race unchanged.
+ void approvalWait.catch(() => undefined)
+ void responseWait.catch(() => undefined)
+ let visible: 'approval' | 'response'
+ try {
+ visible = await Promise.race([approvalWait, responseWait])
+ } catch {
+ // Neither appeared within this slice; loop to re-check the retry banner
+ // and the overall deadline.
+ continue
+ }
+ if (visible === 'response') break
+ await approval.click()
+ approvals += 1
+ }
+ await expect(response).toBeVisible({ timeout: RESPONSE_TIMEOUT_MS })
+ const expand = page.getByTestId('progress-expand-btn').nth(progressIndex)
+ await expect(expand).toBeVisible({ timeout: 30_000 })
+ await expand.click()
+ return expand.locator('..')
+ }
+
+ function toolRow(stepper: Locator, name: string): Locator {
+ return stepper.locator('.stepper-step').filter({ hasText: name }).last()
+ }
+
+ async function expectToolSuccess(stepper: Locator, name: string): Promise<void> {
+ const row = toolRow(stepper, name)
+ await expect(row).toBeVisible({ timeout: 15_000 })
+ await expect(row.locator('.stepper-step-fn')).toContainText(name)
+ await expect(row.locator('.stepper-step-duration.state-error')).toHaveCount(0)
+ }
+
+ async function expectToolForbidden(stepper: Locator, name: string): Promise<void> {
+ const row = toolRow(stepper, name)
+ await expect(row).toBeVisible({ timeout: 15_000 })
+ await expect(row.locator('.stepper-step-fn')).toContainText(name)
- await expect(row.locator('.stepper-step-duration.state-error')).toContainText(/gfsc 403.*forbidden/i)
++ await expect(row.locator('.stepper-step-duration.state-error')).toContainText(
++ /gfsc 403.*forbidden/i
++ )
+ await expect(row).not.toContainText(/gfsc 503|not_mounted/i)
+ await expect(stepper).not.toContainText(SENSITIVE_OUTPUT)
+ }
+
+ async function expectToolConflict(stepper: Locator, name: string): Promise<void> {
+ // A copy onto an existing name is a non-destructive conflict: gfsc maps
+ // already_exists to 409, which mcp-host redacts to `gfsc 409: conflict`.
+ // It must never read as a 503/not_mounted infra failure and must never leak
+ // server internals.
+ const row = toolRow(stepper, name)
+ await expect(row).toBeVisible({ timeout: 15_000 })
+ await expect(row.locator('.stepper-step-fn')).toContainText(name)
- await expect(row.locator('.stepper-step-duration.state-error')).toContainText(/gfsc 409.*conflict/i)
++ await expect(row.locator('.stepper-step-duration.state-error')).toContainText(
++ /gfsc 409.*conflict/i
++ )
+ await expect(row).not.toContainText(/gfsc 503|not_mounted/i)
+ await expect(stepper).not.toContainText(SENSITIVE_OUTPUT)
+ }
+
+ async function expectCopyPublicOutput(stepper: Locator): Promise<void> {
+ // The step-output panel renders the mcp-host preview, which truncates each
+ // line at 200 chars (toolUseLoopPreviews MAX_LINE_LENGTH) — a single-line
+ // copy JSON is cut after ok/requestId/resourceId/gfsUri. Those visible
+ // fields are asserted here; name and object/file/folder counts are business
+ // signals proven from the database right after each copy (child-by-name
+ // lookup plus full tree-snapshot equality), where truncation cannot hide a
+ // wrong result.
+ const row = toolRow(stepper, 'gfs_copy')
+ await row.click()
+ const output = row
+ .locator('xpath=following-sibling::*[@data-testid="step-output-panel"][1]')
+ .locator('.stepper-step-output-code')
+ await expect(output).toBeVisible({ timeout: 10_000 })
+ await expect(output).toContainText('"ok":true')
+ await expect(output).toContainText('"requestId":')
+ await expect(output).toContainText('"resourceId":')
+ await expect(output).toContainText('"gfsUri":"gfs://main/')
+ await expect(output).not.toContainText(SENSITIVE_OUTPUT)
+ }
+
+ function comparableTree(root: ReturnType<typeof getGfsTreeSnapshot>) {
- return root.map(({ relativePath, kind, bytes, content }) => ({ relativePath, kind, bytes, content }))
++ return root.map(({ relativePath, kind, bytes, content }) => ({
++ relativePath,
++ kind,
++ bytes,
++ content,
++ }))
+ }
+
+ async function openFilesBrowser(page: Page): Promise<Locator> {
+ await openResourcesNavItem(page, 'nav-files')
+ const browser = page.getByRole('region', { name: 'Global File System browser' })
+ await expect(browser).toBeVisible({ timeout: 20_000 })
+ return browser
+ }
+
+ async function browseSourceTree(page: Page, fixtures: AgentGfsCopyFixtures): Promise<void> {
+ const browser = await openFilesBrowser(page)
+ await browser.getByRole('button', { name: fixtures.tree.sourceName, exact: true }).click()
+ await expect(
+ browser.getByRole('button', { name: fixtures.tree.standaloneFileName, exact: true })
+ ).toBeVisible()
+ await browser.getByRole('button', { name: 'nested', exact: true }).click()
+ await expect(browser.getByRole('button', { name: 'alpha.txt', exact: true })).toBeVisible()
+ await browser.getByRole('button', { name: 'empty', exact: true }).click()
+ await expect(browser.getByText('This folder is empty', { exact: true })).toBeVisible()
+ }
+
+ async function browseDestinationTree(page: Page, fixtures: AgentGfsCopyFixtures): Promise<void> {
+ const browser = await openFilesBrowser(page)
+ await browser.getByRole('button', { name: fixtures.tree.destinationName, exact: true }).click()
- await expect(browser.getByRole('button', { name: fixtures.fileCopyName, exact: true })).toBeVisible()
++ await expect(
++ browser.getByRole('button', { name: fixtures.fileCopyName, exact: true })
++ ).toBeVisible()
+ await browser.getByRole('button', { name: fixtures.renamedFolderName, exact: true }).click()
+ await expect(browser.getByRole('button', { name: 'nested', exact: true })).toBeVisible()
+ await browser.getByRole('button', { name: 'nested', exact: true }).click()
+ await expect(browser.getByRole('button', { name: 'alpha.txt', exact: true })).toBeVisible()
+ await expect(browser.getByRole('button', { name: 'deeper', exact: true })).toBeVisible()
+ await browser.getByRole('button', { name: 'empty', exact: true }).click()
+ await expect(browser.getByText('This folder is empty', { exact: true })).toBeVisible()
+ }
+
+ test.describe('GFS per-agent native Copy and immediate grant enforcement (issue #797)', () => {
+ test.describe.configure({ mode: 'serial' })
+ let fixtures: AgentGfsCopyFixtures
+
+ test.beforeAll(() => {
+ assertGfsInfraHealthy()
+ fixtures = seedAgentGfsCopyFixtures(OWNER_EMAIL)
+ })
+
+ test.afterAll(() => fixtures?.cleanup())
+
+ test('copies complete trees and revokes destination access in one runtime', async ({}, testInfo) => {
+ // Four real LLM turns (each allowed RESPONSE_TIMEOUT_MS) plus Electron
+ // login and two Files-tree walks cannot fit the 240s config default.
+ testInfo.setTimeout(1_200_000)
+ const sourceBefore = getGfsTreeSnapshot(fixtures.tree.sourceResourceId)
+ const sourceAclShareBefore = getGfsTreeAclShareRows(fixtures.tree.sourceResourceId)
+ const sourceAclShareRecords = sourceAclShareBefore.map(
+ row => JSON.parse(row) as { kind: 'grant' | 'share'; row: Record<string, unknown> }
+ )
+ expect(
+ sourceAclShareRecords.filter(
+ record =>
+ record.kind === 'share' &&
+ record.row.id === fixtures.sourceShareId &&
+ record.row.subject_id === fixtures.sourceShareSubjectId
+ )
+ ).toHaveLength(1)
+ expect(
+ sourceAclShareRecords.filter(
- record =>
- record.kind === 'grant' && record.row.subject_id === fixtures.sourceShareSubjectId
++ record => record.kind === 'grant' && record.row.subject_id === fixtures.sourceShareSubjectId
+ )
+ ).toHaveLength(0)
- expect(getGfsTreeAclShareCounts(fixtures.tree.sourceResourceId).shares).toBeGreaterThanOrEqual(1)
++ expect(getGfsTreeAclShareCounts(fixtures.tree.sourceResourceId).shares).toBeGreaterThanOrEqual(
++ 1
++ )
+ const { app, page } = await launchAndLogin(OWNER_EMAIL)
+ try {
+ await test.step('Agent A copies one file through the native tool', async () => {
+ await browseSourceTree(page, fixtures)
+ await openExactAgent(page, fixtures.agentA.name)
+ const steps = await sendAgentTurn(
+ page,
+ `In drive main, open the folder named "${fixtures.tree.sourceName}" and read the file ` +
+ `"${fixtures.tree.standaloneFileName}" inside it. Then copy that file into the folder ` +
+ `named "${fixtures.tree.destinationName}", naming the copy "${fixtures.fileCopyName}". ` +
+ `Use only your native Clerum GFS tools; never download and re-upload content yourself.`
+ )
+ await expectToolSuccess(steps, 'gfs_read')
+ await expectToolSuccess(steps, 'gfs_copy')
+ await expectCopyPublicOutput(steps)
+ const copied = getGfsChildResourceSummary({
+ parentResourceId: fixtures.tree.destinationResourceId,
+ name: fixtures.fileCopyName,
+ })
+ expect(copied).not.toBeNull()
+ expect(copied?.resourceId).not.toBe(fixtures.tree.standaloneFileResourceId)
+ const copiedTree = getGfsTreeSnapshot(copied!.resourceId)
- const sourceFile = sourceBefore.find(node => node.resourceId === fixtures.tree.standaloneFileResourceId)
++ const sourceFile = sourceBefore.find(
++ node => node.resourceId === fixtures.tree.standaloneFileResourceId
++ )
+ expect(comparableTree(copiedTree)).toEqual([
- { relativePath: '.', kind: 'file', bytes: sourceFile!.bytes, content: sourceFile!.content },
++ {
++ relativePath: '.',
++ kind: 'file',
++ bytes: sourceFile!.bytes,
++ content: sourceFile!.content,
++ },
+ ])
+ expect(getGfsTreeAclShareRows(fixtures.tree.sourceResourceId)).toEqual(sourceAclShareBefore)
+ expect(getGfsTreeAclShareCounts(copied!.resourceId)).toEqual({ grants: 0, shares: 0 })
+ })
+
+ await test.step('Agent A recursively copies the complete folder', async () => {
+ const steps = await sendAgentTurn(
+ page,
+ `Now copy the complete folder named "${fixtures.tree.sourceName}" from drive main into ` +
+ `the folder named "${fixtures.tree.destinationName}", naming the copy ` +
+ `"${fixtures.folderCopyName}". Make exactly one copy; do not move or delete anything.`
+ )
+ await expectToolSuccess(steps, 'gfs_copy')
+ await expectCopyPublicOutput(steps)
+ })
+
+ await test.step('Agent A renames the copied root and reads it back', async () => {
+ // A separate short turn keeps the user intent unambiguous: renaming
+ // must never be "helpfully" followed by a fresh copy of the old name.
+ const steps = await sendAgentTurn(
+ page,
+ `Rename the copy named "${fixtures.folderCopyName}" (inside ` +
+ `"${fixtures.tree.destinationName}") to "${fixtures.renamedFolderName}". Then list ` +
+ `that renamed folder recursively and read every file inside it. Do not copy, move, ` +
+ `or delete anything.`
+ )
+ await expectToolSuccess(steps, 'gfs_rename')
+ await expectToolSuccess(steps, 'gfs_list')
+ await expectToolSuccess(steps, 'gfs_read')
+ })
+
+ await test.step('visible browse and persisted tree prove Copy did real work', async () => {
+ const copied = getGfsChildResourceSummary({
+ parentResourceId: fixtures.tree.destinationResourceId,
+ name: fixtures.renamedFolderName,
+ })
+ expect(copied).not.toBeNull()
+ expect(
+ getGfsChildResourceSummary({
+ parentResourceId: fixtures.tree.destinationResourceId,
+ name: fixtures.folderCopyName,
+ })
+ ).toBeNull()
+ const copiedTree = getGfsTreeSnapshot(copied!.resourceId)
+ expect(comparableTree(copiedTree)).toEqual(comparableTree(sourceBefore))
+ for (const source of sourceBefore) {
+ expect(copiedTree.map(node => node.resourceId)).not.toContain(source.resourceId)
+ }
+ expect(getGfsTreeSnapshot(fixtures.tree.sourceResourceId)).toEqual(sourceBefore)
+ expect(getGfsTreeAclShareRows(fixtures.tree.sourceResourceId)).toEqual(sourceAclShareBefore)
+ expect(getGfsTreeAclShareCounts(copied!.resourceId)).toEqual({ grants: 0, shares: 0 })
+ await browseDestinationTree(page, fixtures)
+ })
+
+ await test.step('copying onto an existing name is a non-destructive conflict (no duplicate)', async () => {
+ // The file copy from the first step already put `fileCopyName` under the
+ // destination. Copying the same source file there under the same name
+ // must be refused (already_exists → gfsc 409), and — the load-bearing
+ // business signal — must leave exactly one live child with that name.
+ const beforeSummary = getGfsChildResourceSummary({
+ parentResourceId: fixtures.tree.destinationResourceId,
+ name: fixtures.fileCopyName,
+ })
+ expect(beforeSummary).not.toBeNull()
+ expect(
+ countGfsLiveChildrenByName({
+ parentResourceId: fixtures.tree.destinationResourceId,
+ name: fixtures.fileCopyName,
+ })
+ ).toBe(1)
+ // Fresh thread on purpose: A has no memory of the earlier copy, so it
+ // must actually re-attempt the copy by name and surface the tool's real
+ // result rather than answering "already done" from context.
+ await openExactAgent(page, fixtures.agentA.name)
+ const steps = await sendAgentTurn(
+ page,
+ `In drive main, copy the file "${fixtures.tree.standaloneFileName}" from the folder ` +
+ `"${fixtures.tree.sourceName}" into the folder "${fixtures.tree.destinationName}", ` +
+ `naming the copy "${fixtures.fileCopyName}". Use your native Clerum GFS copy tool and ` +
+ `report exactly what it returns. Attempt the copy even if a listing suggests the name ` +
+ `already exists — do not decline based on a prior listing — and do not rename, delete, ` +
+ `or overwrite anything.`
+ )
+ await expectToolConflict(steps, 'gfs_copy')
+ // The existing copy is untouched and NO duplicate row was created.
+ const afterSummary = getGfsChildResourceSummary({
+ parentResourceId: fixtures.tree.destinationResourceId,
+ name: fixtures.fileCopyName,
+ })
+ expect(afterSummary?.resourceId).toBe(beforeSummary?.resourceId)
+ expect(
+ countGfsLiveChildrenByName({
+ parentResourceId: fixtures.tree.destinationResourceId,
+ name: fixtures.fileCopyName,
+ })
+ ).toBe(1)
+ })
+
+ await test.step('Agent B passes root/destination grants but unreadable child denies the tree', async () => {
+ await openExactAgent(page, fixtures.agentB.name)
+ const steps = await sendAgentTurn(
+ page,
+ `Copy the folder named "${fixtures.tree.sourceName}" from drive main into the folder ` +
+ `named "${fixtures.tree.destinationName}", naming the copy "${fixtures.deniedCopyName}". ` +
+ `Attempt the copy with your native Clerum GFS copy tool and report exactly what it ` +
+ `returns — do not decline based on a prior listing, even if it looks like you lack access.`
+ )
+ await expectToolForbidden(steps, 'gfs_copy')
+ expect(
+ getGfsChildResourceSummary({
+ parentResourceId: fixtures.tree.destinationResourceId,
+ name: fixtures.deniedCopyName,
+ })
+ ).toBeNull()
+ })
+
+ await test.step('audited revoke denies Agent A immediately in the same runtime', async () => {
+ await openExactAgent(page, fixtures.agentA.name, { reuseThread: true })
+ const runtimeBefore = getManagedAgentPodIdentity(fixtures.agentA)
+ const auditBefore = gfsGrantRevokeAuditCount(fixtures.agentA)
+ await revokeGfsGrantViaControlApi(fixtures.destinationGrantId)
+ expect(gfsGrantRevokeAuditCount(fixtures.agentA)).toBe(auditBefore + 1)
+ const steps = await sendAgentTurn(
+ page,
+ `Copy the folder "${fixtures.tree.sourceName}" into the folder ` +
+ `"${fixtures.tree.destinationName}", naming the copy ` +
+ `"${fixtures.revokedCopyName}". Attempt the copy with your native Clerum GFS copy ` +
+ `tool and report exactly what it returns — do not decline based on a prior listing, ` +
+ `even if it looks like you lack access.`
+ )
+ // Under name driving, revoking the destination removes even its
+ // resolvability (no-disclosure): the visible denial surfaces on the
+ // agent's own discovery tool (gfsc 403/404) BEFORE any gfs_copy can be
+ // issued. Require a gfsc-denied tool row, forbid any successful
+ // gfs_copy, and keep the infra-shape negatives.
+ const deniedGfsRow = steps
+ .locator('.stepper-step-duration.state-error')
+ .filter({ hasText: /gfsc 40[34]/ })
+ await expect(deniedGfsRow.first()).toBeVisible({ timeout: 15_000 })
+ const successfulCopy = steps
+ .locator('.stepper-step')
+ .filter({ has: page.locator('.stepper-step-fn', { hasText: 'gfs_copy' }) })
+ .filter({ hasNot: page.locator('.stepper-step-duration.state-error') })
+ await expect(successfulCopy).toHaveCount(0)
+ await expect(steps).not.toContainText(/gfsc 503|not_mounted/i)
+ await expect(steps).not.toContainText(SENSITIVE_OUTPUT)
+ // Same-runtime proof: the denial must come from live cache
+ // invalidation, not from a pod restart re-reading grants.
+ expect(getManagedAgentPodIdentity(fixtures.agentA)).toBe(runtimeBefore)
+ expect(
+ getGfsChildResourceSummary({
+ parentResourceId: fixtures.tree.destinationResourceId,
+ name: fixtures.revokedCopyName,
+ })
+ ).toBeNull()
+ })
+
+ expect(getGfsTreeSnapshot(fixtures.tree.sourceResourceId)).toEqual(sourceBefore)
+ } finally {
+ await app.close()
+ }
+ })
+ })
diff --cc desktop-app/test/e2e-playwright/gfs-agent-delegation.test.ts
index 000000000,612401489..951290afe
mode 000000,100644..100644
--- a/desktop-app/test/e2e-playwright/gfs-agent-delegation.test.ts
+++ b/desktop-app/test/e2e-playwright/gfs-agent-delegation.test.ts
@@@ -1,0 -1,798 +1,813 @@@
+ /**
+ * E2E — Desktop per-agent GFS delegation (plan "compressed-drifting-matsumoto",
+ * ADDENDUM 1): full pre/post permission sequence with TWO agents.
+ *
+ * One serial suite, two serial tests sharing beforeAll fixtures:
+ *
+ * Test 1 — "agents have no access until granted; grant gives A read AND write":
+ * 1. Pre-grant negative (chat): A, then B, asked to read the file by its
+ * visible path → no-disclosure denial for BOTH (zero successful gfs_read,
+ * no sentinel leak, no gfsc 503/not_mounted).
+ * 2. Grant via UI: Files → Options for <folder> → Manage → Agents section →
+ * select A only → read+write, inherit ON → Grant. Toast + gfs_grants row
+ * (host subject = A, permissions read/write, inherit true) via SQL helper.
+ * 3. Chat A read: sentinel content surfaces from the real PVC.
+ * 4. Chat A write: A replaces the file content (its own tools discover
+ * If-Match); new content + bumped version asserted in DB and on the PVC.
+ * 5. Isolation: B (stateless — exercises the wake path) still denied.
+ *
+ * Test 2 — "stateless agent grant + revoke keeps agents isolated":
+ * 1. Grant B via UI: second Manage round → select B → read → Grant; row
+ * asserted in DB.
+ * 2. Chat B read: B reads the MODIFIED sentinel (stateless runtime + fresh
+ * grant proven together).
+ * 3. Revoke A via UI: Manage → grants list → Revoke on A's row. Toast + row
+ * deleted + gfsGrantRevokeAuditCount +1.
+ * 4. Same-runtime denial for A: retry in A's existing thread is denied with
+ * NO content disclosure (no successful gfs_read, no sentinel, no infra-
+ * shape leak — per the name/path indistinguishability contract; a bare
+ * 403/404 code is intentionally NOT asserted) and pod UID/startTime
+ * invariance (no restart).
+ * 5. B unaffected: B reads again — revocation is isolated in both directions.
+ *
+ * E2E contract (e2e-test-guardian / human-driving):
+ * - Prompts and UI driving reference ONLY visible names and paths; business
+ * truth is always asserted from the database and the PVC via the shared
+ * SQL/kubectl helpers. No fixture helper performs the grant/revoke under
+ * test — those happen exclusively through the Manage modal UI.
+ * - Infra guard: gfsc unhealthy ⇒ the suite THROWS (never skips, never mocks).
+ */
+ import { type Locator, type Page, expect, test } from '@playwright/test'
++import { getGfsHostGrantsUnderTree } from '../../../tests/e2e/gfsCopyFixtures'
++import {
++ type GfsFileFixture,
++ cleanupGfsFixture,
++ getE2EUserId,
++ seedGfsFileFixture,
++ seedGfsGrant,
++ uniqueGfsFixtureName,
++} from '../../../tests/e2e/gfsUiFixtures'
+ import { exactNameFilter } from './helpers/agentLocators'
+ import { getManagedAgentPodIdentity } from './helpers/gfsAgentDiscovery'
+ import {
+ type ManagedGfsAgent,
+ assertGfsInfraHealthy,
+ discoverManagedGfsAgents,
+ getGfsTreeSnapshot,
+ gfsGrantRevokeAuditCount,
+ } from './helpers/gfsFixtures'
-import {
- type GfsFileFixture,
- cleanupGfsFixture,
- getE2EUserId,
- seedGfsFileFixture,
- seedGfsGrant,
- uniqueGfsFixtureName,
-} from '../../../tests/e2e/gfsUiFixtures'
-import { getGfsHostGrantsUnderTree } from '../../../tests/e2e/gfsCopyFixtures'
+ import { openAgentsPage, openResourcesNavItem } from './navigationHelpers'
+ import { launchAndLogin } from './workflowUi'
+
+ const OWNER_EMAIL = '[email protected]'
+ // glm-5.1 calibration (repo baseline): single agent turns can take minutes;
+ // multi-tool turns (discover + read/write) share the 300s budget proven by the
+ // issue #797 copy suite.
+ const RESPONSE_TIMEOUT_MS = 300_000
+ const SENSITIVE_OUTPUT =
+ /\/data\/gfs|\/mnt\/|\.generations|blob_key|blobKey|\bSQL\b|internal (?:path|error)|stack trace/i
+
+ interface AgentGfsDelegationFixtures {
+ /** Stateful journey agent (grantee of read+write, later revoked). */
+ agentA: ManagedGfsAgent
+ /** Stateless journey agent (wake path; read-only grantee, never revoked). */
+ agentB: ManagedGfsAgent
+ /** Seeded folder + file; the file carries the run-unique original sentinel. */
+ folder: GfsFileFixture
+ /** Exact content sentinel seeded into the file (PVC truth). */
+ originalSentinel: string
+ /** Exact replacement sentinel Agent A is asked to write in Test 1. */
+ modifiedSentinel: string
+ cleanup(): void
+ }
+
+ /**
+ * Named setup preconditions ONLY (performed outside the journeys under test):
+ * a folder+file the OWNER can see and manage. The owner grant carries
+ * read+write (escalation guard: you can only grant bits you hold) and
+ * manage_acl (Manage-modal delegation affordance + grants GET). NO host grant
+ * is seeded — creating and revoking those is exactly what the UI journeys
+ * must do themselves.
+ */
+ function seedAgentGfsDelegationFixtures(ownerEmail: string): AgentGfsDelegationFixtures {
+ const [agentA, agentB] = discoverManagedGfsAgents()
+ const folder = seedGfsFileFixture(uniqueGfsFixtureName('e2e-gfs-agent-delegation'))
+ try {
+ seedGfsGrant({
+ resourceId: folder.resourceId,
+ subjectType: 'user',
+ subjectId: getE2EUserId(ownerEmail),
+ permissions: ['read', 'write', 'manage_acl'],
+ inherit: true,
+ grantedBy: 'e2e:gfs-agent-delegation-owner',
+ })
+ for (const agent of [agentA, agentB]) {
+ if (getGfsHostGrantsUnderTree(folder.resourceId, agent.subjectId).length !== 0) {
+ throw new Error(
+ `delegation fixture must start with ZERO host grants for ${agent.subjectId} — ` +
+ 'the pre-grant denial phase would be meaningless'
+ )
+ }
+ }
+ return {
+ agentA,
+ agentB,
+ folder,
+ originalSentinel: `E2E GFS file fixture: ${folder.name}`,
+ modifiedSentinel: `Delegated write sentinel ${folder.name} rewritten by the granted agent`,
+ cleanup: () => cleanupGfsFixture(folder.name),
+ }
+ } catch (error) {
+ try {
+ cleanupGfsFixture(folder.name)
+ } catch (cleanupError) {
+ throw new Error(
+ `GFS delegation setup failed (${String(error)}) and cleanup failed (${String(cleanupError)})`
+ )
+ }
+ throw error
+ }
+ }
+
+ async function openExactAgent(
+ page: Page,
+ agentName: string,
+ opts: { reuseThread?: boolean } = {}
+ ): Promise<void> {
+ await openAgentsPage(page)
+ await expect(page.getByRole('heading', { name: 'Agents', exact: true })).toBeVisible()
+ const row = page.getByLabel(`Open details for ${agentName}`, { exact: true })
+ await expect(row).toBeVisible({ timeout: 30_000 })
+ await row.click()
+ await expect(page.getByText(agentName, { exact: true }).first()).toBeVisible({ timeout: 15_000 })
+ await page.getByTestId('nav-chat').click()
+ await expect(page.getByTestId('chat-input')).toBeVisible({ timeout: 30_000 })
+ // Starting a new chat can reset the composer to the DEFAULT agent, so it
+ // must happen BEFORE the agent switch — never after, or the turn silently
+ // goes to the wrong agent.
+ if (!opts.reuseThread) {
+ const fresh = page.getByRole('button', { name: /new (?:chat|thread)/i }).first()
+ if (await fresh.isVisible().catch(() => false)) await fresh.click()
+ }
+ // The product binds the composer to an agent ONLY through the chat view's
+ // "Switch chat agent" selector — opening another agent's details page
+ // deliberately does not switch the chat. Drive exactly that user flow.
+ const switcher = page.getByRole('button', { name: 'Switch chat agent' })
+ const boundSwitcher = switcher.filter(exactNameFilter(agentName))
+ const breadcrumb = page
+ .getByRole('navigation', { name: 'Chat breadcrumb' })
+ .getByText(agentName, { exact: true })
- if (!(await boundSwitcher.or(breadcrumb).first().isVisible().catch(() => false))) {
++ if (
++ !(await boundSwitcher
++ .or(breadcrumb)
++ .first()
++ .isVisible()
++ .catch(() => false))
++ ) {
+ await switcher.first().click()
+ await page.getByRole('menuitem', { name: agentName, exact: true }).click()
+ }
+ // A stateless agent suspended at idle wakes through the rpc-proxy
+ // wake-and-hold path (up to ~90s of scale-up) before its chat shell binds;
+ // the binding element itself remains mandatory and is the LAST gate before
+ // any turn is sent.
+ await expect(boundSwitcher.or(breadcrumb).first()).toBeVisible({ timeout: 120_000 })
+ if (opts.reuseThread) {
+ // The revocation retry deliberately continues the agent's most recent
+ // session: the user only repeats visible paths, and any resource
+ // identifiers live in the agent's own conversational memory from its
+ // previous discovery.
+ await page.locator('.agent-dedicated-session-title-btn').first().click()
+ await expect(page.getByTestId('agent-response').first()).toBeVisible({ timeout: 15_000 })
+ } else {
+ await expect(page.getByTestId('agent-response')).toHaveCount(0, { timeout: 10_000 })
+ }
+ }
+
+ async function sendAgentTurn(
+ page: Page,
+ prompt: string
+ ): Promise<{ stepper: Locator; responseText: string }> {
+ const responseIndex = await page.getByTestId('agent-response').count()
+ const approvalIndex = await page.getByTestId('approval-approve-btn').count()
+ const progressIndex = await page.getByTestId('progress-expand-btn').count()
+ await expect(page.getByTestId('chat-input')).toBeEnabled()
+ await page.getByTestId('chat-input').fill(prompt)
+ await page.getByTestId('send-button').click()
+
+ const response = page.getByTestId('agent-response').nth(responseIndex)
+ const retrySend = page.getByRole('button', { name: 'Retry last send' })
+ let approvals = 0
+ let sendRetries = 0
+ const deadline = Date.now() + RESPONSE_TIMEOUT_MS
+ for (;;) {
+ const remaining = deadline - Date.now()
+ if (remaining <= 0) throw new Error('timed out waiting for the delegation-suite agent turn')
+ // A just-restarted runtime can drop the send with a visible "Temporary
+ // connection issue" banner; a real user presses the product's own
+ // "Retry last send". Bounded — a persistent failure still fails the turn.
+ if (await retrySend.isVisible().catch(() => false)) {
+ if (sendRetries >= 3) throw new Error('agent send kept failing after 3 product retries')
+ sendRetries += 1
+ // An absorbed retry must be LOUD in a green run: warn on the console
+ // and annotate the test report, without changing pass/fail semantics.
+ const turnLabel = prompt.slice(0, 80)
+ console.warn(
+ `[gfs-agent-delegation] "Retry last send" pressed (attempt ${sendRetries}/3) for turn: ${turnLabel}`
+ )
+ test.info().annotations.push({
+ type: 'retry-last-send',
+ description: `attempt ${sendRetries}/3 for turn: ${turnLabel}`,
+ })
+ await retrySend.click()
+ continue
+ }
+ const approval = page.getByTestId('approval-approve-btn').nth(approvalIndex + approvals)
+ const approvalWait = approval
+ .waitFor({ state: 'visible', timeout: Math.min(remaining, 10_000) })
+ .then(() => 'approval' as const)
+ const responseWait = response
+ .waitFor({ state: 'visible', timeout: Math.min(remaining, 10_000) })
+ .then(() => 'response' as const)
+ // The losing waitFor keeps its timer; silence its eventual rejection so a
+ // settled turn cannot surface a late "Target closed" unhandled rejection.
+ // .catch() returns a NEW promise, so the originals still race unchanged.
+ void approvalWait.catch(() => undefined)
+ void responseWait.catch(() => undefined)
+ let visible: 'approval' | 'response'
+ try {
+ visible = await Promise.race([approvalWait, responseWait])
+ } catch {
+ // Neither appeared within this slice; loop to re-check the retry banner
+ // and the overall deadline.
+ continue
+ }
+ if (visible === 'response') break
+ await approval.click()
+ approvals += 1
+ }
+ await expect(response).toBeVisible({ timeout: RESPONSE_TIMEOUT_MS })
+ const responseText = (await response.textContent()) ?? ''
+ const expand = page.getByTestId('progress-expand-btn').nth(progressIndex)
+ await expect(expand).toBeVisible({ timeout: 30_000 })
+ await expand.click()
+ return { stepper: expand.locator('..'), responseText }
+ }
+
+ function toolRow(stepper: Locator, name: string): Locator {
+ return stepper.locator('.stepper-step').filter({ hasText: name }).last()
+ }
+
+ async function expectToolSuccess(stepper: Locator, name: string): Promise<void> {
+ const row = toolRow(stepper, name)
+ await expect(row).toBeVisible({ timeout: 15_000 })
+ await expect(row.locator('.stepper-step-fn')).toContainText(name)
+ await expect(row.locator('.stepper-step-duration.state-error')).toHaveCount(0)
+ }
+
+ /**
+ * The step-output panel renders the head of the tool result payload — the
+ * run-unique sentinel can only be there if gfsc actually served the file
+ * content from the real PVC. The OutputPanel is a SIBLING of the step row, so
+ * row→panel binds via following-sibling.
+ */
+ async function expectReadWithSentinel(stepper: Locator, sentinel: string): Promise<void> {
+ await expectToolSuccess(stepper, 'gfs_read')
+ const row = toolRow(stepper, 'gfs_read')
+ await row.click()
+ const output = row
+ .locator('xpath=following-sibling::*[@data-testid="step-output-panel"][1]')
+ .locator('.stepper-step-output-code')
+ await expect(output).toBeVisible({ timeout: 10_000 })
+ await expect(output).toContainText(sentinel)
+ await expect(output).not.toContainText(SENSITIVE_OUTPUT)
+ }
+
+ function assertNoInfraFailureShape(responseText: string): void {
+ // Credential repair must be distinguishable from resource authorization: a
+ // not_mounted/503 here means the permission store broke (issue #775 shape),
+ // which must NEVER read as a denial pass.
+ expect(responseText.toLowerCase()).not.toContain('not_mounted')
+ expect(responseText.toLowerCase()).not.toContain('gfsc 503')
+ expect(responseText.toLowerCase()).not.toContain('fetch failed')
+ }
+
+ /**
+ * No-disclosure denial contract for NAME/PATH driving (pattern from
+ * gfs-agent-file-read.test.ts): an ungranted agent cannot even resolve the
+ * resource, so a denied file is deliberately indistinguishable from an absent
+ * one. The contract is: the agent really attempted its gfs tools, NO gfs_read
+ * ever succeeded, nothing leaked the sentinel content, and no infra
+ * 503/not_mounted shape appeared.
+ */
+ async function expectNoDisclosureDenial(
+ turn: { stepper: Locator; responseText: string },
+ forbiddenSentinels: string[]
+ ): Promise<void> {
+ const page = turn.stepper.page()
+ assertNoInfraFailureShape(turn.responseText)
+ for (const sentinel of forbiddenSentinels) {
+ expect(turn.responseText).not.toContain(sentinel)
+ }
+ const gfsSteps = turn.stepper
+ .locator('.stepper-step')
+ .filter({ has: page.locator('.stepper-step-fn', { hasText: /gfs_/ }) })
+ await expect(gfsSteps.first()).toBeVisible({ timeout: 15_000 })
+ const successfulRead = turn.stepper
+ .locator('.stepper-step')
+ .filter({ has: page.locator('.stepper-step-fn', { hasText: 'gfs_read' }) })
+ .filter({ hasNot: page.locator('.stepper-step-duration.state-error') })
+ await expect(successfulRead).toHaveCount(0)
+ await expect(turn.stepper).not.toContainText(/gfsc 503|not_mounted/i)
+ await expect(turn.stepper).not.toContainText(SENSITIVE_OUTPUT)
+ for (const sentinel of forbiddenSentinels) {
+ await expect(turn.stepper).not.toContainText(sentinel)
+ }
+ }
+
+ async function openFilesBrowser(page: Page): Promise<Locator> {
+ await openResourcesNavItem(page, 'nav-files')
+ const browser = page.getByRole('region', { name: 'Global File System browser' })
+ await expect(browser).toBeVisible({ timeout: 20_000 })
+ return browser
+ }
+
+ /**
+ * Enters the fixture folder (visible-path proof: the user sees the file they
+ * will later name to the agents) and opens the Manage dialog through the
+ * folder's own "Options for <folder>" menu.
+ */
+ async function openManageForFixtureFolder(
+ page: Page,
+ fixtures: AgentGfsDelegationFixtures
+ ): Promise<Locator> {
+ const browser = await openFilesBrowser(page)
+ await browser.getByRole('button', { name: fixtures.folder.name, exact: true }).click()
+ await expect(
+ browser.getByRole('button', { name: fixtures.folder.fileName, exact: true })
+ ).toBeVisible({ timeout: 20_000 })
- await browser.getByRole('button', { name: `Options for ${fixtures.folder.name}`, exact: true }).click()
++ await browser
++ .getByRole('button', { name: `Options for ${fixtures.folder.name}`, exact: true })
++ .click()
+ await browser.getByRole('menuitem', { name: 'Manage', exact: true }).click()
+ const dialog = page.getByRole('dialog', { name: `Manage folder ${fixtures.folder.name}` })
+ await expect(dialog).toBeVisible({ timeout: 15_000 })
+ return dialog
+ }
+
+ async function closeManageDialog(page: Page, dialog: Locator): Promise<void> {
+ await dialog.getByRole('button', { name: 'Close manage dialog', exact: true }).click()
+ await expect(page.getByRole('dialog', { name: /^Manage folder / })).toHaveCount(0)
+ }
+
+ /**
+ * Drives the Agents section of the Manage dialog exactly as a user would:
+ * select ONE agent by its visible name (asserting the other stays unselected),
+ * optionally add Write in the permission dropdown, keep the directory-default
+ * "Include contents of this folder" toggle ON, and press Grant. Success is a
+ * product toast plus the agent's row appearing in the "Who has access" list
+ * (list-after-write is mandatory: the grant PUT returns no ids).
+ */
+ async function grantAgentAccessViaManageModal(
+ page: Page,
+ dialog: Locator,
+ opts: { agentName: string; unselectedAgentName: string; includeWrite: boolean }
+ ): Promise<void> {
+ const agentSection = dialog.locator('.da-gfs-agent-access')
+ await expect(agentSection).toBeVisible({ timeout: 20_000 })
+ const agentGroup = agentSection.getByRole('group', { name: 'My agents' })
+ await expect(agentGroup).toBeVisible({ timeout: 20_000 })
+ const target = agentGroup.getByRole('button', { name: opts.agentName, exact: true })
+ const untouched = agentGroup.getByRole('button', { name: opts.unselectedAgentName, exact: true })
+ await expect(untouched).toBeVisible({ timeout: 20_000 })
+ await target.click()
+ await expect(target).toHaveAttribute('aria-pressed', 'true')
+ await expect(untouched).toHaveAttribute('aria-pressed', 'false')
+ if (opts.includeWrite) {
+ // The agent dropdown starts at the read-only default; add Write through
+ // the real menu (menuitemcheckbox), then close it by clicking the section
+ // heading so the Grant press cannot be swallowed by the click-outside
+ // handler.
+ await agentSection.getByRole('button', { name: 'Read', exact: true }).click()
+ const menu = agentSection.getByRole('menu', { name: 'Permissions' })
+ await expect(menu.getByRole('menuitemcheckbox', { name: 'Read' })).toHaveAttribute(
+ 'aria-checked',
+ 'true'
+ )
+ await menu.getByRole('menuitemcheckbox', { name: 'Write' }).click()
+ await expect(menu.getByRole('menuitemcheckbox', { name: 'Write' })).toHaveAttribute(
+ 'aria-checked',
+ 'true'
+ )
+ await agentSection.getByRole('heading', { name: 'Agents' }).click()
+ await expect(
+ agentSection.getByRole('button', { name: '2 permissions', exact: true })
+ ).toBeVisible()
+ } else {
+ await expect(agentSection.getByRole('button', { name: 'Read', exact: true })).toBeVisible()
+ }
+ const inherit = agentSection.getByRole('checkbox', { name: 'Include contents of this folder' })
+ // Directory default is ON — asserted, never toggled: a folder grant with
+ // inherit=false would silently break the agent-reads-file journey.
+ await expect(inherit).toBeChecked()
+ await agentSection.getByRole('button', { name: 'Grant agent access', exact: true }).click()
+ await expect(page.getByText('Access granted to 1 agent', { exact: true }).first()).toBeVisible({
+ timeout: 20_000,
+ })
+ await expect(
+ dialog.getByRole('button', { name: `Revoke access for ${opts.agentName}`, exact: true })
+ ).toBeVisible({ timeout: 20_000 })
+ }
+
+ /**
+ * Bulk multi-agent grant — the #159 feature under test (`subjects[]`). Selects
+ * EVERY named agent so they are all pressed SIMULTANEOUSLY before a single
+ * "Grant agent access" press, which the UI turns into ONE atomic
+ * `ctrl.grant(subjects[], bits, inherit)` PUT. The plural toast ("Access
+ * granted to N agents") is only emitted when the whole batch succeeds as a
+ * unit, and list-after-write must then show a Revoke row for every grantee
+ * (the grants GET returned all N). Read-only + directory-default inherit ON,
+ * asserted, never toggled. Cardinality ≥2 is the whole point: at N=1 this path
+ * is indistinguishable from the pre-#159 one-PUT-per-subject behaviour.
+ */
+ async function grantMultipleAgentsViaManageModal(
+ page: Page,
+ dialog: Locator,
+ opts: { agentNames: string[] }
+ ): Promise<void> {
+ if (opts.agentNames.length < 2) {
+ throw new Error('grantMultipleAgentsViaManageModal requires ≥2 agents to exercise subjects[]')
+ }
+ const agentSection = dialog.locator('.da-gfs-agent-access')
+ await expect(agentSection).toBeVisible({ timeout: 20_000 })
+ const agentGroup = agentSection.getByRole('group', { name: 'My agents' })
+ await expect(agentGroup).toBeVisible({ timeout: 20_000 })
+ // Select each agent; each toggle must stick without clearing the earlier ones.
+ for (const name of opts.agentNames) {
+ const target = agentGroup.getByRole('button', { name, exact: true })
+ await expect(target).toBeVisible({ timeout: 20_000 })
+ await target.click()
+ await expect(target).toHaveAttribute('aria-pressed', 'true')
+ }
+ // The load-bearing assertion for the bulk path: ALL selected agents remain
+ // pressed at the SAME time — that simultaneity is what makes the single Grant
+ // a subjects[] batch of N rather than N separate one-subject grants.
+ for (const name of opts.agentNames) {
+ await expect(agentGroup.getByRole('button', { name, exact: true })).toHaveAttribute(
+ 'aria-pressed',
+ 'true'
+ )
+ }
+ // Read-only default kept; directory inherit default ON, asserted not toggled.
+ await expect(agentSection.getByRole('button', { name: 'Read', exact: true })).toBeVisible()
+ await expect(
+ agentSection.getByRole('checkbox', { name: 'Include contents of this folder' })
+ ).toBeChecked()
+ // ONE press → one atomic PUT carrying subjects:[…N…].
+ await agentSection.getByRole('button', { name: 'Grant agent access', exact: true }).click()
+ // Plural toast proves the batch was accepted as a unit (singular would mean the
+ // multi-select collapsed to one subject — the exact regression this guards).
+ await expect(
- page
- .getByText(`Access granted to ${opts.agentNames.length} agents`, { exact: true })
- .first()
++ page.getByText(`Access granted to ${opts.agentNames.length} agents`, { exact: true }).first()
+ ).toBeVisible({ timeout: 20_000 })
+ // list-after-write: every grantee now has a Revoke row (grants GET returned all N).
+ for (const name of opts.agentNames) {
+ await expect(
+ dialog.getByRole('button', { name: `Revoke access for ${name}`, exact: true })
+ ).toBeVisible({ timeout: 20_000 })
+ }
+ }
+
+ test.describe('GFS per-agent delegation: UI grant/revoke with full pre/post enforcement (Addendum 1)', () => {
+ test.describe.configure({ mode: 'serial' })
+ let fixtures: AgentGfsDelegationFixtures
+
+ test.beforeAll(() => {
+ // Infra guard FIRST: a broken permission-store credential is a blocker to
+ // fix, never a reason to skip or mock (fail-loud rule).
+ assertGfsInfraHealthy()
+ fixtures = seedAgentGfsDelegationFixtures(OWNER_EMAIL)
+ })
+
+ test.afterAll(() => fixtures?.cleanup())
+
+ test('agents have no access until granted; UI grant gives Agent A read AND write', async ({}, testInfo) => {
+ // Four real LLM turns (each allowed RESPONSE_TIMEOUT_MS) plus Electron
+ // login, one stateless wake (≤120s binding), and the Manage-modal grant
+ // round cannot fit the 240s config default.
+ testInfo.setTimeout(1_500_000)
+ const filePath = `/${fixtures.folder.name}/${fixtures.folder.fileName}`
+ const fileBefore = getGfsTreeSnapshot(fixtures.folder.fileResourceId)
+ expect(fileBefore).toHaveLength(1)
+ expect(fileBefore[0]!.kind).toBe('file')
+ expect(fileBefore[0]!.content).toContain(fixtures.originalSentinel)
+ const { app, page } = await launchAndLogin(OWNER_EMAIL)
+ try {
+ await test.step('user sees the delegated folder and file in the Files page', async () => {
+ const browser = await openFilesBrowser(page)
+ await browser.getByRole('button', { name: fixtures.folder.name, exact: true }).click()
+ await expect(
+ browser.getByRole('button', { name: fixtures.folder.fileName, exact: true })
+ ).toBeVisible({ timeout: 20_000 })
+ })
+
+ await test.step('pre-grant: Agent A is denied without disclosure', async () => {
+ await openExactAgent(page, fixtures.agentA.name)
+ const turn = await sendAgentTurn(
+ page,
+ `Read the file at path "${filePath}" in GFS drive main and quote its contents ` +
+ 'verbatim. Do not answer from memory — attempt the read with your Clerum GFS tools ' +
+ 'even if the file is not in your listing.'
+ )
+ await expectNoDisclosureDenial(turn, [fixtures.originalSentinel])
+ })
+
+ await test.step('pre-grant: stateless Agent B is denied without disclosure', async () => {
+ await openExactAgent(page, fixtures.agentB.name)
+ const turn = await sendAgentTurn(
+ page,
+ `Read the file at path "${filePath}" in GFS drive main and quote its contents ` +
+ 'verbatim. Do not answer from memory — attempt the read with your Clerum GFS tools ' +
+ 'even if the file is not in your listing.'
+ )
+ await expectNoDisclosureDenial(turn, [fixtures.originalSentinel])
+ })
+
+ await test.step('UI grant: Agent A gets read+write with inherit ON', async () => {
+ const dialog = await openManageForFixtureFolder(page, fixtures)
+ await grantAgentAccessViaManageModal(page, dialog, {
+ agentName: fixtures.agentA.name,
+ unselectedAgentName: fixtures.agentB.name,
+ includeWrite: true,
+ })
+ await closeManageDialog(page, dialog)
+ // Business truth: exactly one host grant row for A on the folder,
+ // read+write, inherit true — and still none for B.
- const grantsA = getGfsHostGrantsUnderTree(fixtures.folder.resourceId, fixtures.agentA.subjectId)
++ const grantsA = getGfsHostGrantsUnderTree(
++ fixtures.folder.resourceId,
++ fixtures.agentA.subjectId
++ )
+ expect(grantsA).toHaveLength(1)
+ expect(grantsA[0]!.resourceId).toBe(fixtures.folder.resourceId)
+ expect([...grantsA[0]!.permissions].sort()).toEqual(['read', 'write'])
+ expect(grantsA[0]!.inherit).toBe(true)
+ expect(
+ getGfsHostGrantsUnderTree(fixtures.folder.resourceId, fixtures.agentB.subjectId)
+ ).toHaveLength(0)
+ })
+
+ await test.step('Agent A reads the sentinel through the real PVC', async () => {
+ await openExactAgent(page, fixtures.agentA.name)
+ const turn = await sendAgentTurn(
+ page,
+ `Read the file at path "${filePath}" in GFS drive main and quote its contents ` +
+ 'verbatim. Use your Clerum GFS tools; do not answer from memory.'
+ )
+ assertNoInfraFailureShape(turn.responseText)
+ await expectReadWithSentinel(turn.stepper, fixtures.originalSentinel)
+ })
+
+ await test.step('Agent A replaces the content; DB version bumps and the PVC serves it', async () => {
+ // Same thread as the read: the write is the natural follow-up turn.
+ const turn = await sendAgentTurn(
+ page,
+ `Now replace the ENTIRE contents of that same file ("${filePath}" in GFS drive main) ` +
+ `with exactly this single line of text: "${fixtures.modifiedSentinel}". Use only ` +
+ "your native Clerum GFS tools; if your write tool needs the file's current version, " +
+ 'discover it with your own GFS tools first. Do not create, copy, or delete anything.'
+ )
+ assertNoInfraFailureShape(turn.responseText)
+ await expectToolSuccess(turn.stepper, 'gfs_write')
+ const fileAfter = getGfsTreeSnapshot(fixtures.folder.fileResourceId)
+ expect(fileAfter).toHaveLength(1)
+ // DB truth: the version bumped and bytes match the stored blob.
+ expect(fileAfter[0]!.version).toBeGreaterThan(fileBefore[0]!.version)
+ expect(fileAfter[0]!.bytes).toBe(Buffer.byteLength(fileAfter[0]!.content ?? '', 'utf8'))
+ // PVC truth: the snapshot content is read via kubectl exec cat on the
+ // gfsc writer pod — the new sentinel must be served, the old one gone
+ // (a "helpful" append instead of a replace must fail here).
+ expect(fileAfter[0]!.content).toContain(fixtures.modifiedSentinel)
+ expect(fileAfter[0]!.content).not.toContain(fixtures.originalSentinel)
+ })
+
+ await test.step('isolation: stateless Agent B is STILL denied after A was granted', async () => {
+ await openExactAgent(page, fixtures.agentB.name)
+ const turn = await sendAgentTurn(
+ page,
+ `Read the file at path "${filePath}" in GFS drive main and quote its contents ` +
+ 'verbatim. Do not answer from memory — attempt the read with your Clerum GFS tools ' +
+ 'even if the file is not in your listing.'
+ )
+ await expectNoDisclosureDenial(turn, [fixtures.originalSentinel, fixtures.modifiedSentinel])
+ expect(
+ getGfsHostGrantsUnderTree(fixtures.folder.resourceId, fixtures.agentB.subjectId)
+ ).toHaveLength(0)
+ })
+ } finally {
+ await app.close()
+ }
+ })
+
+ test('stateless agent grant + UI revoke keeps agents isolated in the same runtime', async ({}, testInfo) => {
+ // Three real LLM turns plus two Manage-modal rounds, Electron login, and a
+ // possible stateless wake.
+ testInfo.setTimeout(1_200_000)
+ const filePath = `/${fixtures.folder.name}/${fixtures.folder.fileName}`
+ const { app, page } = await launchAndLogin(OWNER_EMAIL)
+ try {
+ await test.step('UI grant: Agent B gets read-only with inherit ON', async () => {
+ const dialog = await openManageForFixtureFolder(page, fixtures)
+ // Continuity from Test 1: A's grant row is still listed before B's
+ // grant is created.
+ await expect(
+ dialog.getByRole('button', {
+ name: `Revoke access for ${fixtures.agentA.name}`,
+ exact: true,
+ })
+ ).toBeVisible({ timeout: 20_000 })
+ await grantAgentAccessViaManageModal(page, dialog, {
+ agentName: fixtures.agentB.name,
+ unselectedAgentName: fixtures.agentA.name,
+ includeWrite: false,
+ })
+ await closeManageDialog(page, dialog)
- const grantsB = getGfsHostGrantsUnderTree(fixtures.folder.resourceId, fixtures.agentB.subjectId)
++ const grantsB = getGfsHostGrantsUnderTree(
++ fixtures.folder.resourceId,
++ fixtures.agentB.subjectId
++ )
+ expect(grantsB).toHaveLength(1)
+ expect(grantsB[0]!.resourceId).toBe(fixtures.folder.resourceId)
+ expect(grantsB[0]!.permissions).toEqual(['read'])
+ expect(grantsB[0]!.inherit).toBe(true)
+ // A's Test-1 grant is untouched by B's grant.
- const grantsA = getGfsHostGrantsUnderTree(fixtures.folder.resourceId, fixtures.agentA.subjectId)
++ const grantsA = getGfsHostGrantsUnderTree(
++ fixtures.folder.resourceId,
++ fixtures.agentA.subjectId
++ )
+ expect(grantsA).toHaveLength(1)
+ expect([...grantsA[0]!.permissions].sort()).toEqual(['read', 'write'])
+ })
+
+ await test.step('stateless Agent B reads the MODIFIED sentinel (wake + fresh grant)', async () => {
+ await openExactAgent(page, fixtures.agentB.name)
+ const turn = await sendAgentTurn(
+ page,
+ `Read the file at path "${filePath}" in GFS drive main and quote its contents ` +
+ 'verbatim. Use your Clerum GFS tools; do not answer from memory.'
+ )
+ assertNoInfraFailureShape(turn.responseText)
+ await expectReadWithSentinel(turn.stepper, fixtures.modifiedSentinel)
+ })
+
+ let runtimeBefore = ''
+ await test.step('UI revoke: Agent A is removed from the grants list, audited', async () => {
+ // Capture A's live pod identity BEFORE the revoke: the later denial
+ // must come from live cache invalidation, not a restart.
+ runtimeBefore = getManagedAgentPodIdentity(fixtures.agentA)
+ const auditBefore = gfsGrantRevokeAuditCount(fixtures.agentA)
+ const dialog = await openManageForFixtureFolder(page, fixtures)
+ const revokeA = dialog.getByRole('button', {
+ name: `Revoke access for ${fixtures.agentA.name}`,
+ exact: true,
+ })
+ await expect(revokeA).toBeVisible({ timeout: 20_000 })
+ await revokeA.click()
+ await expect(
+ page.getByText(`Access revoked for ${fixtures.agentA.name}`, { exact: true }).first()
+ ).toBeVisible({ timeout: 20_000 })
+ await expect(
+ dialog.getByRole('button', {
+ name: `Revoke access for ${fixtures.agentA.name}`,
+ exact: true,
+ })
+ ).toHaveCount(0, { timeout: 20_000 })
+ // B's row survives A's revocation.
+ await expect(
+ dialog.getByRole('button', {
+ name: `Revoke access for ${fixtures.agentB.name}`,
+ exact: true,
+ })
+ ).toBeVisible({ timeout: 20_000 })
+ await closeManageDialog(page, dialog)
+ expect(
+ getGfsHostGrantsUnderTree(fixtures.folder.resourceId, fixtures.agentA.subjectId)
+ ).toHaveLength(0)
+ expect(gfsGrantRevokeAuditCount(fixtures.agentA)).toBe(auditBefore + 1)
+ })
+
+ await test.step('Agent A is denied in the SAME runtime (no pod restart)', async () => {
+ // A FRESH thread is deliberate: reusing A's earlier thread would let it
+ // quote the file straight from conversational memory (it legitimately
+ // read+wrote the content while granted), which proves nothing about the
+ // revocation. Driving by name in a clean thread forces a real re-access
+ // through gfsc, which now denies it. Revocation blocks FUTURE access; it
+ // does not erase context the agent already holds.
+ await openExactAgent(page, fixtures.agentA.name)
+ const turn = await sendAgentTurn(
+ page,
+ `Read the file at path "${filePath}" in GFS drive main and quote its contents ` +
+ 'verbatim. Do not answer from memory — attempt the read with your Clerum GFS ' +
+ 'tools even if the file is not in your listing.'
+ )
- await expectNoDisclosureDenial(turn, [
- fixtures.originalSentinel,
- fixtures.modifiedSentinel,
- ])
++ await expectNoDisclosureDenial(turn, [fixtures.originalSentinel, fixtures.modifiedSentinel])
+ // Same-runtime proof: pod UID + startTime are unchanged across the
+ // revoke and the denied retry — live cache invalidation, not a restart.
+ expect(getManagedAgentPodIdentity(fixtures.agentA)).toBe(runtimeBefore)
+ })
+
+ await test.step('Agent B still reads fine — revocation is isolated per agent', async () => {
+ await openExactAgent(page, fixtures.agentB.name)
+ const turn = await sendAgentTurn(
+ page,
+ `Read the file at path "${filePath}" in GFS drive main one more time and quote its ` +
+ 'contents verbatim. Use your Clerum GFS tools; do not answer from memory.'
+ )
+ assertNoInfraFailureShape(turn.responseText)
+ await expectReadWithSentinel(turn.stepper, fixtures.modifiedSentinel)
- const grantsB = getGfsHostGrantsUnderTree(fixtures.folder.resourceId, fixtures.agentB.subjectId)
++ const grantsB = getGfsHostGrantsUnderTree(
++ fixtures.folder.resourceId,
++ fixtures.agentB.subjectId
++ )
+ expect(grantsB).toHaveLength(1)
+ expect(grantsB[0]!.permissions).toEqual(['read'])
+ })
+ } finally {
+ await app.close()
+ }
+ })
+ })
+
+ /**
+ * E2E — the #159 headline capability the journey above never exercises: an
+ * ATOMIC bulk grant to MULTIPLE agents in one request (`subjects[]`). The
+ * pre/post journey grants one agent at a time (cardinality 1), which is
+ * behaviourally identical to the pre-#159 one-PUT-per-subject path; a broken
+ * bulk aggregation would still let it pass. This suite drives the real
+ * multi-select UI (≥2 agents pressed simultaneously) into a single Grant and
+ * asserts business-truth from the database: exactly one read grant row per
+ * agent, both produced by the one action.
+ */
+ test.describe('GFS per-agent delegation: atomic bulk grant to multiple agents (#159 subjects[])', () => {
+ test.describe.configure({ mode: 'serial' })
+ let fixtures: AgentGfsDelegationFixtures
+
+ test.beforeAll(() => {
+ // Fail-loud infra guard first, then a FRESH folder (its own uniqueGfsFixture
+ // name) with zero host grants so the bulk grant's DB truth is unambiguous.
+ assertGfsInfraHealthy()
+ fixtures = seedAgentGfsDelegationFixtures(OWNER_EMAIL)
+ })
+
+ test.afterAll(() => fixtures?.cleanup())
+
+ test('one Grant action delegates read to BOTH agents in a single atomic request', async ({}, testInfo) => {
+ // No LLM turns — Electron login + one Manage-modal round only. The business
+ // signal is the two host-grant rows, not any agent chat (agent read/write
+ // through a grant is already proven by the pre/post journey above).
+ testInfo.setTimeout(600_000)
+ // Precondition truth: neither agent holds a grant on the fresh folder, so
+ // the two rows asserted afterwards can only come from the bulk action.
+ expect(
+ getGfsHostGrantsUnderTree(fixtures.folder.resourceId, fixtures.agentA.subjectId)
+ ).toHaveLength(0)
+ expect(
+ getGfsHostGrantsUnderTree(fixtures.folder.resourceId, fixtures.agentB.subjectId)
+ ).toHaveLength(0)
+ const { app, page } = await launchAndLogin(OWNER_EMAIL)
+ try {
+ await test.step('bulk grant: select BOTH agents, press Grant exactly once', async () => {
+ const dialog = await openManageForFixtureFolder(page, fixtures)
+ await grantMultipleAgentsViaManageModal(page, dialog, {
+ agentNames: [fixtures.agentA.name, fixtures.agentB.name],
+ })
+ await closeManageDialog(page, dialog)
+ })
+
+ await test.step('business truth: one read grant per agent from the single request', async () => {
+ // The atomic subjects:[A,B] PUT must have produced EXACTLY one host grant
+ // row for EACH agent — read-only, inherit true, on the fixture folder. If
+ // the bulk collapsed to the first subject, agent B would have zero rows
+ // here and this fails; if it silently escalated the cap, permissions
+ // would not equal ['read'].
+ const grantsA = getGfsHostGrantsUnderTree(
+ fixtures.folder.resourceId,
+ fixtures.agentA.subjectId
+ )
+ const grantsB = getGfsHostGrantsUnderTree(
+ fixtures.folder.resourceId,
+ fixtures.agentB.subjectId
+ )
+ expect(grantsA).toHaveLength(1)
+ expect(grantsB).toHaveLength(1)
+ expect(grantsA[0]!.resourceId).toBe(fixtures.folder.resourceId)
+ expect(grantsB[0]!.resourceId).toBe(fixtures.folder.resourceId)
+ expect(grantsA[0]!.permissions).toEqual(['read'])
+ expect(grantsB[0]!.permissions).toEqual(['read'])
+ expect(grantsA[0]!.inherit).toBe(true)
+ expect(grantsB[0]!.inherit).toBe(true)
+ })
+ } finally {
+ await app.close()
+ }
+ })
+ })
diff --cc desktop-app/test/e2e-playwright/helpers/gfsAclShareFixtures.ts
index 000000000,8027f6596..130de19e9
mode 000000,100644..100644
--- a/desktop-app/test/e2e-playwright/helpers/gfsAclShareFixtures.ts
+++ b/desktop-app/test/e2e-playwright/helpers/gfsAclShareFixtures.ts
@@@ -1,0 -1,66 +1,62 @@@
-import {
- UUID_RE,
- runControlPostgresSql,
- sqlLiteral,
-} from '../../../../tests/e2e/gfsUiFixtures'
++import { UUID_RE, runControlPostgresSql, sqlLiteral } from '../../../../tests/e2e/gfsUiFixtures'
+
+ /**
+ * Named setup precondition: shares may target users/teams, never managed Host
+ * subjects. Keeping one real source share makes the E2E prove both halves of
+ * the Copy ACL contract: the source row is unchanged and no destination row is
+ * cloned.
+ */
+ export function seedIssue797SourceShare(resourceId: string, shareUserId: string): string {
+ if (!UUID_RE.test(resourceId) || !UUID_RE.test(shareUserId)) {
+ throw new Error('issue #797 source share requires UUID resource and user subjects')
+ }
+ const shareId = runControlPostgresSql(`
+ INSERT INTO gfs_shares (
+ drive, resource_id, subject_type, subject_id, permissions,
+ include_descendants, created_by
+ )
+ VALUES (
+ 'main', ${sqlLiteral(resourceId)}::uuid, 'user', ${sqlLiteral(shareUserId)},
+ ARRAY['read']::text[], true, 'e2e:issue-797-source-share'
+ )
+ ON CONFLICT (drive, resource_id, subject_type, subject_id)
+ DO UPDATE SET
+ permissions = EXCLUDED.permissions,
+ include_descendants = EXCLUDED.include_descendants,
+ created_by = EXCLUDED.created_by
+ RETURNING id::text;
+ `)
+ .split('\n')
+ .map(line => line.trim())
+ .find(line => UUID_RE.test(line))
+ if (!shareId) throw new Error('failed to seed issue #797 source user share')
+ return shareId
+ }
+
+ /** Canonical JSONB rows for every direct grant/share under a resource tree. */
+ export function getGfsTreeAclShareRows(rootId: string): string[] {
+ if (!UUID_RE.test(rootId)) throw new Error(`invalid GFS root id: ${rootId}`)
+ return runControlPostgresSql(`
+ WITH RECURSIVE tree AS (
+ SELECT resource_id FROM gfs_resources
+ WHERE drive = 'main' AND resource_id = ${sqlLiteral(rootId)}::uuid
+ AND deleted_at IS NULL
+ UNION ALL
+ SELECT child.resource_id FROM gfs_resources child
+ JOIN tree ON child.parent_resource_id = tree.resource_id
+ WHERE child.drive = 'main' AND child.deleted_at IS NULL
+ ), acl_rows AS (
+ SELECT 'grant'::text AS row_kind, id::text AS row_id,
+ jsonb_build_object('kind', 'grant', 'row', to_jsonb(g))::text AS row_json
+ FROM gfs_grants g WHERE resource_id IN (SELECT resource_id FROM tree)
+ UNION ALL
+ SELECT 'share'::text AS row_kind, id::text AS row_id,
+ jsonb_build_object('kind', 'share', 'row', to_jsonb(s))::text AS row_json
+ FROM gfs_shares s WHERE resource_id IN (SELECT resource_id FROM tree)
+ )
+ SELECT row_json FROM acl_rows ORDER BY row_kind, row_id;
+ `)
+ .split('\n')
+ .map(line => line.trim())
+ .filter(line => line.startsWith('{') && line.endsWith('}'))
+ }
diff --cc desktop-app/test/e2e-playwright/helpers/gfsAgentDiscovery.ts
index 000000000,9394beecb..54bd51f4c
mode 000000,100644..100644
--- a/desktop-app/test/e2e-playwright/helpers/gfsAgentDiscovery.ts
+++ b/desktop-app/test/e2e-playwright/helpers/gfsAgentDiscovery.ts
@@@ -1,0 -1,169 +1,174 @@@
+ /**
+ * TEST-HARNESS discovery, not agent behavior: this module finds eligible
+ * HCC-managed Host CRDs via kubectl so the suites can pick the two journey
+ * agents (Agent A / Agent B). It has nothing to do with the agents' own
+ * tool-based GFS file discovery (gfs_resolve/gfs_list), which the journeys
+ * exercise through the real chat UI.
+ */
+ import { kubectlOut } from '../../../../tests/e2e/gfsUiFixtures'
+
+ /** Historical fleet-wide identity, retained only as an explicit rejection guard. */
+ const LEGACY_FLEET_WIDE_SUBJECT_ID = '1st:mcp-host/standalone'
+
+ export interface ManagedGfsAgent {
+ name: string
+ namespace: string
+ subjectId: string
+ }
+
+ interface CandidateError {
+ namespace: string
+ name: string
+ message: string
+ }
+
+ function formatCandidateError(item: CandidateError): string {
+ return `${item.namespace}/${item.name}: ${item.message}`
+ }
+
+ /**
+ * Reads HCC safe metadata only: the Secret ANNOTATIONS below (expected subject,
+ * host UID/generation) are non-sensitive drift metadata. No credential data is
+ * requested, decoded, or printed — the go-template projects annotations only.
+ */
+ function discoverManagedGfsAgentCandidates(): {
+ candidates: ManagedGfsAgent[]
+ candidateErrors: CandidateError[]
+ } {
+ const expected = 'clerum.io/gfs-token-expected-subject'
+ const uid = 'clerum.io/gfs-token-host-uid'
+ const generation = 'clerum.io/gfs-token-host-generation'
+ const template =
+ `{{range .items}}{{with .metadata.annotations}}{{if index . "${expected}"}}` +
+ `{{index . "${expected}"}}{{"\\t"}}` +
+ `{{index . "${uid}"}}{{"\\t"}}` +
+ `{{index . "${generation}"}}{{"\\n"}}{{end}}{{end}}{{end}}`
+ const output = kubectlOut(['get', 'secrets', '-A', '-o', `go-template=${template}`])
+ const bySubject = new Map<string, ManagedGfsAgent>()
+ const candidateErrors: CandidateError[] = []
- for (const line of output.split('\n').map(value => value.trim()).filter(Boolean)) {
++ for (const line of output
++ .split('\n')
++ .map(value => value.trim())
++ .filter(Boolean)) {
+ const [annotatedSubject, hostUid, hostGeneration] = line.split('\t')
- const match = /^host:1st:([a-z0-9](?:[-a-z0-9]*[a-z0-9])?)\/([a-z0-9](?:[-a-z0-9]*[a-z0-9])?)$/.exec(
- annotatedSubject ?? ''
- )
++ const match =
++ /^host:1st:([a-z0-9](?:[-a-z0-9]*[a-z0-9])?)\/([a-z0-9](?:[-a-z0-9]*[a-z0-9])?)$/.exec(
++ annotatedSubject ?? ''
++ )
+ if (!match || !hostUid || !/^\d+$/.test(hostGeneration ?? '')) continue
+ const namespace = match[1]!
+ const name = match[2]!
+ const subjectId = `1st:${namespace}/${name}`
+ if (name === 'standalone' || subjectId === LEGACY_FLEET_WIDE_SUBJECT_ID) continue
+ let hostState = ''
+ try {
+ hostState = kubectlOut([
+ '-n',
+ namespace,
+ 'get',
+ 'hosts',
+ name,
+ '-o',
+ 'go-template={{.metadata.uid}}{{"\\t"}}{{.metadata.generation}}{{"\\t"}}{{if .metadata.deletionTimestamp}}deleting{{end}}{{"\\t"}}{{if eq .spec.enabled false}}disabled{{end}}',
+ ]).trim()
+ } catch (error) {
+ // An infra error while validating a candidate must not be silently
+ // reported as "agent does not exist"; it is surfaced with the final
+ // topology failure so a broken kubectl path fails for the real reason.
+ candidateErrors.push({
+ namespace,
+ name,
+ message: error instanceof Error ? error.message : String(error),
+ })
+ continue
+ }
+ const [activeUid, activeGeneration, deleting, disabled] = hostState.split('\t')
- if (activeUid !== hostUid || activeGeneration !== hostGeneration || deleting || disabled) continue
++ if (activeUid !== hostUid || activeGeneration !== hostGeneration || deleting || disabled)
++ continue
+ bySubject.set(subjectId, { name, namespace, subjectId })
+ }
+ if (bySubject.size === 0 && candidateErrors.length > 0) {
+ throw new Error(
+ `GFS agent discovery could not validate any candidate host: ${candidateErrors
+ .map(formatCandidateError)
+ .join('; ')}`
+ )
+ }
+ return {
+ candidates: [...bySubject.values()].sort((a, b) => a.subjectId.localeCompare(b.subjectId)),
+ candidateErrors,
+ }
+ }
+
+ function chooseManagedGfsAgent(
+ candidates: ManagedGfsAgent[],
+ candidateErrors: CandidateError[],
+ requested: string | undefined,
+ excluded?: string
+ ): ManagedGfsAgent | undefined {
+ const eligible = candidates.filter(item => item.subjectId !== excluded)
+ if (requested) {
+ const matches = eligible.filter(item => item.name === requested)
+ if (matches.length !== 1) {
+ // If the requested agent was among the candidates whose kubectl
+ // validation errored, "missing" would misreport an infra failure as a
+ // topology failure — include the recorded error for that candidate.
+ const requestedErrors = candidateErrors
+ .filter(item => item.name === requested)
+ .map(formatCandidateError)
+ throw new Error(
+ `HCC agent "${requested}" is missing or ambiguous` +
+ (requestedErrors.length > 0
+ ? ` (candidate validation errors: ${requestedErrors.join('; ')})`
+ : '')
+ )
+ }
+ return matches[0]
+ }
+ return eligible.find(item => eligible.filter(other => other.name === item.name).length === 1)
+ }
+
+ /**
+ * Live pod identity (UID + startTime) for an HCC-managed agent. Used to prove
+ * "same runtime" claims: revocation enforcement must not depend on a pod
+ * restart, so the identity captured before a revoke must equal the identity
+ * observed after the denied retry.
+ */
+ export function getManagedAgentPodIdentity(agent: ManagedGfsAgent): string {
+ const identity = kubectlOut([
+ '-n',
+ agent.namespace,
+ 'get',
+ 'pods',
+ '-l',
+ `app=${agent.name}`,
+ '-o',
+ 'go-template={{range .items}}{{if not .metadata.deletionTimestamp}}{{.metadata.uid}}{{"\\t"}}{{.status.startTime}}{{"\\n"}}{{end}}{{end}}',
+ ]).trim()
+ if (!identity) {
+ throw new Error(`no live pod found for HCC-managed agent ${agent.namespace}/${agent.name}`)
+ }
+ return identity
+ }
+
+ export function discoverManagedGfsAgent(): ManagedGfsAgent {
+ const { candidates, candidateErrors } = discoverManagedGfsAgentCandidates()
+ const agent = chooseManagedGfsAgent(candidates, candidateErrors, process.env.E2E_GFS_AGENT_A)
+ if (!agent) throw new Error('GFS agent E2E requires one unambiguous HCC-managed agent name')
+ return agent
+ }
+
+ export function discoverManagedGfsAgents(): [ManagedGfsAgent, ManagedGfsAgent] {
+ const { candidates, candidateErrors } = discoverManagedGfsAgentCandidates()
+ const agentA = chooseManagedGfsAgent(candidates, candidateErrors, process.env.E2E_GFS_AGENT_A)
+ const agentB = chooseManagedGfsAgent(
+ candidates,
+ candidateErrors,
+ process.env.E2E_GFS_AGENT_B,
+ agentA?.subjectId
+ )
+ if (!agentA || !agentB || agentA.name === agentB.name) {
+ throw new Error('Issue #797 requires two distinct, unambiguous HCC-managed agent names')
+ }
+ return [agentA, agentB]
+ }
diff --cc desktop-app/test/e2e-playwright/helpers/gfsFixtures.ts
index 1b404edc4,642d2faec..4ba819635
--- a/desktop-app/test/e2e-playwright/helpers/gfsFixtures.ts
+++ b/desktop-app/test/e2e-playwright/helpers/gfsFixtures.ts
@@@ -1,39 -1,43 +1,43 @@@
- /**
- * GFS fixtures for the agent-file-read E2E journey (issue #775).
- *
- * Seeds two isolated GFS files through the shared SQL fixtures:
- * - `granted`: visible to the Desktop user AND granted read to the agent
- * host `chatllm` — the happy path.
- * - `ungranted`: visible to the Desktop user but NOT granted to the host —
- * the agent must receive a clean authorization denial (403),
- * never a permission-store outage (503 not_mounted).
- *
- * Also provides the fail-loud infra guard: when gfsc is unhealthy the suite
- * THROWS with the concrete pod/Secret state. It never skips and never mocks —
- * a broken permission store is an infrastructure blocker, not a reason to
- * fake a pass (repo rule: tests fail loud, especially minikube E2E).
- */
+ /** Exact-subject GFS fixtures for the #775 regression and #797 Copy journey. */
++import { request } from '@playwright/test'
++import {
++ type GfsCopyTreeFixture,
++ cleanupGfsCopyTreeFixture,
++ getGfsHostGrantsUnderTree,
++ getGfsTreeAclShareCounts,
++ getGfsTreeSnapshot,
++ seedGfsCopyTreeFixture,
++} from '../../../../tests/e2e/gfsCopyFixtures'
import {
type GfsFileFixture,
cleanupGfsFixture,
+ countGfsLiveChildrenByName,
- getGfsChildResourceSummary,
getE2EUserId,
++ getGfsChildResourceSummary,
kubectlOut,
+ runControlPostgresSql,
seedGfsFileFixture,
seedGfsGrant,
+ sqlLiteral,
uniqueGfsFixtureName,
} from '../../../../tests/e2e/gfsUiFixtures'
++import { seedIssue797SourceShare } from './gfsAclShareFixtures'
+ import {
- type GfsCopyTreeFixture,
- cleanupGfsCopyTreeFixture,
- getGfsHostGrantsUnderTree,
- getGfsTreeAclShareCounts,
- getGfsTreeSnapshot,
- seedGfsCopyTreeFixture,
-} from '../../../../tests/e2e/gfsCopyFixtures'
-import { request } from '@playwright/test'
-import {
++ type ManagedGfsAgent,
+ discoverManagedGfsAgent,
+ discoverManagedGfsAgents,
- type ManagedGfsAgent,
+ } from './gfsAgentDiscovery'
-import { seedIssue797SourceShare } from './gfsAclShareFixtures'
- /**
- * The Desktop agent journey runs through the concrete `chatllm` Host. GFS
- * grants are host-specific, so `chatllm-stateless` and every other first-party
- * Host remain independently denied unless they receive their own grant.
- */
- export const FIRST_PARTY_HOST_SUBJECT_ID = '1st:mcp-host/chatllm'
+ export {
+ discoverManagedGfsAgent,
+ discoverManagedGfsAgents,
+ type ManagedGfsAgent,
+ } from './gfsAgentDiscovery'
+ export { getGfsTreeAclShareRows } from './gfsAclShareFixtures'
const GFS_NS = 'gfs'
- // Pod-template labels — pods do NOT inherit the deployment-level managed-by
- // label (see gfsFactory commonLabels vs spec.selector).
const GFSC_POD_SELECTOR = 'app=gfs-controller'
+ const ISSUE_797_SHARE_RECIPIENT_EMAIL = '[email protected]'
/**
* FAIL LOUD, NEVER SKIP: proves gfsc can actually authorize before any test
@@@ -96,12 -102,170 +102,187 @@@ export interface AgentGfsFixtures
cleanup(): void
}
+ export interface AgentGfsCopyFixtures {
+ agentA: ManagedGfsAgent
+ agentB: ManagedGfsAgent
+ tree: GfsCopyTreeFixture
+ fileCopyName: string
+ folderCopyName: string
+ renamedFolderName: string
+ deniedCopyName: string
+ revokedCopyName: string
+ destinationGrantId: string
+ /** Source user-share whose exact row must survive Copy unchanged. */
+ sourceShareId: string
+ sourceShareSubjectId: string
+ cleanup(): void
+ }
+
+ export function seedAgentGfsCopyFixtures(ownerEmail: string): AgentGfsCopyFixtures {
+ const [agentA, agentB] = discoverManagedGfsAgents()
+ const tree = seedGfsCopyTreeFixture(uniqueGfsFixtureName('e2e-gfs-copy-797'))
+ try {
+ const ownerUserId = getE2EUserId(ownerEmail)
+ const sourceShareSubjectId = getE2EUserId(ISSUE_797_SHARE_RECIPIENT_EMAIL)
+ for (const resourceId of [tree.sourceResourceId, tree.destinationResourceId]) {
+ seedGfsGrant({
+ resourceId,
+ subjectType: 'user',
+ subjectId: ownerUserId,
+ permissions: ['read'],
+ inherit: true,
+ grantedBy: 'e2e:issue-797-owner',
+ })
+ }
+ seedGfsGrant({
+ resourceId: tree.sourceResourceId,
+ subjectType: 'host',
+ subjectId: agentA.subjectId,
+ permissions: ['read'],
+ inherit: true,
+ grantedBy: 'e2e:issue-797-agent-a',
+ })
+ seedGfsGrant({
- resourceId: tree.sourceResourceId, subjectType: 'host', subjectId: agentB.subjectId,
- permissions: ['read'], inherit: false, grantedBy: 'e2e:issue-797-agent-b-root-only',
++ resourceId: tree.sourceResourceId,
++ subjectType: 'host',
++ subjectId: agentB.subjectId,
++ permissions: ['read'],
++ inherit: false,
++ grantedBy: 'e2e:issue-797-agent-b-root-only',
+ })
+ seedGfsGrant({
- resourceId: tree.destinationResourceId, subjectType: 'host', subjectId: agentB.subjectId,
- permissions: ['read', 'write'], inherit: true, grantedBy: 'e2e:issue-797-agent-b-destination',
++ resourceId: tree.destinationResourceId,
++ subjectType: 'host',
++ subjectId: agentB.subjectId,
++ permissions: ['read', 'write'],
++ inherit: true,
++ grantedBy: 'e2e:issue-797-agent-b-destination',
+ })
+ const agentBSource = getGfsHostGrantsUnderTree(tree.sourceResourceId, agentB.subjectId)
- if (agentBSource.length !== 1 || agentBSource[0]?.resourceId !== tree.sourceResourceId ||
- agentBSource[0].inherit || agentBSource[0].permissions.join(',') !== 'read') {
++ if (
++ agentBSource.length !== 1 ||
++ agentBSource[0]?.resourceId !== tree.sourceResourceId ||
++ agentBSource[0].inherit ||
++ agentBSource[0].permissions.join(',') !== 'read'
++ ) {
+ throw new Error('Agent B fixture must have root-only source read and no descendant grant')
+ }
+ const agentBDest = getGfsHostGrantsUnderTree(tree.destinationResourceId, agentB.subjectId)
- if (agentBDest.length !== 1 || !agentBDest[0]?.inherit ||
- agentBDest[0].permissions.join(',') !== 'read,write') {
++ if (
++ agentBDest.length !== 1 ||
++ !agentBDest[0]?.inherit ||
++ agentBDest[0].permissions.join(',') !== 'read,write'
++ ) {
+ throw new Error('Agent B fixture must have destination read/write')
+ }
+ const destinationGrantId = seedGfsGrant({
+ resourceId: tree.destinationResourceId,
+ subjectType: 'host',
+ subjectId: agentA.subjectId,
+ permissions: ['read', 'write'],
+ inherit: true,
+ grantedBy: 'e2e:issue-797-agent-a',
+ })
+ const sourceShareId = seedIssue797SourceShare(tree.sourceResourceId, sourceShareSubjectId)
+ return {
+ agentA,
+ agentB,
+ tree,
+ fileCopyName: `${tree.sourceName}-file-copy.txt`,
+ folderCopyName: `${tree.sourceName}-copy`,
+ renamedFolderName: `${tree.sourceName}-renamed`,
+ deniedCopyName: `${tree.sourceName}-agent-b-denied`,
+ revokedCopyName: `${tree.sourceName}-revoked-denied`,
+ destinationGrantId,
+ sourceShareId,
+ sourceShareSubjectId,
+ cleanup: () => cleanupGfsCopyTreeFixture(tree),
+ }
+ } catch (error) {
+ try {
+ cleanupGfsCopyTreeFixture(tree)
+ } catch (cleanupError) {
+ throw new Error(
+ `GFS Copy setup failed (${String(error)}) and cleanup failed (${String(cleanupError)})`
+ )
+ }
+ throw error
+ }
+ }
+
+ export async function revokeGfsGrantViaControlApi(grantId: string): Promise<void> {
+ const rawBase = process.env.E2E_CONTROL_API_URL || process.env.CONTROL_API_BASE_URL
+ if (!rawBase) throw new Error('audited GFS revoke requires an explicit Control API URL')
+ const base = new URL(rawBase)
+ if (!['127.0.0.1', 'localhost'].includes(base.hostname)) {
+ throw new Error(`refusing issue #797 fixture revoke against ${base.origin}`)
+ }
+ // The desktop suite has no storageState producer, so the admin session is
+ // created here through the real cookie login the Control UI uses. The
+ // local-only default password is safe behind the localhost guard above and
+ // matches the repo-wide E2E admin credential priority.
+ const api = await request.newContext({ baseURL: base.origin })
+ try {
+ const username = process.env.TEST_ADMIN_USERNAME || 'admin'
+ const password =
+ process.env.E2E_ADMIN_PASSWORD ||
+ process.env.ADMIN_PASSWORD ||
+ process.env.ADMIN_PASS ||
+ process.env.TEST_ADMIN_PASSWORD ||
+ 'admin123!'
+ const login = await api.post('/api/v1/admin/auth/login', {
+ data: { username, password },
+ })
+ if (!login.ok()) {
+ throw new Error(
+ `audited GFS revoke admin login failed with HTTP ${login.status()}: ${await login.text()}`
+ )
+ }
+ // The admin session cookie is issued Secure; Playwright's cookie jar
+ // rightly refuses to send Secure cookies over the http:// port-forward, so
+ // API-only consumers send the captured value as an explicit Cookie header
+ // (same pattern as the root suite's adminSessionCookieHeader helper).
+ const sessionCookie = (await api.storageState()).cookies.find(
+ cookie => cookie.name === 'control_ui_admin_session'
+ )
+ if (!sessionCookie?.value) {
+ throw new Error('audited GFS revoke admin login did not set control_ui_admin_session')
+ }
+ const response = await api.delete(`/api/v1/gfs/grants/${encodeURIComponent(grantId)}`, {
+ headers: {
+ 'X-Request-Id': `e2e-797-revoke-${Date.now()}`,
+ cookie: `${sessionCookie.name}=${sessionCookie.value}`,
+ },
+ })
+ if (!response.ok()) {
- throw new Error(`audited GFS revoke failed with HTTP ${response.status()}: ${await response.text()}`)
++ throw new Error(
++ `audited GFS revoke failed with HTTP ${response.status()}: ${await response.text()}`
++ )
+ }
+ } finally {
+ await api.dispose()
+ }
+ }
+
+ export function gfsGrantRevokeAuditCount(agent: ManagedGfsAgent): number {
+ const rows = runControlPostgresSql(`
+ SELECT count(*)::text FROM gfs_audit
+ WHERE subject = ${sqlLiteral(`host:${agent.subjectId}`)}
+ AND op = 'grant.delete' AND outcome = 'allowed';
+ `)
+ return Number(rows.trim())
+ }
+
+ export {
+ countGfsLiveChildrenByName,
+ getGfsChildResourceSummary,
+ getGfsTreeAclShareCounts,
+ getGfsTreeSnapshot,
+ }
+
export function seedAgentGfsFixtures(ownerEmail: string): AgentGfsFixtures {
+ const agent = discoverManagedGfsAgent()
const ownerUserId = getE2EUserId(ownerEmail)
- // Exception-safe seeding: if any later step throws, tear down whatever was
- // already created (rows + PVC blobs) before rethrowing — a partial seed must
- // not leak into the shared profile, and afterAll never runs on a failed
- // beforeAll.
const seeded: GfsFileFixture[] = []
let granted: GfsFileFixture
let ungranted: GfsFileFixture
diff --cc desktop-app/test/gfsAclShareFixtures.test.ts
index 000000000,3db3831d2..baad33750
mode 000000,100644..100644
--- a/desktop-app/test/gfsAclShareFixtures.test.ts
+++ b/desktop-app/test/gfsAclShareFixtures.test.ts
@@@ -1,0 -1,53 +1,52 @@@
+ import { beforeEach, describe, expect, it, vi } from 'vitest'
++import {
++ getGfsTreeAclShareRows,
++ seedIssue797SourceShare,
++} from './e2e-playwright/helpers/gfsAclShareFixtures'
+
+ const runControlPostgresSqlMock = vi.hoisted(() => vi.fn())
+
+ vi.mock('../../tests/e2e/gfsUiFixtures', () => ({
+ UUID_RE: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
+ runControlPostgresSql: runControlPostgresSqlMock,
+ sqlLiteral: (value: string) => `'${value.replace(/'/g, "''")}'`,
+ }))
+
-import {
- getGfsTreeAclShareRows,
- seedIssue797SourceShare,
-} from './e2e-playwright/helpers/gfsAclShareFixtures'
-
+ describe('issue #797 GFS ACL/share fixture evidence', () => {
+ beforeEach(() => runControlPostgresSqlMock.mockReset())
+
+ it('seeds the named source share for a user, never a Host subject', () => {
+ runControlPostgresSqlMock.mockReturnValue('d4d2c593-6932-488e-844c-c5852b910783\n')
+
+ expect(
+ seedIssue797SourceShare(
+ '5a50453e-04d1-4403-8473-23013eaa56c7',
+ 'ef72208d-783a-4574-9181-440a6764fa27'
+ )
+ ).toBe('d4d2c593-6932-488e-844c-c5852b910783')
+
+ const sql = String(runControlPostgresSqlMock.mock.calls[0]?.[0])
+ expect(sql).toContain("'user', 'ef72208d-783a-4574-9181-440a6764fa27'")
+ expect(sql).toContain("ARRAY['read']::text[], true")
+ expect(sql).not.toContain("'host'")
+ })
+
+ it('returns stable full-row JSON evidence for both grants and shares', () => {
+ const rows = [
+ '{"kind":"grant","row":{"id":"grant-1"}}',
+ '{"kind":"share","row":{"id":"share-1"}}',
+ ]
+ runControlPostgresSqlMock.mockReturnValue(`\n${rows.join('\n')}\n`)
+
+ expect(getGfsTreeAclShareRows('5a50453e-04d1-4403-8473-23013eaa56c7')).toEqual(rows)
+ const sql = String(runControlPostgresSqlMock.mock.calls[0]?.[0])
+ expect(sql).toContain("jsonb_build_object('kind', 'grant', 'row', to_jsonb(g))")
+ expect(sql).toContain("jsonb_build_object('kind', 'share', 'row', to_jsonb(s))")
+ expect(sql).toContain('ORDER BY row_kind, row_id')
+ })
+
+ it('rejects an invalid root before querying PostgreSQL', () => {
+ expect(() => getGfsTreeAclShareRows('not-a-resource-id')).toThrow('invalid GFS root id')
+ expect(runControlPostgresSqlMock).not.toHaveBeenCalled()
+ })
+ })
diff --cc desktop-app/test/gfsFixtureDiscovery.test.ts
index 000000000,e9f517c22..dd3e75c99
mode 000000,100644..100644
--- a/desktop-app/test/gfsFixtureDiscovery.test.ts
+++ b/desktop-app/test/gfsFixtureDiscovery.test.ts
@@@ -1,0 -1,74 +1,73 @@@
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
++import {
++ discoverManagedGfsAgent,
++ discoverManagedGfsAgents,
++} from './e2e-playwright/helpers/gfsFixtures'
+
+ const execFileSyncMock = vi.hoisted(() => vi.fn())
+
+ vi.mock('node:child_process', () => ({
+ execFileSync: execFileSyncMock,
+ }))
+
-import {
- discoverManagedGfsAgent,
- discoverManagedGfsAgents,
-} from './e2e-playwright/helpers/gfsFixtures'
-
+ describe('discoverManagedGfsAgents', () => {
+ const context = 'clerum-codex-gfs-fixture-test'
+ let secretRows: string
+
+ beforeEach(() => {
+ process.env.E2E_K8S_CONTEXT = context
+ secretRows =
+ 'host:1st:mcp-host/agent-a\tuid-a\t1\n' +
+ 'host:1st:mcp-host/agent-b\tuid-b\t2\n' +
+ 'host:1st:mcp-host/incomplete\t\t\n'
+ execFileSyncMock.mockImplementation((_command: string, args: string[]) => {
+ const resourceIndex = args.indexOf('get') + 1
+ const resource = args[resourceIndex]
+ if (resource === 'secrets') {
+ return secretRows
+ }
+ if (resource === 'hosts' && args[resourceIndex + 1] === 'agent-a') {
+ return 'uid-a\t1\t\t'
+ }
+ if (resource === 'hosts' && args[resourceIndex + 1] === 'agent-b') {
+ return 'uid-b\t2\t\t'
+ }
+ throw new Error(`unexpected kubectl call: ${args.join(' ')}`)
+ })
+ })
+
+ afterEach(() => {
+ delete process.env.E2E_K8S_CONTEXT
+ execFileSyncMock.mockReset()
+ })
+
+ it('reads only annotated Secret metadata and returns two active exact-subject hosts', () => {
+ expect(discoverManagedGfsAgents()).toEqual([
+ { name: 'agent-a', namespace: 'mcp-host', subjectId: '1st:mcp-host/agent-a' },
+ { name: 'agent-b', namespace: 'mcp-host', subjectId: '1st:mcp-host/agent-b' },
+ ])
+
+ const calls = execFileSyncMock.mock.calls
+ expect(calls).toHaveLength(3)
+ for (const [command, args] of calls) {
+ expect(command).toBe('kubectl')
+ expect(args.slice(0, 2)).toEqual(['--context', context])
+ }
+
+ const secretArgs = calls[0]![1] as string[]
+ const outputArg = secretArgs.find(value => value.startsWith('go-template='))
+ expect(outputArg).toContain('{{with .metadata.annotations}}')
+ expect(outputArg).toContain('clerum.io/gfs-token-expected-subject')
+ expect(secretArgs).not.toContain('json')
+ })
+
+ it('keeps the single-agent read regression independent from the two-agent Copy gate', () => {
+ secretRows = 'host:1st:mcp-host/agent-a\tuid-a\t1\n'
+
+ expect(discoverManagedGfsAgent()).toEqual({
+ name: 'agent-a',
+ namespace: 'mcp-host',
+ subjectId: '1st:mcp-host/agent-a',
+ })
+ })
+ })
diff --cc desktop-app/test/gfsUriHandler.test.ts
index d162a8f08,dac8fbd92..18d9442a5
--- a/desktop-app/test/gfsUriHandler.test.ts
+++ b/desktop-app/test/gfsUriHandler.test.ts
@@@ -7,6 -8,6 +7,7 @@@ import
parseGfsUri,
parseSubjectKey,
} from '../src/gfs/uriHandler.js'
++import { ApiError } from '../src/httpClient.js'
/**
* P2-S06 — Desktop gfs:// resolve + read. Acceptance: a gfs://<drive>/<rid> link
diff --cc desktop-app/ui/src/gfs/GfsGrantList/types.ts
index 000000000,18bc9cd87..727e5faab
mode 000000,100644..100644
--- a/desktop-app/ui/src/gfs/GfsGrantList/types.ts
+++ b/desktop-app/ui/src/gfs/GfsGrantList/types.ts
@@@ -1,0 -1,22 +1,22 @@@
++import type { GfsGrantErrorPresentation } from '@lib/gfsGrantErrors'
+ import type {
+ GfsAgentSubjectOption,
+ GfsDelegationSubjectOption,
+ GfsGrantListItem,
+ } from '@/gfs/delegation.types'
-import type { GfsGrantErrorPresentation } from '@lib/gfsGrantErrors'
+
+ export interface GfsGrantListProps {
+ items: GfsGrantListItem[]
+ 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
+ /** 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>
+ revoking?: boolean
+ }
diff --cc desktop-app/ui/src/gfs/__tests__/GfsAgentAccessSection.test.tsx
index 000000000,172f82176..3744df990
mode 000000,100644..100644
--- a/desktop-app/ui/src/gfs/__tests__/GfsAgentAccessSection.test.tsx
+++ b/desktop-app/ui/src/gfs/__tests__/GfsAgentAccessSection.test.tsx
@@@ -1,0 -1,125 +1,115 @@@
+ // @vitest-environment jsdom
+ import { afterEach, describe, expect, it, vi } from 'vitest'
+ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+ import { GfsAgentAccessSection } from '../GfsAgentAccessSection'
+
+ /**
+ * Per-agent GFS delegation section (Manage modal). Proves the read/write-only
+ * permission cap, the `host:`-prefixed subject keys, and the inherit contract:
+ * directories default inherit ON (a folder grant without inherit would silently
+ * break the agent-reads-file journey); files never send inherit.
+ */
+
+ afterEach(cleanup)
+
+ const agents = [
+ { id: '1st:mcp-host/chatllm', name: 'chatllm' },
+ { id: '1st:mcp-host/chatllm-stateless', name: 'chatllm-stateless' },
+ ]
+
+ describe('GfsAgentAccessSection', () => {
+ it('offers ONLY read and write permissions for agents', () => {
- render(
- <GfsAgentAccessSection agents={agents} isDirectory onGrantAgents={vi.fn()} />
- )
++ render(<GfsAgentAccessSection agents={agents} isDirectory onGrantAgents={vi.fn()} />)
+
+ fireEvent.click(screen.getByRole('button', { name: 'Read' }))
+ expect(screen.getByRole('menuitemcheckbox', { name: 'Read' })).toBeTruthy()
+ expect(screen.getByRole('menuitemcheckbox', { name: 'Write' })).toBeTruthy()
+ expect(screen.queryByRole('menuitemcheckbox', { name: 'Manage access' })).toBeNull()
+ expect(screen.queryByRole('menuitemcheckbox', { name: 'Share' })).toBeNull()
+ expect(screen.queryByRole('menuitemcheckbox', { name: 'Delete' })).toBeNull()
+ })
+
+ it('emits host:-prefixed subject keys for the selected agents', async () => {
+ const onGrantAgents = vi.fn().mockResolvedValue(undefined)
- render(
- <GfsAgentAccessSection agents={agents} isDirectory onGrantAgents={onGrantAgents} />
- )
++ render(<GfsAgentAccessSection agents={agents} isDirectory onGrantAgents={onGrantAgents} />)
+
+ fireEvent.click(screen.getByRole('button', { name: 'chatllm' }))
+ fireEvent.click(screen.getByRole('button', { name: 'chatllm-stateless' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Grant agent access' }))
+
+ await waitFor(() =>
+ expect(onGrantAgents).toHaveBeenCalledWith(
+ ['host:1st:mcp-host/chatllm', 'host:1st:mcp-host/chatllm-stateless'],
+ ['read'],
+ true
+ )
+ )
+ })
+
+ it('defaults the inherit toggle ON for directories and honors turning it off', async () => {
+ const onGrantAgents = vi.fn().mockResolvedValue(undefined)
- render(
- <GfsAgentAccessSection agents={agents} isDirectory onGrantAgents={onGrantAgents} />
- )
++ render(<GfsAgentAccessSection agents={agents} isDirectory onGrantAgents={onGrantAgents} />)
+
+ const inherit = screen.getByRole('checkbox', { name: 'Include contents of this folder' })
+ expect(inherit).toHaveProperty('checked', true)
+
+ fireEvent.click(inherit)
+ fireEvent.click(screen.getByRole('button', { name: 'chatllm' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Grant agent access' }))
+
+ await waitFor(() =>
+ expect(onGrantAgents).toHaveBeenCalledWith(['host:1st:mcp-host/chatllm'], ['read'], false)
+ )
+ })
+
+ it('hides the inherit toggle for files and always sends inherit false', async () => {
+ const onGrantAgents = vi.fn().mockResolvedValue(undefined)
+ render(
+ <GfsAgentAccessSection agents={agents} isDirectory={false} onGrantAgents={onGrantAgents} />
+ )
+
- expect(
- screen.queryByRole('checkbox', { name: 'Include contents of this folder' })
- ).toBeNull()
++ expect(screen.queryByRole('checkbox', { name: 'Include contents of this folder' })).toBeNull()
+
+ fireEvent.click(screen.getByRole('button', { name: 'chatllm' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Grant agent access' }))
+
+ await waitFor(() =>
+ expect(onGrantAgents).toHaveBeenCalledWith(['host:1st:mcp-host/chatllm'], ['read'], false)
+ )
+ })
+
+ it('surfaces a mapped server verdict and keeps ALL selected agents on an atomic failure', async () => {
+ // The bulk grant is all-or-nothing: a rejection means NO agent was granted,
+ // so every selected agent stays selected for a retry (no partial-success).
+ const onGrantAgents = vi
+ .fn()
+ .mockRejectedValue(new Error('403 Forbidden: managed_agent_permission_forbidden'))
- render(
- <GfsAgentAccessSection agents={agents} isDirectory onGrantAgents={onGrantAgents} />
- )
++ render(<GfsAgentAccessSection agents={agents} isDirectory onGrantAgents={onGrantAgents} />)
+
+ fireEvent.click(screen.getByRole('button', { name: 'chatllm' }))
+ fireEvent.click(screen.getByRole('button', { name: 'chatllm-stateless' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Grant agent access' }))
+
+ await screen.findByText('Managed agents can only be granted read and write.')
+ expect(onGrantAgents).toHaveBeenCalledTimes(1)
+ expect(onGrantAgents).toHaveBeenCalledWith(
+ ['host:1st:mcp-host/chatllm', 'host:1st:mcp-host/chatllm-stateless'],
+ ['read'],
+ true
+ )
+ // SelectableOption only sets aria-pressed="true" while selected — both stay.
- expect(
- screen.getByRole('button', { name: 'chatllm' }).getAttribute('aria-pressed')
- ).toBe('true')
++ expect(screen.getByRole('button', { name: 'chatllm' }).getAttribute('aria-pressed')).toBe(
++ 'true'
++ )
+ expect(
+ screen.getByRole('button', { name: 'chatllm-stateless' }).getAttribute('aria-pressed')
+ ).toBe('true')
+ })
+
+ it('renders an empty notice when the caller has no grantable agents', () => {
+ render(<GfsAgentAccessSection agents={[]} isDirectory onGrantAgents={vi.fn()} />)
+
+ expect(screen.getByText('You have no agents that can be granted access.')).toBeTruthy()
+ expect(screen.queryByRole('button', { name: 'Grant agent access' })).toBeNull()
+ })
+ })
diff --cc desktop-app/ui/src/gfs/__tests__/GfsGrantList.test.tsx
index 000000000,ed69207c4..e9989c5a5
mode 000000,100644..100644
--- a/desktop-app/ui/src/gfs/__tests__/GfsGrantList.test.tsx
+++ b/desktop-app/ui/src/gfs/__tests__/GfsGrantList.test.tsx
@@@ -1,0 -1,119 +1,117 @@@
+ // @vitest-environment jsdom
+ import { afterEach, describe, expect, it, vi } from 'vitest'
+ import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'
-import type { GfsGrantListItem } from '../delegation.types'
+ import { GfsGrantList } from '../GfsGrantList'
++import type { GfsGrantListItem } from '../delegation.types'
+
+ /**
+ * "Who has access" list (Manage modal). Rows resolve host subjects to agent
+ * names, user/team subjects through the visible team directory, and fall back
+ * to the raw id (a row is never hidden). A manage_acl_required list failure is
+ * an expected state and renders as a quiet informational banner, not an error.
+ */
+
+ afterEach(cleanup)
+
+ const agents = [{ id: '1st:mcp-host/chatllm', name: 'Chat LLM' }]
+ const subjects = [
+ { type: 'user' as const, id: 'user-2', label: 'Test Two', description: '[email protected]' },
+ { type: 'team' as const, id: 'team-1', label: 'Core Team' },
+ ]
+
+ function grantItem(overrides: Partial<GfsGrantListItem>): GfsGrantListItem {
+ return {
+ id: 'grant-1',
+ drive: 'main',
+ resourceId: 'res-1',
+ subject: { type: 'host', id: '1st:mcp-host/chatllm' },
+ permissions: ['read'],
+ inherit: false,
+ ...overrides,
+ }
+ }
+
+ describe('GfsGrantList', () => {
+ it('renders resolved subject labels, permission chips, and the inherit badge', () => {
+ render(
+ <GfsGrantList
+ agents={agents}
+ items={[
+ grantItem({ id: 'grant-1', permissions: ['read', 'write'], inherit: true }),
+ grantItem({
+ id: 'grant-2',
+ subject: { type: 'user', id: 'user-2' },
+ permissions: ['read'],
+ }),
+ grantItem({ id: 'grant-3', subject: { type: 'host', id: '1st:mcp-host/unknown' } }),
+ ]}
+ onRevoke={vi.fn()}
+ subjects={subjects}
+ />
+ )
+
+ const agentRow = screen.getByText('Chat LLM').closest('li')!
+ expect(within(agentRow).getByText('Read')).toBeTruthy()
+ expect(within(agentRow).getByText('Write')).toBeTruthy()
+ expect(within(agentRow).getByText('Includes contents')).toBeTruthy()
+
+ const userRow = screen.getByText('Test Two').closest('li')!
+ expect(within(userRow).getByText('Read')).toBeTruthy()
+ expect(within(userRow).queryByText('Includes contents')).toBeNull()
+
+ // Unresolvable subject ids stay visible as raw ids — never hidden.
+ expect(screen.getByText('1st:mcp-host/unknown')).toBeTruthy()
+ })
+
+ it('fires the revoke callback from the row button with an accessible name', () => {
+ const onRevoke = vi.fn()
+ const item = grantItem({ id: 'grant-1' })
+ render(<GfsGrantList agents={agents} items={[item]} onRevoke={onRevoke} subjects={subjects} />)
+
+ fireEvent.click(screen.getByRole('button', { name: 'Revoke access for Chat LLM' }))
+
+ expect(onRevoke).toHaveBeenCalledWith(item, 'Chat LLM')
+ })
+
+ it('renders manage_acl_required as a quiet informational banner instead of the list', () => {
+ render(
+ <GfsGrantList
+ agents={agents}
+ error={{
+ code: 'manage_acl_required',
+ message: 'Only people with manage access can view who has access here.',
+ severity: 'quiet',
+ }}
+ items={[grantItem({ id: 'grant-1' })]}
+ onRevoke={vi.fn()}
+ subjects={subjects}
+ />
+ )
+
- const banner = screen.getByText(
- 'Only people with manage access can view who has access here.'
- )
++ const banner = screen.getByText('Only people with manage access can view who has access here.')
+ expect(banner.closest('.status-banner')?.className).toContain('tone-info')
+ expect(screen.queryByRole('list')).toBeNull()
+ expect(screen.queryByRole('button', { name: /Revoke access for/ })).toBeNull()
+ })
+
+ it('renders other list failures as an error banner', () => {
+ render(
+ <GfsGrantList
+ agents={agents}
+ error={{ code: null, message: 'listGrants exploded', severity: 'error' }}
+ items={[]}
+ onRevoke={vi.fn()}
+ subjects={subjects}
+ />
+ )
+
+ const banner = screen.getByText('listGrants exploded')
+ expect(banner.closest('.status-banner')?.className).toContain('tone-error')
+ })
+
+ 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()
+ })
+ })
diff --cc desktop-app/ui/src/lib/__tests__/gfsGrantErrors.test.ts
index 000000000,f2df6c2e8..1a3407e3f
mode 000000,100644..100644
--- a/desktop-app/ui/src/lib/__tests__/gfsGrantErrors.test.ts
+++ b/desktop-app/ui/src/lib/__tests__/gfsGrantErrors.test.ts
@@@ -1,0 -1,119 +1,115 @@@
+ import { describe, expect, it } from 'vitest'
+ import { describeGfsGrantError } from '../gfsGrantErrors'
+
+ /**
+ * Pure presentation map for GFS grant-plane server verdicts. Codes arrive
+ * embedded in Electron IPC error messages, so matching is substring-based.
+ *
+ * `invalidIndexes` / `retryAfterSeconds` are SEPARATE response-body fields on the
+ * server; the desktop main process (uriHandler surfaceGfsGrantError) appends them
+ * to the error message as `invalidIndexes=[…]` / `retryAfterSeconds=…` BEFORE the
+ * IPC boundary drops `ApiError.bodyText`. These cases feed that real production
+ * message shape — not a JSON blob the wire never carries.
+ */
+
+ describe('describeGfsGrantError', () => {
+ it.each([
- [
- 'agent_manager_forbidden',
- "Agents can't be given manage or share access.",
- ],
- [
- 'managed_agent_permission_forbidden',
- 'Managed agents can only be granted read and write.',
- ],
++ ['agent_manager_forbidden', "Agents can't be given manage or share access."],
++ ['managed_agent_permission_forbidden', 'Managed agents can only be granted read and write.'],
+ ['foreign_agent_forbidden', 'You can only grant access to your own agents.'],
+ ['escalation_rejected', 'You can only grant permissions you already hold here.'],
+ ])('maps %s to its human message with error severity', (code, message) => {
+ const presentation = describeGfsGrantError(
+ new Error(`Error invoking remote method 'gfs:grant': Error: 403 Forbidden: ${code}`)
+ )
+
+ expect(presentation).toEqual({ code, message, severity: 'error' })
+ })
+
+ it('maps manage_acl_required to a quiet banner, never an error toast', () => {
+ const presentation = describeGfsGrantError(
- new Error("Error invoking remote method 'gfs:listGrants': Error: 403 Forbidden: manage_acl_required")
++ new Error(
++ "Error invoking remote method 'gfs:listGrants': Error: 403 Forbidden: manage_acl_required"
++ )
+ )
+
+ expect(presentation).toEqual({
+ code: 'manage_acl_required',
+ message: 'Only people with manage access can view who has access here.',
+ severity: 'quiet',
+ })
+ })
+
+ it('maps subjects_invalid without indexes', () => {
+ expect(describeGfsGrantError(new Error('400 Bad Request: subjects_invalid'))).toEqual({
+ code: 'subjects_invalid',
+ message: 'Some selected subjects are invalid and were rejected.',
+ severity: 'error',
+ })
+ })
+
+ it('appends 1-based subject positions when subjects_invalid carries invalidIndexes', () => {
+ // The exact message the main process now produces: the ApiError message with
+ // the appended `invalidIndexes=[…]` the server sent as a separate body field.
+ const presentation = describeGfsGrantError(
+ new Error(
+ "Error invoking remote method 'gfs:grant': Error: 400 Bad Request: subjects_invalid invalidIndexes=[0,2]"
+ )
+ )
+
+ expect(presentation).toEqual({
+ code: 'subjects_invalid',
+ message: 'Some selected subjects are invalid and were rejected. (subjects 1, 3)',
+ severity: 'error',
+ })
+ })
+
+ it('maps 429 with retryAfterSeconds into the retry message', () => {
+ // rate-limit body is `{ error: 'Too Many Requests', retryAfterSeconds }`; the
+ // main process appends `retryAfterSeconds=…` from the dropped body field.
+ const presentation = describeGfsGrantError(
+ new Error(
+ "Error invoking remote method 'gfs:grant': Error: 429 Too Many Requests: Too Many Requests retryAfterSeconds=42"
+ )
+ )
+
+ expect(presentation).toEqual({
+ code: 'rate_limited',
+ message: 'Too many permission changes — try again in 42s.',
+ severity: 'error',
+ })
+ })
+
+ it('maps 429 without a parseable retryAfterSeconds to the generic retry message', () => {
+ const presentation = describeGfsGrantError(new Error('429 Too Many Requests'))
+
+ expect(presentation).toEqual({
+ code: 'rate_limited',
+ message: 'Too many permission changes — try again shortly.',
+ severity: 'error',
+ })
+ })
+
+ it('does not treat an id containing 429 as a rate limit', () => {
+ const presentation = describeGfsGrantError(new Error('resource res-4290 not found'))
+
+ expect(presentation).toEqual({
+ code: null,
+ message: 'resource res-4290 not found',
+ severity: 'error',
+ })
+ })
+
+ it('passes unknown errors through verbatim — fail loud, never swallow', () => {
+ expect(describeGfsGrantError(new Error('total surprise'))).toEqual({
+ code: null,
+ message: 'total surprise',
+ severity: 'error',
+ })
+ expect(describeGfsGrantError('string failure')).toEqual({
+ code: null,
+ message: 'string failure',
+ severity: 'error',
+ })
+ })
+ })
diff --cc desktop-app/ui/src/pages/FilesPage.tsx
index f7f56e134,8e75585ae..8c9ed6df9
--- a/desktop-app/ui/src/pages/FilesPage.tsx
+++ b/desktop-app/ui/src/pages/FilesPage.tsx
@@@ -15,11 -15,17 +15,17 @@@ import
import { desktopQueryKeys } from '@hooks/domain/queryKeys'
import { useGfsBrowserController } from '@hooks/domain/useGfsBrowserController'
import { assertGfsFileUploadSize } from '@lib/gfsFileUpload'
+ import { describeGfsGrantError } from '@lib/gfsGrantErrors'
import { gfsImagePreviewMimeType } from '@lib/gfsImagePreview'
import { isGfsMarkdownPreviewFile } from '@lib/gfsMarkdownPreview'
- import { GfsSubjectBatchError, runGfsSubjectBatch } from '@lib/gfsSubjectBatch'
import { formatSharedFileSize } from '@lib/sharedFiles'
- import { GfsDelegationPanel, type GfsDelegationSubjectOption } from '@/gfs/delegation'
++import { GfsAgentAccessSection } from '@/gfs/GfsAgentAccessSection'
++import { GfsGrantList } from '@/gfs/GfsGrantList'
+ import {
- GfsDelegationPanel,
+ type GfsAgentSubjectOption,
++ GfsDelegationPanel,
+ type GfsDelegationSubjectOption,
+ } from '@/gfs/delegation'
-import { GfsAgentAccessSection } from '@/gfs/GfsAgentAccessSection'
-import { GfsGrantList } from '@/gfs/GfsGrantList'
import { GfsFilePicker } from '@/gfs/filePicker'
import { normalizeGfsResourceName } from '@/gfs/resourceName'
import type { TeamDirectoryResult } from '../../../src/types'
@@@ -129,6 -151,21 +151,18 @@@ export function FilesPage({ pushToast }
() => delegationSubjectOptions(teamDirectoryQuery.data),
[teamDirectoryQuery.data]
)
+ // MY agents (with canonical gfsSubject) load when the Manage dialog opens:
+ // they feed both the agent grant section and grant-list label resolution.
+ const myAgentsQuery = useQuery({
+ queryKey: desktopQueryKeys.myAgents,
+ queryFn: () => window.clerum.agents.listMine(),
+ enabled: manageOpen,
+ })
- const agentSubjects = useMemo(
- () => agentSubjectOptions(myAgentsQuery.data),
- [myAgentsQuery.data]
- )
++ const agentSubjects = useMemo(() => agentSubjectOptions(myAgentsQuery.data), [myAgentsQuery.data])
+ const grantsError = useMemo(
+ () => (ctrl.grantsError ? describeGfsGrantError(ctrl.grantsError) : null),
+ [ctrl.grantsError]
+ )
const canWriteCurrent = hasBit(affordances, 'write')
const canDeleteCurrent = hasBit(affordances, 'delete')
const currentIsFolder = current?.kind === 'directory'
@@@ -949,6 -1004,24 +1001,26 @@@
<p className="muted">Loading permissions…</p>
)}
</section>
+
+ <section className="da-gfs-manage-section da-gfs-manage-section--grants">
+ <div className="da-gfs-manage-section__header">
+ <div>
+ <h4>Who has access</h4>
- <p className="muted">Existing grants on this resource. Revoking is immediate.</p>
++ <p className="muted">
++ Existing grants on this resource. Revoking is immediate.
++ </p>
+ </div>
+ </div>
+ <GfsGrantList
+ agents={agentSubjects}
+ error={grantsError}
+ items={ctrl.grants}
+ loading={ctrl.loadingGrants}
+ onRevoke={(item, label) => void handleRevokeGrant(item.id, label)}
+ revoking={ctrl.revoking}
+ subjects={delegationSubjects}
+ />
+ </section>
</div>
</section>
</div>
diff --cc desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
index 90ecb3093,5ef32fb7d..587080184
--- a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
@@@ -710,6 -718,305 +718,302 @@@ describe('FilesPage', () =>
expect(screen.queryByPlaceholderText(/uuid/i)).toBeNull()
})
+ it('loads my agents when the manage dialog opens and offers only valid gfs subjects', async () => {
+ const listMine = vi.fn(async () => [
+ {
+ name: 'chatllm',
+ contextRef: 'ctx-1',
+ mcpServers: [],
+ gfsSubject: { type: 'host', id: '1st:mcp-host/chatllm' },
+ },
+ // No canonical gfsSubject yet — not a grantable delegation target.
+ { name: 'pending-agent', contextRef: null, mcpServers: [] },
+ ])
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: {
+ agents: { listMine },
+ team: { directory: vi.fn(async () => ({ currentTeamId: 'team-1', items: [] })) },
+ },
+ })
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ current: {
+ resourceId: 'folder-1',
+ gfsUri: 'gfs://main/folder',
+ name: 'Team folder',
+ kind: 'directory',
+ },
+ affordances: {
+ held: ['read', 'manage_acl'],
+ canDelegate: true,
+ grantableBits: ['read'],
+ canCreateShare: false,
+ },
+ })
+
+ renderFilesPage()
+ expect(listMine).not.toHaveBeenCalled()
+
+ await openManageDialog('Team folder')
+
+ await waitFor(() => expect(listMine).toHaveBeenCalledTimes(1))
+ expect(await screen.findByRole('button', { name: 'chatllm' })).toBeTruthy()
+ expect(screen.queryByRole('button', { name: 'pending-agent' })).toBeNull()
+ expect(
+ screen.getByRole('checkbox', { name: 'Include contents of this folder' })
+ ).toHaveProperty('checked', true)
+ })
+
+ it('refetches the grants list after a successful agent grant', async () => {
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: {
+ agents: {
+ listMine: vi.fn(async () => [
+ {
+ name: 'chatllm',
+ contextRef: 'ctx-1',
+ mcpServers: [],
+ gfsSubject: { type: 'host', id: '1st:mcp-host/chatllm' },
+ },
+ ]),
+ },
+ team: { directory: vi.fn(async () => ({ currentTeamId: 'team-1', items: [] })) },
+ },
+ })
+ const grant = vi.fn(async () => undefined)
+ const refreshGrants = 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', 'write', 'manage_acl'],
+ canDelegate: true,
+ grantableBits: ['read', 'write'],
+ canCreateShare: false,
+ },
+ grant,
+ refreshGrants,
+ })
+
+ renderFilesPage(pushToast)
+ await openManageDialog('Team folder')
+
+ fireEvent.click(await screen.findByRole('button', { name: 'chatllm' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Grant agent access' }))
+
+ await waitFor(() =>
+ expect(grant).toHaveBeenCalledWith(['host:1st:mcp-host/chatllm'], ['read'], true)
+ )
+ await waitFor(() => expect(refreshGrants).toHaveBeenCalledTimes(1))
+ expect(pushToast).toHaveBeenCalledWith('Access granted to 1 agent', 'success')
+ })
+
+ it('refetches the grants list after a successful user or team grant', 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: [
+ {
+ id: 'user-2',
+ email: '[email protected]',
+ name: 'Test Two',
+ role: 'member',
+ status: 'active',
+ },
+ ],
+ contextIds: [],
+ agentNames: [],
+ },
+ ],
+ })),
+ },
+ },
+ })
+ const grant = vi.fn(async () => undefined)
+ const refreshGrants = 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'],
+ canDelegate: true,
+ grantableBits: ['read'],
+ canCreateShare: false,
+ },
+ grant,
+ refreshGrants,
+ })
+
+ renderFilesPage(pushToast)
+ await openManageDialog('Team folder')
+
+ const subjectPicker = await screen.findByRole('combobox', { name: 'Add people or teams' })
+ fireEvent.focus(subjectPicker)
+ fireEvent.click(await screen.findByRole('option', { name: /Test Two/ }))
+ fireEvent.click(screen.getByRole('button', { name: 'Grant access' }))
+
+ // handleGrant issues the grant then MUST list-after-write (the grant PUT
+ // returns no ids). Deleting `await ctrl.refreshGrants()` must fail here.
+ await waitFor(() => expect(grant).toHaveBeenCalledWith(['user:user-2'], ['read']))
+ await waitFor(() => expect(refreshGrants).toHaveBeenCalledTimes(1))
+ expect(pushToast).toHaveBeenCalledWith('Access granted to 1 subject', 'success')
+ })
+
+ it('issues ONE atomic bulk grant and does not refetch or toast when it is rejected', 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: [
+ {
+ id: 'user-2',
+ email: '[email protected]',
+ name: 'Test Two',
+ role: 'member',
+ status: 'active',
+ },
+ {
+ id: 'user-3',
+ email: '[email protected]',
+ name: 'Test Three',
+ role: 'member',
+ status: 'active',
+ },
+ ],
+ contextIds: [],
+ agentNames: [],
+ },
+ ],
+ })),
+ },
+ },
+ })
+ // The bulk grant is atomic: the whole request is rejected, so NOTHING landed.
+ // No success toast, and no list-after-write (there is nothing new to reveal).
+ const grant = vi.fn().mockRejectedValue(new Error('400 Bad Request: subjects_invalid'))
+ const refreshGrants = 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'],
+ canDelegate: true,
+ grantableBits: ['read'],
+ canCreateShare: false,
+ },
+ grant,
+ refreshGrants,
+ })
+
+ renderFilesPage(pushToast)
+ await openManageDialog('Team folder')
+
+ const subjectPicker = await screen.findByRole('combobox', { name: 'Add people or teams' })
+ fireEvent.focus(subjectPicker)
+ fireEvent.click(await screen.findByRole('option', { name: /Test Two/ }))
+ fireEvent.click(await screen.findByRole('option', { name: /Test Three/ }))
+ fireEvent.click(screen.getByRole('button', { name: 'Grant access' }))
+
+ await waitFor(() =>
+ expect(grant).toHaveBeenCalledWith(['user:user-2', 'user:user-3'], ['read'])
+ )
+ expect(grant).toHaveBeenCalledTimes(1)
+ // The panel maps the verdict; no partial-success toast, no list-after-write.
+ await screen.findByText('Some selected subjects are invalid and were rejected.')
+ expect(refreshGrants).not.toHaveBeenCalled()
- expect(pushToast).not.toHaveBeenCalledWith(
- expect.stringContaining('Access granted'),
- 'success'
- )
++ expect(pushToast).not.toHaveBeenCalledWith(expect.stringContaining('Access granted'), 'success')
+ })
+
+ it('revokes a grant from the who-has-access list and toasts the outcome', async () => {
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: {
+ agents: {
+ listMine: vi.fn(async () => [
+ {
+ name: 'chatllm',
+ contextRef: 'ctx-1',
+ mcpServers: [],
+ gfsSubject: { type: 'host', id: '1st:mcp-host/chatllm' },
+ },
+ ]),
+ },
+ team: { directory: vi.fn(async () => ({ currentTeamId: 'team-1', items: [] })) },
+ },
+ })
+ const revokeGrant = 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'],
+ canDelegate: true,
+ grantableBits: ['read'],
+ canCreateShare: false,
+ },
+ grants: [
+ {
+ id: 'grant-1',
+ drive: 'main',
+ resourceId: 'folder-1',
+ subject: { type: 'host', id: '1st:mcp-host/chatllm' },
+ permissions: ['read'],
+ inherit: true,
+ },
+ ],
+ revokeGrant,
+ })
+
+ renderFilesPage(pushToast)
+ await openManageDialog('Team folder')
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Revoke access for chatllm' }))
+
+ await waitFor(() => expect(revokeGrant).toHaveBeenCalledWith('grant-1'))
+ await waitFor(() =>
+ expect(pushToast).toHaveBeenCalledWith('Access revoked for chatllm', 'success')
+ )
+ })
+
it('refreshes server affordances whenever the manage dialog opens', async () => {
const refreshAffordances = vi.fn(async () => undefined)
hookMock.useGfsBrowserController.mockReturnValue({
diff --cc external-rest-api/package-lock.json
index 871b290e7,871b290e7..9472695cf
--- a/external-rest-api/package-lock.json
+++ b/external-rest-api/package-lock.json
@@@ -1,12 -1,12 +1,12 @@@
{
"name": "clerum-external-rest-api",
-- "version": "0.1.59",
++ "version": "0.1.60",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-external-rest-api",
-- "version": "0.1.59",
++ "version": "0.1.60",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.21.2",
diff --cc external-rest-api/package.json
index 9e20ce21e,9e20ce21e..355c471dc
--- a/external-rest-api/package.json
+++ b/external-rest-api/package.json
@@@ -1,6 -1,6 +1,6 @@@
{
"name": "clerum-external-rest-api",
-- "version": "0.1.59",
++ "version": "0.1.60",
"description": "External REST API for profile, team management, and RPC token brokerage",
"main": "dist/main.js",
"engines": {
diff --cc host-context-controller/package-lock.json
index 854e35948,854e35948..2e04d1e84
--- a/host-context-controller/package-lock.json
+++ b/host-context-controller/package-lock.json
@@@ -1,12 -1,12 +1,12 @@@
{
"name": "clerum-host-context-controller",
-- "version": "0.1.157",
++ "version": "0.1.158",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
-- "version": "0.1.157",
++ "version": "0.1.158",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@clerum/image-policy": "file:../packages/image-policy",
diff --cc host-context-controller/package.json
index 0fc08aae0,0fc08aae0..32eca539e
--- a/host-context-controller/package.json
+++ b/host-context-controller/package.json
@@@ -1,6 -1,6 +1,6 @@@
{
"name": "clerum-host-context-controller",
-- "version": "0.1.157",
++ "version": "0.1.158",
"description": "Host Context Controller - provides McpServer CRDs to mcp-host via REST API",
"main": "dist/main.js",
"engines": {
diff --cc host-context-controller/src/gfsConfig.ts
index f0a7b66f1,1c8760c14..331e43599
--- a/host-context-controller/src/gfsConfig.ts
+++ b/host-context-controller/src/gfsConfig.ts
@@@ -60,8 -60,16 +60,13 @@@ export function gfsDefaultFactoryConfig
jwtPublicKeyConfigMapKey: env('CONTEXT_MAPPER_GFS_JWT_CONFIGMAP_KEY', 'jwt-public-key'),
pgSecretName: env('CONTEXT_MAPPER_GFS_PG_SECRET', 'gfs-controller-db'),
pgSecretKey: env('CONTEXT_MAPPER_GFS_PG_SECRET_KEY', 'connection-string'),
- readerPgSecretName: env(
- 'CONTEXT_MAPPER_GFS_READER_PG_SECRET',
- 'gfs-controller-reader-db'
- ),
++ readerPgSecretName: env('CONTEXT_MAPPER_GFS_READER_PG_SECRET', 'gfs-controller-reader-db'),
+ readerPgSecretKey: env('CONTEXT_MAPPER_GFS_READER_PG_SECRET_KEY', 'connection-string'),
driveName: env('CONTEXT_MAPPER_GFS_DRIVE_NAME', 'main'),
tokenAudience: env('CONTEXT_MAPPER_GFS_TOKEN_AUDIENCE', 'gfs-controller'),
+ syncCopyMaxObjects: process.env.GFS_SYNC_COPY_MAX_OBJECTS,
+ syncCopyMaxBytes: process.env.GFS_SYNC_COPY_MAX_BYTES,
+ syncCopyTimeoutMs: process.env.GFS_SYNC_COPY_TIMEOUT_MS,
nodeLocalDnsCidr: parseNodeLocalDnsCidr(env('CONTEXT_MAPPER_NODELOCAL_DNS_CIDR', '')),
}
}
diff --cc host-context-controller/src/gfsHostSubject.test.ts
index 000000000,6de4b5e9a..68d1bfb09
mode 000000,100644..100644
--- a/host-context-controller/src/gfsHostSubject.test.ts
+++ b/host-context-controller/src/gfsHostSubject.test.ts
@@@ -1,0 -1,48 +1,45 @@@
++import { describe, expect, it } from 'vitest'
+ import { readFileSync } from 'node:fs'
+ import path from 'node:path'
-import { describe, expect, it } from 'vitest'
+ import { makeExpectedHostGfsSubject } from './gfsHostSubject'
+
+ type HostSubjectVector = {
+ label: string
+ namespace: string
+ name: string
+ displayText: string
+ expectedSubjectId: string | null
+ expectedSubject: string | null
+ }
+
+ const vectors = JSON.parse(
- readFileSync(
- path.join(__dirname, '../../tests/contracts/gfs-host-subject-vectors.json'),
- 'utf8'
- )
++ readFileSync(path.join(__dirname, '../../tests/contracts/gfs-host-subject-vectors.json'), 'utf8')
+ ) as HostSubjectVector[]
+
+ describe('makeExpectedHostGfsSubject', () => {
+ it.each(vectors)('matches the Control API identity contract: $label', vector => {
+ const actual = makeExpectedHostGfsSubject(vector.namespace, vector.name)
+
+ expect(actual).toBe(vector.expectedSubject)
+ if (actual) {
+ expect(actual).toBe(`host:${vector.expectedSubjectId}`)
+ expect(actual).not.toContain(vector.displayText)
+ }
+ })
+
+ it('does not accept display text in place of trusted metadata.name', () => {
+ const vector = vectors.find(candidate => candidate.expectedSubject !== null)
+ expect(vector).toBeDefined()
+ expect(makeExpectedHostGfsSubject(vector!.namespace, vector!.displayText)).toBeNull()
+ })
+
+ it('reserves the legacy fleet-wide standalone subject without rejecting standalone elsewhere', () => {
+ expect(makeExpectedHostGfsSubject('mcp-host', 'standalone')).toBeNull()
+ expect(makeExpectedHostGfsSubject('sandbox-recipes', 'standalone')).toBe(
+ 'host:1st:sandbox-recipes/standalone'
+ )
+ expect(makeExpectedHostGfsSubject('mcp-host', 'standalone-worker')).toBe(
+ 'host:1st:mcp-host/standalone-worker'
+ )
+ })
+ })
diff --cc host-context-controller/src/hostReconciler.ts
index 6d5b3edf3,c9251dece..5bf92cfa6
--- a/host-context-controller/src/hostReconciler.ts
+++ b/host-context-controller/src/hostReconciler.ts
@@@ -19,6 -21,6 +21,13 @@@ import
} from './k8s/sharedFileSystemFactory'
import { hccLogger } from './logger'
import { issueMcpHostRuntimeTokens } from './mcpHostRuntimeTokenIssuerClient'
++import {
++ hostCleanupDeferredTotal,
++ hostDeleteCleanupTotal,
++ hostReconcileDurationSeconds,
++ hostReconcileInFlight,
++ hostReconcileQueueWaitSeconds,
++} from './metrics'
import {
MCP_HOST_GFS_TOKEN_SECRET_KEY,
MCP_HOST_RUNTIME_TOKEN_SECRET_ACCESS_KEY,
@@@ -50,13 -52,13 +59,6 @@@ import
preserveServiceAssignedFields,
replaceWithConflictRetry,
} from './utils'
--import {
-- hostCleanupDeferredTotal,
-- hostDeleteCleanupTotal,
-- hostReconcileDurationSeconds,
-- hostReconcileInFlight,
-- hostReconcileQueueWaitSeconds,
--} from './metrics'
export type { EffectiveHostLifecycle } from './statelessLifecycle.types'
@@@ -3886,7 -3978,7 +3978,8 @@@ export class HostReconciler
if (!authorityValid()) {
const current = this.hostWatchAuthority()
-- const reason = !capturedAuthority.known || !current.known ? 'authority_unknown' : 'generation_changed'
++ const reason =
++ !capturedAuthority.known || !current.known ? 'authority_unknown' : 'generation_changed'
hostCleanupDeferredTotal.inc({ reason })
console.warn(`[HostReconciler] Deferring orphan cleanup: ${reason}`)
return failures
@@@ -4046,7 -4138,7 +4139,10 @@@
try {
const list = await this.coreApi.listNamespacedSecret({
namespace: channelsNs,
-- labelSelector: [`${MANAGED_BY_LABEL}=${MANAGED_BY_VALUE}`, 'clerum.io/component=channel-reader'].join(','),
++ labelSelector: [
++ `${MANAGED_BY_LABEL}=${MANAGED_BY_VALUE}`,
++ 'clerum.io/component=channel-reader',
++ ].join(','),
})
for (const sec of list.items ?? []) {
const labels = sec.metadata?.labels
@@@ -4175,7 -4267,7 +4271,6 @@@
})
return (response.items || []).filter(item => item.metadata?.labels?.[HOST_LABEL])
}
--
}
function canonicalStringify(obj: Record<string, unknown>): string {
diff --cc host-context-controller/src/k8s/gfsFactory.ts
index d4d6c40da,a93a21a21..81430d656
--- a/host-context-controller/src/k8s/gfsFactory.ts
+++ b/host-context-controller/src/k8s/gfsFactory.ts
@@@ -249,6 -256,18 +256,17 @@@ export function buildPvc
}
function gfscEnv(config: GfsFactoryConfig, role: GfscRole): k8s.V1EnvVar[] {
- const pgSecretName =
- role === 'writer' ? config.pgSecretName : config.readerPgSecretName
++ const pgSecretName = role === 'writer' ? config.pgSecretName : config.readerPgSecretName
+ const pgSecretKey = role === 'writer' ? config.pgSecretKey : config.readerPgSecretKey
+ const copyEnvEntries: ReadonlyArray<readonly [string, string | undefined]> = [
+ ['GFS_SYNC_COPY_MAX_OBJECTS', config.syncCopyMaxObjects],
+ ['GFS_SYNC_COPY_MAX_BYTES', config.syncCopyMaxBytes],
+ ['GFS_SYNC_COPY_TIMEOUT_MS', config.syncCopyTimeoutMs],
+ ]
+ const copyEnv = copyEnvEntries.flatMap(([name, value]): k8s.V1EnvVar[] =>
+ value === undefined ? [] : [{ name, value }]
+ )
+
return [
{ name: 'GFS_PORT', value: String(config.gfscPort) },
{ name: 'GFS_STORAGE_PATH', value: GFS_MOUNT_PATH },
diff --cc host-context-controller/src/k8sClient.test.ts
index 281d44568,c4f573f0e..375a37333
--- a/host-context-controller/src/k8sClient.test.ts
+++ b/host-context-controller/src/k8sClient.test.ts
@@@ -2370,9 -2399,9 +2399,10 @@@ describe('McpServerWatcher Host periodi
order.push(`watch:${host.name}:${host.generation}`)
})
await (watcher as any).startHostWatch('test-host-rv')
-- if (!hostWatchCallback) throw new Error('Host watch callback was not installed')
-- // Cache already synced: the full pass blocks purely on the mocked
-- // fullReconcile and does not drive recovery, isolating admission behavior.
++ if (!hostWatchCallback)
++ throw new Error('Host watch callback was not installed')
++ // Cache already synced: the full pass blocks purely on the mocked
++ // fullReconcile and does not drive recovery, isolating admission behavior.
;(watcher as any).hostCacheSynced = true
const full = (watcher as any).requestHostFleetReconcile(
@@@ -2446,11 -2475,11 +2476,7 @@@
spec: { host: 'same-host' },
})
-- expect(order).toEqual([
-- 'reconcile:same-host:1',
-- 'reconcile:same-host:2',
-- 'delete:same-host',
-- ])
++ expect(order).toEqual(['reconcile:same-host:1', 'reconcile:same-host:2', 'delete:same-host'])
expect((watcher as any).hosts.has('same-host')).toBe(false)
watcher.stop()
})
@@@ -2942,6 -2971,7 +2968,10 @@@ describe('McpServerWatcher Host watch g
spec: { host: 'retry-host', lifecycle: { stateless: true } },
})
expect(reconcile).toHaveBeenCalledOnce()
- expect(reconcile).toHaveBeenCalledWith(expect.objectContaining({ uid: 'retry-host-uid' }), 'urgent')
++ expect(reconcile).toHaveBeenCalledWith(
++ expect.objectContaining({ uid: 'retry-host-uid' }),
++ 'urgent'
++ )
expect((watcher as any).hostWatchRetryTimers.size).toBe(1)
expect((watcher as any).latestHostWatchEventRevisions.size).toBe(1)
@@@ -3199,11 -3230,11 +3230,7 @@@
expect(reconcileDelete).toHaveBeenCalledWith('gone-host', 'mcp-host', expect.anything())
)
// A Host still present in the fresh snapshot is never deleted.
-- expect(reconcileDelete).not.toHaveBeenCalledWith(
-- 'live-host',
-- 'mcp-host',
-- expect.anything()
-- )
++ expect(reconcileDelete).not.toHaveBeenCalledWith('live-host', 'mcp-host', expect.anything())
watcher.stop()
})
@@@ -3291,7 -3322,7 +3318,12 @@@
it('suppresses a watch event whose identity (uid) differs from the cached Host (#827 item 2)', () => {
const watcher = new McpServerWatcher()
-- ;(watcher as any).hosts.set('x', { name: 'x', namespace: 'mcp-host', uid: 'uid-B', generation: 3 })
++ ;(watcher as any).hosts.set('x', {
++ name: 'x',
++ namespace: 'mcp-host',
++ uid: 'uid-B',
++ generation: 3,
++ })
;(watcher as any).latestHostWatchEventRevisions.set('x', 7)
// A stale MODIFIED carrying the OLD identity must not act on the recreated one.
expect(
@@@ -3349,10 -3380,10 +3381,7 @@@
new Map([['waker', 'u1']]) // NOT recreated (same uid)
)
await vi.waitFor(() =>
-- expect(reconcile).toHaveBeenCalledWith(
-- expect.objectContaining({ name: 'waker' }),
-- 'urgent'
-- )
++ expect(reconcile).toHaveBeenCalledWith(expect.objectContaining({ name: 'waker' }), 'urgent')
)
watcher.stop()
})
@@@ -3374,7 -3405,7 +3403,15 @@@
spec: { host: 'steady' },
})
;(watcher as any).enqueueRecoveredUrgentHosts(
-- [{ name: 'steady', namespace: 'mcp-host', uid: 'u1', generation: 4, spec: { host: 'steady' } }],
++ [
++ {
++ name: 'steady',
++ namespace: 'mcp-host',
++ uid: 'u1',
++ generation: 4,
++ spec: { host: 'steady' },
++ },
++ ],
new Set(['steady']),
new Map([['steady', 4]]),
new Map([['steady', 'u1']])
diff --cc host-context-controller/test/hostReconciler.heartbeat.test.ts
index eb28006b4,6d9918a16..4e6593024
--- a/host-context-controller/test/hostReconciler.heartbeat.test.ts
+++ b/host-context-controller/test/hostReconciler.heartbeat.test.ts
@@@ -439,7 -439,7 +439,8 @@@ describe('HostReconciler.publishSuspend
lifecycle: {
state: 'active',
wakeHandledGeneration: 0,
-- reason: '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',
++ reason:
++ '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',
},
},
})
@@@ -452,7 -452,7 +453,8 @@@
freshHostRead({
state: 'active',
wakeHandledGeneration: 0,
-- reason: '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',
++ reason:
++ '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',
})
)
diff --cc host-context-controller/test/hostReconciler.lifecycle.test.ts
index c8d653513,3bd808b44..d624bf4e2
--- a/host-context-controller/test/hostReconciler.lifecycle.test.ts
+++ b/host-context-controller/test/hostReconciler.lifecycle.test.ts
@@@ -793,7 -793,7 +793,8 @@@ describe('HostReconciler stateless life
expect(writes[1].lifecycle).toEqual({
state: 'active',
wakeHandledGeneration: 5,
-- reason: '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',
++ reason:
++ '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',
})
expect(rejectedCondition(writes[1])).toMatchObject({
status: 'True',
@@@ -872,7 -872,7 +873,8 @@@
expect(writes[1].lifecycle).toEqual({
state: 'active',
wakeHandledGeneration: 6,
-- reason: '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',
++ reason:
++ '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',
})
})
@@@ -988,7 -988,7 +990,9 @@@
)
const writes = lifecycleStatusWrites(customApi)
expect(writes).toHaveLength(2)
-- expect(writes[1].lifecycle?.reason).toBe('1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle')
++ expect(writes[1].lifecycle?.reason).toBe(
++ '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle'
++ )
})
it('does not repeat bootstrap provisioning when channel ingress already existed in spec', async () => {
@@@ -1388,7 -1388,7 +1392,8 @@@ describe('HostReconciler stateless life
expect(writes[0].lifecycle).toEqual({
state: 'active',
wakeHandledGeneration: 3,
-- reason: '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',
++ reason:
++ '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',
})
expect(rejectedCondition(writes[0]).status).toBe('True')
})
@@@ -1602,7 -1602,7 +1607,8 @@@ describe('HostReconciler stateless life
expect(writes.at(-1)?.lifecycle).toEqual({
state: 'active',
wakeHandledGeneration: 3,
-- reason: '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',
++ reason:
++ '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',
})
})
@@@ -1630,7 -1630,7 +1636,8 @@@
expect(writes.at(-1)?.lifecycle).toEqual({
state: 'active',
wakeHandledGeneration: 2,
-- reason: '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',
++ reason:
++ '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',
})
})
@@@ -1656,7 -1656,7 +1663,8 @@@
expect(writes.at(-1)?.lifecycle).toEqual({
state: 'suspended',
wakeHandledGeneration: 5,
-- reason: '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',
++ reason:
++ '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',
})
})
diff --cc host-context-controller/test/hostReconciler.test.ts
index dbe54f200,d250cf53e..ccb55d3a8
--- a/host-context-controller/test/hostReconciler.test.ts
+++ b/host-context-controller/test/hostReconciler.test.ts
@@@ -1,6 -1,6 +1,7 @@@
import { describe, expect, it, vi } from 'vitest'
import * as k8s from '@kubernetes/client-node'
import type { AdministrativeOutcomeReporter } from '../src/administrativeOutcomeReporter'
++import { mintHostGfsToken } from '../src/gfsHostBinding'
import {
DEFAULT_FIRST_PARTY_WORKFLOW_CONTROL_SCOPES,
HostReconciler,
diff --cc mcp-host/package-lock.json
index 39fc80840,39fc80840..f488d15a3
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@@ -1,12 -1,12 +1,12 @@@
{
"name": "clerum-mcp-host",
-- "version": "0.1.209",
++ "version": "0.1.210",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
-- "version": "0.1.209",
++ "version": "0.1.210",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@anthropic-ai/sdk": "^0.32.0",
diff --cc mcp-host/package.json
index 720639769,720639769..076738265
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@@ -1,6 -1,6 +1,6 @@@
{
"name": "clerum-mcp-host",
-- "version": "0.1.209",
++ "version": "0.1.210",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --cc mcp-host/src/internalTools/gfs.test.ts
index ae59db460,ab15d5eff..ed2b8d154
--- a/mcp-host/src/internalTools/gfs.test.ts
+++ b/mcp-host/src/internalTools/gfs.test.ts
@@@ -123,4 -156,114 +156,121 @@@ describe('buildGfsWriteTools (P4)', ()
expect(r.error).toMatch(/If-Match/i)
expect(c.write).not.toHaveBeenCalled()
})
+
+ it.each([
- [
- 'clerum__gfs_write',
- { drive: 'main', resourceId: 'abc', content: 'hi' },
- ],
- [
- 'clerum__gfs_rename',
- { drive: 'main', resourceId: 'abc', newName: 'renamed.txt' },
- ],
++ ['clerum__gfs_write', { drive: 'main', resourceId: 'abc', content: 'hi' }],
++ ['clerum__gfs_rename', { drive: 'main', resourceId: 'abc', newName: 'renamed.txt' }],
+ [
+ 'clerum__gfs_copy',
+ { drive: 'main', sourceResourceId: 'source', destinationParentId: 'destination' },
+ ],
+ ])('rejects invalid If-Match values before %s reaches gfsc', async (name, baseArgs) => {
+ for (const ifMatch of [Number.NaN, -1, 1.5, Number.MAX_SAFE_INTEGER + 1]) {
+ const c = writeClient()
+ const tools = new Map(
+ [...buildGfsWriteTools(c), ...buildGfsCopyTools(c)].map(tool => [tool.name, tool])
+ )
+ const result = await tools.get(name)!.execute({ ...baseArgs, ifMatch }, '')
+ expect(result.success).toBe(false)
+ expect(result.error).toMatch(/non-negative safe-integer If-Match/)
+ expect(c.write).not.toHaveBeenCalled()
+ expect(c.rename).not.toHaveBeenCalled()
+ expect(c.copy).not.toHaveBeenCalled()
+ }
+ })
+
+ it('passes create and rename payloads without exposing move fields', async () => {
+ const c = writeClient()
+ const tools = new Map(buildGfsWriteTools(c).map(tool => [tool.name, tool]))
- await tools.get('clerum__gfs_create_file')!.execute(
- { drive: 'main', parentResourceId: 'parent', name: 'note.txt', content: 'hello' },
- ''
- )
- await tools.get('clerum__gfs_create_folder')!.execute(
- { drive: 'main', parentResourceId: 'parent', name: 'docs' },
- ''
- )
- await tools.get('clerum__gfs_rename')!.execute(
- { drive: 'main', resourceId: 'abc', newName: 'renamed.txt', ifMatch: 4 },
- ''
- )
++ await tools
++ .get('clerum__gfs_create_file')!
++ .execute(
++ { drive: 'main', parentResourceId: 'parent', name: 'note.txt', content: 'hello' },
++ ''
++ )
++ await tools
++ .get('clerum__gfs_create_folder')!
++ .execute({ drive: 'main', parentResourceId: 'parent', name: 'docs' }, '')
++ await tools
++ .get('clerum__gfs_rename')!
++ .execute({ drive: 'main', resourceId: 'abc', newName: 'renamed.txt', ifMatch: 4 }, '')
+ expect(c.createFile).toHaveBeenCalledWith({
- drive: 'main', parentResourceId: 'parent', name: 'note.txt', content: 'hello',
++ drive: 'main',
++ parentResourceId: 'parent',
++ name: 'note.txt',
++ content: 'hello',
+ })
+ expect(c.createFolder).toHaveBeenCalledWith({
- drive: 'main', parentResourceId: 'parent', name: 'docs',
++ drive: 'main',
++ parentResourceId: 'parent',
++ name: 'docs',
+ })
+ expect(c.rename).toHaveBeenCalledWith({
- drive: 'main', resourceId: 'abc', newName: 'renamed.txt', ifMatch: 4,
++ drive: 'main',
++ resourceId: 'abc',
++ newName: 'renamed.txt',
++ ifMatch: 4,
+ })
+ expect(tools.has('clerum__gfs_move')).toBe(false)
+ expect(tools.has('clerum__gfs_delete')).toBe(false)
+ })
+
+ it('copies through one server-side call with the exact root contract', async () => {
+ const c = writeClient()
+ const tool = buildGfsCopyTools(c)[0]!
+ expect(tool.description).toContain('The original remains at the source')
+ expect(tool.description).toContain('never deletes it')
+ const args = {
- drive: 'main', sourceResourceId: 'source', destinationParentId: 'destination',
- newName: 'source-copy', ifMatch: 7,
++ drive: 'main',
++ sourceResourceId: 'source',
++ destinationParentId: 'destination',
++ newName: 'source-copy',
++ ifMatch: 7,
+ }
+ const result = await tool.execute(args, '')
+ expect(result.success).toBe(true)
+ expect(c.copy).toHaveBeenCalledTimes(1)
+ expect(c.copy).toHaveBeenCalledWith(args)
+ expect(c.read).not.toHaveBeenCalled()
+ expect(c.write).not.toHaveBeenCalled()
+ })
+
+ it('does not expose backend paths or keys in mutation failures', async () => {
+ const c = writeClient({
- copy: vi.fn(async () => { throw new Error('failed at /mnt/gfs/private/blob-key') }),
++ copy: vi.fn(async () => {
++ throw new Error('failed at /mnt/gfs/private/blob-key')
++ }),
+ })
+ const result = await buildGfsCopyTools(c)[0]!.execute(
+ { drive: 'main', sourceResourceId: 'source', destinationParentId: 'destination', ifMatch: 7 },
+ ''
+ )
+ expect(result).toEqual({ success: false, error: 'GFS mutation failed' })
+ })
+
+ it.each([
+ [403, 'forbidden'],
+ [409, 'conflict'],
+ [412, 'precondition_failed'],
+ [413, 'limit_exceeded'],
+ [503, 'unavailable'],
+ ])('preserves safe gfsc status/category for mutation failure %s', async (status, category) => {
+ const c = writeClient({
+ copy: vi.fn(async () => {
+ throw new Error(
+ `gfsc ${status}: private path=/data/gfs/.generations/secret sql=do-not-expose`
+ )
+ }),
+ })
+ const result = await buildGfsCopyTools(c)[0]!.execute(
+ { drive: 'main', sourceResourceId: 'source', destinationParentId: 'destination', ifMatch: 7 },
+ ''
+ )
+ expect(result).toEqual({
+ success: false,
+ error: `GFS mutation failed (gfsc ${status}: ${category})`,
+ })
+ expect(result.error).not.toContain('/data/')
+ expect(result.error).not.toContain('sql=')
+ })
})
diff --cc mcp-host/src/internalTools/gfsClient.test.ts
index f384431ec,dbb3e561c..a575f6355
--- a/mcp-host/src/internalTools/gfsClient.test.ts
+++ b/mcp-host/src/internalTools/gfsClient.test.ts
@@@ -28,6 -39,16 +39,17 @@@ describe('gfs runtime gfsc client', ()
).toBe(false)
})
+ it('derives only recognized GFS tool scopes and fails closed', () => {
- expect([...(getGfsToolScopes({ get: () => encodedClaims(['gfs.read', 'gfs.write']) }) ?? [])])
- .toEqual(['gfs.read', 'gfs.write'])
++ expect([
++ ...(getGfsToolScopes({ get: () => encodedClaims(['gfs.read', 'gfs.write']) }) ?? []),
++ ]).toEqual(['gfs.read', 'gfs.write'])
+ expect(getGfsToolScopes({ get: () => encodedClaims(['gfs.read', 'gfs.delete']) })).toBeNull()
+ expect(getGfsToolScopes({ get: () => encodedClaims(['gfs.delete']) })).toBeNull()
+ expect(getGfsToolScopes({ get: () => encodedClaims([]) })).toBeNull()
+ expect(getGfsToolScopes({ get: () => encodedClaims('gfs.read') })).toBeNull()
+ expect(getGfsToolScopes({ get: () => 'malformed' })).toBeNull()
+ })
+
it('calls gfsc accessible with runtime bearer auth', async () => {
const fetchFn = vi.fn(async (_input: string, _init?: RequestInit) =>
jsonResponse({ ok: true, data: { items: [] } })
@@@ -63,6 -84,47 +85,56 @@@
})
})
+ it('uses exact writer routes and bodies for create, rename, and copy', async () => {
+ const fetchFn = vi.fn(async (_input: string, _init?: RequestInit) =>
+ jsonResponse({ ok: true, data: {} })
+ )
+ const client = createGfscClient({
+ get: key => (key === 'MCP_HOST_GFS_TOKEN' ? 'gfs-access' : undefined),
+ fetch: fetchFn,
+ })
+ await client.createFile({
- drive: 'main', parentResourceId: 'parent/id', name: 'note.txt', content: 'hello',
++ drive: 'main',
++ parentResourceId: 'parent/id',
++ name: 'note.txt',
++ content: 'hello',
+ })
+ await client.createFolder({ drive: 'main', parentResourceId: 'parent/id', name: 'docs' })
+ await client.rename({
- drive: 'main', resourceId: 'source/id', newName: 'renamed.txt', ifMatch: 4,
++ drive: 'main',
++ resourceId: 'source/id',
++ newName: 'renamed.txt',
++ ifMatch: 4,
+ })
+ const copy = {
- drive: 'main', sourceResourceId: 'source', destinationParentId: 'destination',
- newName: 'source-copy', ifMatch: 7,
++ drive: 'main',
++ sourceResourceId: 'source',
++ destinationParentId: 'destination',
++ newName: 'source-copy',
++ ifMatch: 7,
+ }
+ await client.copy(copy)
+
+ expect(fetchFn.mock.calls.map(call => [call[0], call[1]?.method, call[1]?.body])).toEqual([
+ [
+ 'http://gfsc-writer.gfs.svc.cluster.local:8087/v1/resources/parent%2Fid/children?drive=main',
- 'POST', JSON.stringify({ name: 'note.txt', kind: 'file', content: 'hello' }),
++ 'POST',
++ JSON.stringify({ name: 'note.txt', kind: 'file', content: 'hello' }),
+ ],
+ [
+ 'http://gfsc-writer.gfs.svc.cluster.local:8087/v1/resources/parent%2Fid/children?drive=main',
- 'POST', JSON.stringify({ name: 'docs', kind: 'directory' }),
++ 'POST',
++ JSON.stringify({ name: 'docs', kind: 'directory' }),
+ ],
+ [
+ 'http://gfsc-writer.gfs.svc.cluster.local:8087/v1/resources/source%2Fid',
- 'PATCH', JSON.stringify({ drive: 'main', newName: 'renamed.txt', ifMatch: 4 }),
- ],
- [
- 'http://gfsc-writer.gfs.svc.cluster.local:8087/v1/copy',
- 'POST', JSON.stringify(copy),
++ 'PATCH',
++ JSON.stringify({ drive: 'main', newName: 'renamed.txt', ifMatch: 4 }),
+ ],
++ ['http://gfsc-writer.gfs.svc.cluster.local:8087/v1/copy', 'POST', JSON.stringify(copy)],
+ ])
+ })
+
it('fails loud when the mounted runtime token file is empty', async () => {
const client = createGfscClient({
get: () => undefined,
diff --cc mcp-host/src/internalTools/gfsClient.ts
index c1bf606f8,f51305c40..115cc542f
--- a/mcp-host/src/internalTools/gfsClient.ts
+++ b/mcp-host/src/internalTools/gfsClient.ts
@@@ -1,6 -1,7 +1,7 @@@
- import { existsSync } from 'node:fs'
+ import { existsSync, readFileSync } from 'node:fs'
import { readFile } from 'node:fs/promises'
-import type { GfscWriteClient } from './gfs'
+ import { decodeRuntimeJwtScopes } from '../workflow/mcpHostRuntimeJwt'
+import type { GfscWriteClient } from './gfs'
const DIRECT_KEY = 'MCP_HOST_GFS_TOKEN'
const FILE_KEY = 'MCP_HOST_GFS_TOKEN_FILE'
diff --cc mcp-host/src/workflow/mcpHostRuntimeJwt.ts
index 265ac194e,65d9c84c9..e9b8902e6
--- a/mcp-host/src/workflow/mcpHostRuntimeJwt.ts
+++ b/mcp-host/src/workflow/mcpHostRuntimeJwt.ts
@@@ -13,6 -13,24 +13,27 @@@ type RuntimeJwtClaims =
recipeName?: unknown
exp?: unknown
iat?: unknown
+ scopes?: unknown
+ }
+
+ /**
+ * Decode a runtime token's scope advertisement without treating it as an
+ * authorization decision. Callers use this only to hide tools the token can
+ * never invoke; the receiving service must still verify and authorize it.
+ */
+ export function decodeRuntimeJwtScopes(token: string): string[] | null {
+ try {
+ const payload = decodeJwt(token) as RuntimeJwtClaims
- if (!Array.isArray(payload.scopes) || !payload.scopes.every(scope => typeof scope === 'string')) {
++ if (
++ !Array.isArray(payload.scopes) ||
++ !payload.scopes.every(scope => typeof scope === 'string')
++ ) {
+ return null
+ }
+ return payload.scopes
+ } catch {
+ return null
+ }
}
export type DecodedRuntimeJwtClaims = {
diff --cc profile-ui/package-lock.json
index d4f026f22,fe34102dc..189a943d0
--- a/profile-ui/package-lock.json
+++ b/profile-ui/package-lock.json
@@@ -1,12 -1,12 +1,12 @@@
{
"name": "clerum-profile-ui",
-- "version": "0.1.104",
++ "version": "0.1.105",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-profile-ui",
-- "version": "0.1.104",
++ "version": "0.1.105",
"dependencies": {
"next": "16.2.11",
"react": "^18.3.1",
diff --cc profile-ui/package.json
index 97f4d1436,97f4d1436..f5c368b96
--- a/profile-ui/package.json
+++ b/profile-ui/package.json
@@@ -1,6 -1,6 +1,6 @@@
{
"name": "clerum-profile-ui",
-- "version": "0.1.104",
++ "version": "0.1.105",
"private": true,
"scripts": {
"dev": "next dev",
diff --cc scripts/minikube/pre-gate-sync.sh
index 34c54b329,01f7d631c..7726935e8
--- a/scripts/minikube/pre-gate-sync.sh
+++ b/scripts/minikube/pre-gate-sync.sh
@@@ -259,43 -326,50 +259,61 @@@ run_if_changed control-ui "npm test
run_if_changed desktop-app "npm test"
if [[ "${cluster_changed}" == "true" ]]; then
- log "Cluster-relevant changes detected — rebuilding and redeploying before ${GATE_NAME}"
- # Apply the canonical cluster bootstrap before any namespaced Secret work.
- (
- cd "${PROJECT_DIR}"
- make minikube-deploy-crds
- )
- CONTEXT="${PROFILE}" bash "${PROJECT_DIR}/deploy/scripts/apply-gfs-writer-secret.sh"
- writer_dsn="$(${KC} -n gfs get secret gfs-controller-db -o 'jsonpath={.data.connection-string}')"
- if [[ -n "${writer_dsn}" ]]; then
- if ! ${KC} -n control-plane rollout status deployment/control-api --timeout=5s >/dev/null 2>&1; then
- err "Existing GFS writer detected but control-api is not Ready; refusing full overlay sync"
- exit 1
+ incremental_plan
+ log "Cluster sync plan before ${GATE_NAME}: images=$(incremental_target_summary), full-image-build=${INCREMENTAL_FULL_IMAGE_BUILD}, full-deployment=${INCREMENTAL_FULL_DEPLOYMENT}"
- incremental_build_images
- (
- cd "${PROJECT_DIR}"
- # CRD changes live outside the Kustomize overlay. Apply them before the
- # service rollout when a fresh baseline or chart change requires it.
- if [[ "${INCREMENTAL_FULL_IMAGE_BUILD}" == "true" || "${INCREMENTAL_CRDS_CHANGED}" == "true" ]]; then
++
++ if [[ "${INCREMENTAL_FULL_IMAGE_BUILD}" == "true" ||
++ "${INCREMENTAL_FULL_DEPLOYMENT}" == "true" ]]; then
++ (
++ cd "${PROJECT_DIR}"
+ make minikube-deploy-crds
++ )
++ CONTEXT="${PROFILE}" bash "${PROJECT_DIR}/deploy/scripts/apply-gfs-writer-secret.sh"
++ writer_dsn="$(${KC} -n gfs get secret gfs-controller-db -o 'jsonpath={.data.connection-string}')"
++ if [[ -n "${writer_dsn}" ]]; then
++ if ! ${KC} -n control-plane rollout status deployment/control-api --timeout=5s >/dev/null 2>&1; then
++ log "ERROR: existing GFS writer detected but control-api is not Ready; refusing full overlay sync"
++ exit 1
++ fi
++ log "Upgrade path — reconciling GFS credentials before full overlay sync"
++ CONTEXT="${PROFILE}" bash "${PROJECT_DIR}/deploy/scripts/reconcile-gfs-deploy-credentials.sh"
++ else
++ log "Fresh bootstrap — reader staging deferred until post-migration convergence; GFSC remains fail-closed"
fi
- if [[ "${INCREMENTAL_FULL_IMAGE_BUILD}" == "true" || "${INCREMENTAL_FULL_DEPLOYMENT}" == "true" ]]; then
- make minikube-apply-secrets
- make minikube-deploy-all
- fi
- if [[ "${FORCE_RESTART}" == "true" || "${INCREMENTAL_FULL_IMAGE_BUILD}" == "true" ]]; then
- make minikube-restart-all
- fi
- )
- log "Upgrade path — reconciling GFS credentials before full overlay sync"
- CONTEXT="${PROFILE}" bash "${PROJECT_DIR}/deploy/scripts/reconcile-gfs-deploy-credentials.sh"
- else
- log "Fresh bootstrap — reader staging deferred until post-migration convergence; GFSC remains fail-closed"
+ fi
- (
- cd "${PROJECT_DIR}"
- make minikube-build-images
- make minikube-verify-images
- make minikube-apply-secrets
- make minikube-deploy-all
- if [[ "${infra_changed}" == "true" ]]; then
- make minikube-restart-all
- fi
- )
+
- rollout_if_present control-plane control-postgres
- CONTEXT="${PROFILE}" ALLOWED_CONTEXTS="${PROFILE}" \
- bash "${PROJECT_DIR}/deploy/scripts/run-control-api-db-migration.sh" \
- --overlay "${PROJECT_DIR}/deploy/overlays/minikube"
- CONTEXT="${PROFILE}" ALLOWED_CONTEXTS="${PROFILE}" \
- bash "${PROJECT_DIR}/deploy/scripts/provision-control-api-runtime-roles.sh"
- rollout_if_present control-plane control-api
- # The base manifest no longer declares connection-string (provisioning-owned
- # key), so deploy-all cannot clobber it. Provisioning must still run AFTER
- # control-api migrations (0048 creates the least-privilege gfs_controller
- # role) for fresh profiles and to converge any stale credential before the
- # rest of the gate observes service readiness.
- provision_gfs_serving
++ incremental_build_images
++
++ if [[ "${INCREMENTAL_FULL_IMAGE_BUILD}" == "true" ||
++ "${INCREMENTAL_FULL_DEPLOYMENT}" == "true" ]]; then
++ (
++ cd "${PROJECT_DIR}"
++ make minikube-apply-secrets
++ make minikube-deploy-all
++ if [[ "${FORCE_RESTART}" == "true" || "${INCREMENTAL_FULL_IMAGE_BUILD}" == "true" ]]; then
++ make minikube-restart-all
++ fi
++ )
++ fi
+
+ if incremental_requires_database_reconcile; then
+ rollout_if_present control-plane control-postgres
+ CONTEXT="${PROFILE}" ALLOWED_CONTEXTS="${PROFILE}" \
+ bash "${PROJECT_DIR}/deploy/scripts/run-control-api-db-migration.sh" \
+ --overlay "${PROJECT_DIR}/deploy/overlays/minikube"
+ CONTEXT="${PROFILE}" ALLOWED_CONTEXTS="${PROFILE}" \
+ bash "${PROJECT_DIR}/deploy/scripts/provision-control-api-runtime-roles.sh"
+ rollout_if_present control-plane control-api
+ # The base manifest no longer declares connection-string (provisioning-owned
+ # key), so deploy-all cannot clobber it. Provisioning must still run AFTER
+ # control-api migrations (0048 creates the least-privilege gfs_controller
+ # role) for fresh profiles and to converge any stale credential before the
+ # rest of the gate observes service readiness.
+ provision_gfs_serving
+ fi
ensure_evenfire_registry
+ incremental_restart_targets
rollout_if_present control-plane host-context-controller
rollout_if_present control-plane workflow-recipes
diff --cc scripts/tests/test-gfs-deploy-contract.sh
index 000000000,7a36317bb..c738c1871
mode 000000,100755..100755
--- a/scripts/tests/test-gfs-deploy-contract.sh
+++ b/scripts/tests/test-gfs-deploy-contract.sh
@@@ -1,0 -1,136 +1,136 @@@
+ #!/usr/bin/env bash
+ set -euo pipefail
+ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"; cd "$ROOT"
+ fail() { echo "FAIL: $*" >&2; exit 1; }
+ # Scope: OSS-resident GFS deploy invariants only. The GCP deploy invariants
+ # (deploy-dev/deploy-prod workflow ordering, gcp-* Makefile targets, gcp-prod
+ # overlay render, and the HCC rollback contract) live in evenfire-infra after
+ # the app/config repo split and are validated by its sibling contract there.
+ for mode in stage-writer stage-reader rotate-reader rotate-writer; do
+ grep -q "$mode" deploy/scripts/provision-gfs-db.sh || fail "missing $mode"
+ done
+ grep -q 'PG_DB="${PG_DB:-profiles}"' deploy/scripts/provision-gfs-db.sh || fail 'provisioner canonical GFS database default drifted'
+ grep -q 'PG_DB="${PG_DB:-profiles}"' deploy/scripts/preflight-gfs-db-reset.sh || fail 'reset preflight diverges from provisioner GFS database default'
+ grep -q 'recover_abandoned_applying' deploy/scripts/provision-gfs-db.sh || fail 'explicit applying-state recovery is not wired'
+ grep -q 'role_can_login' deploy/scripts/lib/gfs-credential-recovery.sh || fail 'fresh bootstrap recovery does not verify NOLOGIN'
+ ! grep -q 'rollout restart deployment -l' deploy/scripts/provision-gfs-db.sh || fail 'broad rollout'
+ role_migration="$(sed -n "/version: '0074_gfs_runtime_role_exact_contract'/,/^ },$/p" control-api/src/db.ts)"
+ [[ "$role_migration" == *'ALTER ROLE gfs_controller'* && "$role_migration" == *'ALTER ROLE gfs_controller_reader'* && "$role_migration" == *'NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS'* ]] || fail 'exact GFS runtime role attributes are not reconciled'
+ [[ "$role_migration" != *'NOLOGIN'* && "$role_migration" != *'LOGIN'* && "$role_migration" != *'PASSWORD'* && "$role_migration" != *'DROP ROLE'* ]] || fail 'role-contract migration changes credentials or replaces a role'
+ [[ "$role_migration" == *"ARRAY['gfs_controller', 'gfs_controller_reader']"* && "$role_migration" == *"EXECUTE format('REVOKE %I FROM %I'"* ]] || fail 'role-contract migration leaves inherited memberships'
+ provision_contract="$(sed -n '/verify_role_contract()/,/^}/p' deploy/scripts/provision-gfs-db.sh)"
+ [[ "$provision_contract" == *"has_column_privilege(:'role_name', 'control_admin_users', 'id', 'SELECT')"* && "$provision_contract" == *"has_column_privilege(:'role_name', 'team_members', 'status', 'SELECT')"* && "$provision_contract" == *"column_name NOT IN ('id', 'status')"* && "$provision_contract" == *"column_name NOT IN ('team_id', 'user_id', 'status')"* ]] || fail 'provisioner does not verify the exact subject-column contract'
+ writer_case="$(sed -n '/rotate-writer)/,/;;/p' deploy/scripts/provision-gfs-db.sh)"
+ [[ "$writer_case" == *'reconcile_credential gfs_controller writer "$WRITER_SECRET" gfsc-writer true'* && "$writer_case" != *'gfsc-reader'* ]] || fail 'writer rollout scope'
+ runtime_script="$(cat deploy/scripts/provision-gfs-runtime.sh)"
+ [[ "$runtime_script" == *'reconcile-gfs-deploy-credentials.sh'* ]] \
+ || fail 'post-overlay runtime path does not reconcile staged credentials'
+ [[ "$runtime_script" == *'rollout status deployment/gfsc-writer'* && \
+ "$runtime_script" == *'rollout status deployment/gfsc-reader'* ]] \
+ || fail 'post-overlay runtime path does not wait for exact GFSC rollouts'
+ [[ "$runtime_script" != *'rollout restart'* && "$runtime_script" != *'rotate-writer'* ]] \
+ || fail 'post-overlay runtime path rotates or unconditionally restarts GFS'
+ make_block() {
+ awk -v target="$1" '$0 ~ "^" target ":" {active=1} active && /^\.PHONY:/ {exit} active {print}' Makefile
+ }
+ for target in minikube-db-reset; do
+ block="$(make_block "$target")"
+ reset="$(grep -n 'reset-control-db-storage.sh' <<<"$block" | head -1 | cut -d: -f1)"
+ recreate="$(grep -n 'apply -k .* -l app=control-postgres' <<<"$block" | head -1 | cut -d: -f1)"
+ postgres_ready="$(grep -nE 'wait .*control-postgres|wait .*deploy/control-postgres' <<<"$block" | head -1 | cut -d: -f1)"
+ converge="$(grep -n 'converge-control-db-after-reset.sh' <<<"$block" | head -1 | cut -d: -f1)"
+ success="$(grep -n 'DB reset complete' <<<"$block" | tail -1 | cut -d: -f1)"
+ [[ -n "$reset" && -n "$recreate" && -n "$postgres_ready" && -n "$converge" && -n "$success" ]] && \
+ [[ "$reset" -lt "$recreate" && "$recreate" -lt "$postgres_ready" && "$postgres_ready" -lt "$converge" && "$converge" -lt "$success" ]] \
+ || fail "$target bypasses safe GFS reset recovery"
+ done
+ reset_storage="$(cat deploy/scripts/reset-control-db-storage.sh)"
+ for required in preflight-gfs-db-reset.sh 'scale deployment/control-api --replicas=0' 'scale deployment/control-postgres --replicas=0' 'wait_for_pods_gone app=control-api' 'wait_for_pods_gone app=control-postgres' 'preconditions":{"uid":"%s"}' 'persistentvolumeclaims/${PVC}'; do
+ [[ "$reset_storage" == *"$required"* ]] || fail "reset storage boundary omits $required"
+ done
+ preflight="$(grep -n 'preflight-gfs-db-reset.sh' deploy/scripts/reset-control-db-storage.sh | cut -d: -f1)"
+ scale="$(grep -n 'scale deployment/control-api' deploy/scripts/reset-control-db-storage.sh | cut -d: -f1)"
+ delete="$(grep -n 'delete --raw' deploy/scripts/reset-control-db-storage.sh | head -1 | cut -d: -f1)"
+ [[ "$preflight" -lt "$scale" && "$scale" -lt "$delete" ]] || fail 'reset storage mutates before metadata preflight'
+ grep -q 'claim.get("namespace") == "control-plane"' deploy/scripts/reset-control-db-storage.sh || fail 'released PV cleanup is not namespace-scoped'
+ grep -q 'claim.get("uid") == expected_uid' deploy/scripts/reset-control-db-storage.sh || fail 'released PV cleanup is not claim-UID-scoped'
+ ! grep -q 'ensure_pvc "control-postgres-data"' scripts/minikube/ensure-pvcs.sh || fail 'generic PVC reconciler can still delete the control database'
+ reset_convergence="$(cat deploy/scripts/converge-control-db-after-reset.sh)"
+ for required in run-control-api-db-migration.sh provision-control-api-runtime-roles.sh 'rollout status deployment/control-api' 'GFS_RESTORE_ACTIVE_NOLOGIN=true' reconcile-gfs-deploy-credentials.sh verify-gfs.sh; do
+ [[ "$reset_convergence" == *"$required"* ]] || fail "reset convergence omits $required"
+ done
+ migration="$(grep -n 'run-control-api-db-migration.sh' deploy/scripts/converge-control-db-after-reset.sh | cut -d: -f1)"
+ roles="$(grep -n 'provision-control-api-runtime-roles.sh' deploy/scripts/converge-control-db-after-reset.sh | cut -d: -f1)"
+ scale="$(grep -n 'scale deployment/control-api' deploy/scripts/converge-control-db-after-reset.sh | cut -d: -f1)"
+ ready="$(grep -n 'rollout status deployment/control-api' deploy/scripts/converge-control-db-after-reset.sh | cut -d: -f1)"
+ restore="$(grep -n 'GFS_RESTORE_ACTIVE_NOLOGIN=true' deploy/scripts/converge-control-db-after-reset.sh | cut -d: -f1)"
+ verify="$(grep -n 'verify-gfs.sh' deploy/scripts/converge-control-db-after-reset.sh | tail -1 | cut -d: -f1)"
+ success="$(grep -n 'migrations, runtime roles, GFS restore, and verification complete' deploy/scripts/converge-control-db-after-reset.sh | cut -d: -f1)"
+ [[ "$migration" -lt "$roles" && "$roles" -lt "$scale" && "$scale" -lt "$ready" && "$ready" -lt "$restore" && "$restore" -lt "$verify" && "$verify" -lt "$success" ]] \
+ || fail 'reset convergence ordering is incomplete'
+ ! grep -q '|| true' deploy/scripts/converge-control-db-after-reset.sh || fail 'reset convergence suppresses a critical failure'
+ for upgrade_path in Makefile scripts/minikube/pre-gate-sync.sh scripts/minikube/full-setup.sh; do
+ grep -q 'get secret gfs-controller-db' "$upgrade_path" || fail "$upgrade_path does not distinguish partial bootstrap"
+ done
+ assert_minikube_upgrade_classifier() {
+ local path="$1" start="$2" end="$3" block dsn classify ready abort reconcile fallback fresh
+ block="$(awk -v start="$start" -v end="$end" '
+ index($0, start) { active=1 }
+ active { print }
+ active && index($0, end) { exit }
+ ' "$path")"
+ dsn="$(grep -n 'writer_dsn=.*get secret gfs-controller-db' <<<"$block" | head -1 | cut -d: -f1)"
+ classify="$(grep -nE 'if \[\[? -n .*writer_dsn' <<<"$block" | head -1 | cut -d: -f1)"
+ ready="$(grep -n 'rollout status deployment/control-api' <<<"$block" | head -1 | cut -d: -f1)"
+ abort="$(grep -n 'exit 1' <<<"$block" | tail -1 | cut -d: -f1)"
+ reconcile="$(grep -n 'reconcile-gfs-deploy-credentials.sh' <<<"$block" | head -1 | cut -d: -f1)"
+ fallback="$(grep -nE '^[[:space:]]*else' <<<"$block" | tail -1 | cut -d: -f1)"
+ fresh="$(grep -ni 'fresh bootstrap' <<<"$block" | tail -1 | cut -d: -f1)"
+ [[ -n "$dsn" && -n "$classify" && -n "$ready" && -n "$abort" && -n "$reconcile" && -n "$fallback" && -n "$fresh" ]] \
+ || fail "$path upgrade classifier is incomplete"
+ [[ "$dsn" -lt "$classify" && "$classify" -lt "$ready" && "$ready" -lt "$abort" && \
+ "$abort" -lt "$reconcile" && "$reconcile" -lt "$fallback" && "$fallback" -lt "$fresh" ]] \
+ || fail "$path does not reconcile ready upgrades, abort unready upgrades, and defer only empty bootstraps"
+ }
+ assert_minikube_upgrade_classifier Makefile '# Upgrade path: adopt/validate writer' 'kustomize deploy/overlays/minikube'
+ assert_minikube_upgrade_classifier scripts/minikube/full-setup.sh '# Upgrade path: stage the additive reader' 'Applying kustomize overlay'
-assert_minikube_upgrade_classifier scripts/minikube/pre-gate-sync.sh 'apply-gfs-writer-secret.sh' 'make minikube-build-images'
++assert_minikube_upgrade_classifier scripts/minikube/pre-gate-sync.sh 'apply-gfs-writer-secret.sh' 'incremental_build_images'
+ full_setup_classifier="$(sed -n '/# Upgrade path: stage the additive reader/,/Applying kustomize overlay/p' scripts/minikube/full-setup.sh)"
+ reset_classifier="$(grep -n 'if \[ "$RESET_DB" = true \]; then' <<<"$full_setup_classifier" | head -1 | cut -d: -f1)"
+ reset_classifier_defer="$(grep -n 'HCC cutover deferred until post-convergence verification' <<<"$full_setup_classifier" | head -1 | cut -d: -f1)"
+ reset_classifier_else="$(grep -n '^else$' <<<"$full_setup_classifier" | head -1 | cut -d: -f1)"
+ reset_classifier_dsn="$(grep -n 'writer_dsn=.*get secret gfs-controller-db' <<<"$full_setup_classifier" | head -1 | cut -d: -f1)"
+ [[ -n "$reset_classifier" && -n "$reset_classifier_defer" && -n "$reset_classifier_else" && -n "$reset_classifier_dsn" ]] && \
+ [[ "$reset_classifier" -lt "$reset_classifier_defer" && "$reset_classifier_defer" -lt "$reset_classifier_else" && \
+ "$reset_classifier_else" -lt "$reset_classifier_dsn" ]] \
+ || fail 'full-setup reset still reaches the control-api readiness upgrade classifier'
+ full_setup_reset="$(sed -n '/# 6a. Optional DB reset/,/# 6c. Re-apply generated service tokens/p' scripts/minikube/full-setup.sh)"
+ reset_defer="$(grep -n 'HCC cutover deferred until post-convergence verification' <<<"$full_setup_reset" | head -1 | cut -d: -f1)"
+ reset_postgres_only="$(grep -n 'apply -k .* -l app=control-postgres' <<<"$full_setup_reset" | head -1 | cut -d: -f1)"
+ reset_converge="$(grep -n 'converge-control-db-after-reset.sh' <<<"$full_setup_reset" | head -1 | cut -d: -f1)"
+ reset_full_overlay="$(grep -n 'kubectl kustomize .* | .* apply -f -' <<<"$full_setup_reset" | tail -1 | cut -d: -f1)"
+ [[ -n "$reset_defer" && -n "$reset_postgres_only" && -n "$reset_converge" && -n "$reset_full_overlay" ]] && \
+ [[ "$reset_defer" -lt "$reset_postgres_only" && "$reset_postgres_only" -lt "$reset_converge" && "$reset_converge" -lt "$reset_full_overlay" ]] \
+ || fail 'full-setup reset can require ready control-api or cut over HCC before convergence'
+ pre_gate_crds="$(grep -n 'make minikube-deploy-crds' scripts/minikube/pre-gate-sync.sh | cut -d: -f1)"
+ pre_gate_writer="$(grep -n 'apply-gfs-writer-secret.sh' scripts/minikube/pre-gate-sync.sh | head -1 | cut -d: -f1)"
+ pre_gate_overlay="$(grep -n 'make minikube-deploy-all' scripts/minikube/pre-gate-sync.sh | head -1 | cut -d: -f1)"
+ [[ "$(wc -l <<<"$pre_gate_crds" | tr -d ' ')" -eq 1 ]] || fail 'pre-gate must apply CRDs exactly once'
+ [[ "$pre_gate_crds" -lt "$pre_gate_writer" && "$pre_gate_writer" -lt "$pre_gate_overlay" ]] \
+ || fail 'pre-gate must apply namespaces/CRDs before GFS Secrets and overlay'
+ # The GFS writer Secret must never be applied into a missing namespace. In the
+ # OSS deploy model, namespaces are applied by the prior deploy-crds/pre-gate step
+ # (asserted above for pre-gate-sync: CRDs -> writer Secret -> overlay), and
+ # minikube-deploy-all applies namespaces via the kustomize overlay, not a
+ # standalone deploy/base/namespaces.yaml line. The ordering guarantee is enforced
+ # defensively by apply-gfs-writer-secret.sh, which is fail-closed when the gfs
+ # namespace is absent. Assert that guard directly.
+ grep -q 'is not declared; apply deploy/base/namespaces.yaml before GFS Secrets' deploy/scripts/apply-gfs-writer-secret.sh \
+ || fail 'apply-gfs-writer-secret.sh is not fail-closed on a missing gfs namespace'
+ bash scripts/tests/test-gfs-credential-lifecycle.sh
+ bash scripts/tests/test-provision-gfs-runtime.sh
+ bash scripts/tests/test-gfs-writer-secret-apply.sh
+ bash scripts/tests/test-gfs-nologin-restore.sh
+ bash scripts/tests/test-gfs-db-reset-preflight.sh
+ bash scripts/tests/test-reset-control-db-storage.sh
+ echo 'PASS: GFS deploy contract (OSS-resident invariants)'
diff --cc scripts/tests/test-reset-control-db-storage.sh
index 000000000,9382e6101..2576e3601
mode 000000,100755..100755
--- a/scripts/tests/test-reset-control-db-storage.sh
+++ b/scripts/tests/test-reset-control-db-storage.sh
@@@ -1,0 -1,255 +1,255 @@@
+ #!/usr/bin/env bash
+ set -euo pipefail
+
+ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
+ TMP="$(mktemp -d)"
+ trap 'rm -rf "$TMP"' EXIT
+ mkdir -p "$TMP/bin"
+
+ cat >"$TMP/bin/kubectl" <<'EOF'
+ #!/usr/bin/env bash
+ set -euo pipefail
+ printf '%s\n' "$*" >>"$FAKE_LOG"
+
+ case "$*" in
+ *'get secret gfs-controller-db -o name') printf 'secret/gfs-controller-db\n' ;;
+ *'get secret'*'-o json')
+ if [[ "$*" == *gfs-controller-reader-db* ]]; then role=gfs_controller_reader; else role=gfs_controller; fi
+ DSN="postgresql://${role}:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa@control-postgres.control-plane.svc.cluster.local:5432/profiles" \
+ python3 -c 'import base64,json,os; print(json.dumps({"metadata":{"resourceVersion":"1","annotations":{"clerum.io/gfs-dsn-state":"ready"}},"data":{"connection-string":base64.b64encode(os.environ["DSN"].encode()).decode()}}))'
+ ;;
+ *'apply set-last-applied'*|*' apply -f '*) exit 0 ;;
+ *'get pvc control-postgres-data -o json --ignore-not-found'*)
+ # JSON view consumed by the scrub-finalizer compare-and-swap. Finalizer
+ # presence is tracked in a file toggled by the pvc patch mock below.
+ if [ "$FAKE_MODE" = no-pvc ]; then exit 0; fi
+ uid=claim-uid-1
+ [ "$FAKE_MODE" != pin-replaced ] || uid=replacement-uid
+ deletion=''
+ [ "$FAKE_MODE" != pin-terminating ] || deletion=',"deletionTimestamp":"2026-07-21T00:00:00Z"'
+ fin='"kubernetes.io/pvc-protection"'
+ [ ! -f "$FAKE_FINALIZER" ] || fin="$fin,\"clerum.io/control-db-reset-scrub\""
+ printf '{"metadata":{"uid":"%s","resourceVersion":"10","finalizers":[%s]%s}}\n' "$uid" "$fin" "$deletion"
+ ;;
+ *'patch pvc control-postgres-data --type=json'*)
+ [ "$FAKE_MODE" != pin-patch-fail ] || exit 1
+ payload=""
+ while [ "$#" -gt 0 ]; do
+ if [ "$1" = -p ]; then shift; payload="$1"; break; fi
+ shift
+ done
+ [ -n "$payload" ] || { printf 'missing pvc patch payload\n' >&2; exit 1; }
+ case "$payload" in
+ *control-db-reset-scrub*) touch "$FAKE_FINALIZER" ;;
+ *)
+ if [ "$FAKE_MODE" = unpin-contention ] && [ ! -f "$FAKE_UNPIN" ]; then
+ touch "$FAKE_UNPIN"
+ exit 1
+ fi
+ rm -f "$FAKE_FINALIZER"
+ ;;
+ esac
+ ;;
+ *'get pvc control-postgres-data'*)
+ count=0; [ ! -f "$FAKE_COUNTER" ] || count="$(cat "$FAKE_COUNTER")"
+ count=$((count + 1)); printf '%s' "$count" >"$FAKE_COUNTER"
+ if [ "$FAKE_MODE" = no-pvc ]; then exit 0; fi
+ if [[ "$FAKE_MODE" =~ ^resume-(after-delete|replacement-bound|converged|deleting-replacement)$ ]]; then printf replacement-uid; exit 0; fi
+ if [ "$FAKE_MODE" = uid-mismatch ] && [ "$count" -eq 1 ]; then printf other-uid; exit 0; fi
+ if [ "$FAKE_MODE" = uid-replaced-before-scrub ] && [ "$count" -ge 2 ]; then printf replacement-uid; exit 0; fi
+ if [ "$FAKE_MODE" = uid-replaced-before-delete ] && [ "$count" -eq 3 ]; then printf replacement-uid; exit 0; fi
+ if [ "$FAKE_MODE" = pin-replaced ] && [ "$count" -ge 3 ]; then printf replacement-uid; exit 0; fi
+ printf claim-uid-1
+ ;;
+ *'get configmap control-db-reset-state'*)
+ [ -s "$FAKE_STATE" ] || exit 1
+ cat "$FAKE_STATE"
+ ;;
+ *'get deployment/host-context-controller'*) printf 4 ;;
+ *'get deployment/workflow-recipes'*) printf 5 ;;
+ *'get deployment/trace-maintenance-worker'*) printf 6 ;;
+ *'get deployment/gfsc-writer'*) printf 3 ;;
+ *'get deployment/gfsc-reader'*) printf 2 ;;
+ *'get deployment/control-api'*) printf 2 ;;
+ *'create configmap control-db-reset-state'*)
+ [ "$FAKE_MODE" != state-create-fail ] || exit 1
+ printf '1|1|authorized|%s|unbound|4|5|6|3|2|2\n' "${FAKE_ORIGINAL_UID:-claim-uid-1}" >"$FAKE_STATE"
+ ;;
+ *'patch configmap control-db-reset-state'*)
+ [ "$FAKE_MODE" != state-cas-fail ] || exit 1
+ IFS='|' read -r rv version phase original replacement hcc workflow trace writer reader controlapi <"$FAKE_STATE"
+ payload=""
+ while [ "$#" -gt 0 ]; do
+ if [ "$1" = -p ]; then shift; payload="$1"; break; fi
+ shift
+ done
+ [ -n "$payload" ] || { printf 'missing patch payload\n' >&2; exit 1; }
+ next_phase="$(python3 -c 'import json,sys; p=json.loads(sys.argv[1]); print(next(x["value"] for x in p if x["op"]=="replace" and x["path"]=="/data/phase"))' "$payload")" || { printf 'cannot parse phase\n' >&2; exit 1; }
+ next_replacement="$(python3 -c 'import json,sys; p=json.loads(sys.argv[1]); print(next(x["value"] for x in p if x["op"]=="replace" and x["path"]=="/data/replacementPvcUid"))' "$payload")" || { printf 'cannot parse replacement\n' >&2; exit 1; }
+ printf '%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s\n' "$((rv + 1))" "$version" "$next_phase" "$original" "$next_replacement" "$hcc" "$workflow" "$trace" "$writer" "$reader" "$controlapi" >"$FAKE_STATE"
+ ;;
+ *'scale deployment/host-context-controller --replicas=0'*) exit 0 ;;
+ *'scale deployment/workflow-recipes deployment/trace-maintenance-worker --replicas=0'*) exit 0 ;;
+ *'scale deployment/gfsc-writer deployment/gfsc-reader --replicas=0'*) exit 0 ;;
+ *'get pods -l app=host-context-controller -o name') printf 'pod/hcc-old\n' ;;
+ *'get pods -l app=gfs-controller -o name') printf 'pod/gfsc-old\n' ;;
+ *'get pods -l app=workflow-recipes -o name') printf 'pod/workflow-old\n' ;;
+ *'get pods -l app=trace-maintenance-worker -o name') printf 'pod/trace-old\n' ;;
+ *'wait --for=delete pod -l app=host-context-controller'*) exit 0 ;;
+ *'wait --for=delete pod -l app=gfs-controller'*) exit 0 ;;
+ *'wait --for=delete pod -l app=workflow-recipes'*) exit 0 ;;
+ *'wait --for=delete pod -l app=trace-maintenance-worker'*) exit 0 ;;
+ *'scale deployment/control-api --replicas=0'*) exit 0 ;;
+ *'scale deployment/control-postgres --replicas=0'*) exit 0 ;;
+ *'get pods -l'*'-o json') printf '{"items":[]}\n' ;;
+ *'get deployment control-postgres'*) printf 'postgres:16-alpine' ;;
+ *'create -f -'*) cat >"$FAKE_MANIFEST"; [ "$FAKE_MODE" != scrub-create-fail ] ;;
+ *'get pod control-postgres-storage-reset'*) printf Succeeded ;;
+ *'delete pod control-postgres-storage-reset'*) exit 0 ;;
+ *'delete --raw /api/v1/namespaces/control-plane/persistentvolumeclaims/control-postgres-data'*) cat >/dev/null; exit 0 ;;
+ *'get pv -o json'*) printf '{"items":[]}\n' ;;
+ *) printf 'unexpected kubectl invocation: %s\n' "$*" >&2; exit 91 ;;
+ esac
+ EOF
+ chmod +x "$TMP/bin/kubectl"
+
+ run_case() {
+ local mode="$1"; shift
+ : >"$TMP/$mode.log"; : >"$TMP/$mode.manifest"
+ rm -f "$TMP/$mode.counter" "$TMP/$mode.state" "$TMP/$mode.finalizer" "$TMP/$mode.unpin"
+ case "$mode" in
+ concurrent|resume) printf '1|1|deleting-original|claim-uid-1|unbound|4|5|6|3|2|2\n' >"$TMP/$mode.state" ;;
+ resume-pinned)
+ printf '1|1|deleting-original|claim-uid-1|unbound|4|5|6|3|2|2\n' >"$TMP/$mode.state"
+ touch "$TMP/$mode.finalizer" ;;
+ resume-after-delete) printf '1|1|original-deleted|claim-uid-1|unbound|4|5|6|3|2|2\n' >"$TMP/$mode.state" ;;
+ resume-replacement-bound) printf '1|1|replacement-bound|claim-uid-1|replacement-uid|4|5|6|3|2|2\n' >"$TMP/$mode.state" ;;
+ resume-converged) printf '1|1|converged|claim-uid-1|replacement-uid|4|5|6|3|2|2\n' >"$TMP/$mode.state" ;;
+ resume-deleting-replacement) printf '1|1|deleting-original|claim-uid-1|unbound|4|5|6|3|2|2\n' >"$TMP/$mode.state" ;;
+ state-substitution) printf '1|1|replacement-bound|claim-uid-1|other-replacement|4|5|6|3|2|2\n' >"$TMP/$mode.state" ;;
+ esac
+ env PATH="$TMP/bin:$PATH" FAKE_MODE="$mode" FAKE_LOG="$TMP/$mode.log" \
+ FAKE_MANIFEST="$TMP/$mode.manifest" FAKE_COUNTER="$TMP/$mode.counter" \
+ FAKE_STATE="$TMP/$mode.state" FAKE_FINALIZER="$TMP/$mode.finalizer" \
+ FAKE_UNPIN="$TMP/$mode.unpin" \
+ FAKE_ORIGINAL_UID="$([ "$mode" = no-pvc ] && printf none || printf claim-uid-1)" CONTEXT=test \
+ bash "$ROOT/deploy/scripts/reset-control-db-storage.sh" "$@" >"$TMP/$mode.out" 2>&1
+ }
+
+ if ! run_case success --expected-pvc-uid claim-uid-1; then
+ cat "$TMP/success.out" >&2
+ cat "$TMP/success.log" >&2
+ exit 1
+ fi
+ log="$TMP/success.log"
+ hcc_zero="$(grep -n 'scale deployment/host-context-controller --replicas=0' "$log" | head -1 | cut -d: -f1)"
+ hcc_wait="$(grep -n 'wait --for=delete pod -l app=host-context-controller' "$log" | cut -d: -f1)"
+ gfsc_zero="$(grep -n 'scale deployment/gfsc-writer deployment/gfsc-reader --replicas=0' "$log" | head -1 | cut -d: -f1)"
+ scrub="$(grep -n 'create -f -' "$log" | cut -d: -f1)"
+ pvc_delete="$(grep -n 'delete --raw /api/v1/namespaces/control-plane/persistentvolumeclaims/control-postgres-data' "$log" | cut -d: -f1)"
+ [[ "$hcc_zero" -lt "$hcc_wait" && "$hcc_wait" -lt "$gfsc_zero" && "$gfsc_zero" -lt "$scrub" && "$scrub" -lt "$pvc_delete" ]]
+ grep -q -- '--from-literal=hccReplicas=4' "$log"
+ grep -q -- '--from-literal=workflowReplicas=5' "$log"
+ grep -q -- '--from-literal=traceReplicas=6' "$log"
+ grep -q -- '--from-literal=writerReplicas=3' "$log"
+ grep -q -- '--from-literal=readerReplicas=2' "$log"
+ grep -q -- '--from-literal=controlApiReplicas=2' "$log"
+ grep -q 'find /reset-target -mindepth 1 -xdev -delete' "$TMP/success.manifest"
+ # The scrub-finalizer pin closes the mount-by-name reuse window: the original
+ # is pinned before the scrub pod exists and released only after the post-scrub
+ # UID recheck, immediately before the UID-preconditioned delete.
+ pin="$(grep -n 'patch pvc control-postgres-data' "$log" | head -1 | cut -d: -f1)"
+ unpin="$(grep -n 'patch pvc control-postgres-data' "$log" | tail -1 | cut -d: -f1)"
+ [[ -n "$pin" && -n "$unpin" && "$pin" != "$unpin" ]]
+ [[ "$pin" -lt "$scrub" && "$scrub" -lt "$unpin" && "$unpin" -lt "$pvc_delete" ]]
+
+ run_case resume --expected-pvc-uid claim-uid-1 --resume
+ ! grep -q 'create configmap control-db-reset-state' "$TMP/resume.log"
+ grep -q 'delete --raw /api/v1/namespaces/control-plane/persistentvolumeclaims/control-postgres-data' "$TMP/resume.log"
+ # A crash can leave the fixed-name scrub pod behind; resume must remove any
+ # leftover BEFORE creating its own, or it would fail AlreadyExists forever.
+ leftover_cleanup="$(grep -n 'delete pod control-postgres-storage-reset' "$TMP/resume.log" | head -1 | cut -d: -f1)"
+ resume_scrub="$(grep -n 'create -f -' "$TMP/resume.log" | head -1 | cut -d: -f1)"
+ [[ -n "$leftover_cleanup" && -n "$resume_scrub" && "$leftover_cleanup" -lt "$resume_scrub" ]]
+
+ # A crash BETWEEN pin and unpin leaves the original still pinned. Resume must
+ # treat the present finalizer as an idempotent "already pinned" (no second pin
+ # patch), run the scrub, and issue exactly one pvc patch — the unpin — before
+ # the UID-preconditioned delete.
+ run_case resume-pinned --expected-pvc-uid claim-uid-1 --resume
+ [ "$(grep -c 'patch pvc control-postgres-data' "$TMP/resume-pinned.log")" -eq 1 ]
+ rp_scrub="$(grep -n 'create -f -' "$TMP/resume-pinned.log" | head -1 | cut -d: -f1)"
+ rp_unpin="$(grep -n 'patch pvc control-postgres-data' "$TMP/resume-pinned.log" | head -1 | cut -d: -f1)"
+ rp_delete="$(grep -n 'delete --raw /api/v1/namespaces/control-plane/persistentvolumeclaims/control-postgres-data' "$TMP/resume-pinned.log" | head -1 | cut -d: -f1)"
+ [[ -n "$rp_scrub" && -n "$rp_unpin" && -n "$rp_delete" ]]
+ [[ "$rp_scrub" -lt "$rp_unpin" && "$rp_unpin" -lt "$rp_delete" ]]
+ # The single patch really released the finalizer in the mock's tracked state.
+ [ ! -f "$TMP/resume-pinned.finalizer" ]
+
+ run_case resume-after-delete --expected-pvc-uid claim-uid-1 --resume
+ ! grep -q 'create -f -' "$TMP/resume-after-delete.log"
+ grep -q 'scale deployment/host-context-controller --replicas=0' "$TMP/resume-after-delete.log"
+ ! grep -q 'persistentvolumeclaims/control-postgres-data' "$TMP/resume-after-delete.log"
+
+ for mode in resume-deleting-replacement resume-replacement-bound resume-converged; do
+ run_case "$mode" --expected-pvc-uid claim-uid-1 --resume
+ ! grep -q 'create -f -' "$TMP/$mode.log"
+ ! grep -q 'persistentvolumeclaims/control-postgres-data' "$TMP/$mode.log"
+ done
+ grep -q 'original-deleted' "$TMP/resume-deleting-replacement.state"
+ # A converged reset already restored the controllers; a stray resume must not
+ # quiesce the healthy stack, only point the operator back at convergence.
+ ! grep -q 'scale deployment' "$TMP/resume-converged.log"
+ grep -q 'converge-control-db-after-reset.sh' "$TMP/resume-converged.out"
+
+ run_case uid-replaced-before-scrub --expected-pvc-uid claim-uid-1
+ ! grep -q 'create -f -' "$TMP/uid-replaced-before-scrub.log"
+ ! grep -q 'persistentvolumeclaims/control-postgres-data' "$TMP/uid-replaced-before-scrub.log"
+ grep -q 'original-deleted' "$TMP/uid-replaced-before-scrub.state"
+
+ # A replacement that takes the name between the UID check and the finalizer
+ # pin is detected by the pin CAS itself: no scrub pod is created, nothing is
+ # deleted, and the reset still converges to original-deleted.
+ run_case pin-replaced --expected-pvc-uid claim-uid-1
+ ! grep -q 'create -f -' "$TMP/pin-replaced.log"
+ ! grep -q 'persistentvolumeclaims/control-postgres-data' "$TMP/pin-replaced.log"
+ grep -q 'original-deleted' "$TMP/pin-replaced.state"
+
+ # A contended finalizer release retries against the live object and still
+ # completes the UID-preconditioned delete (1 pin + 2 unpin attempts).
+ run_case unpin-contention --expected-pvc-uid claim-uid-1
+ [ "$(grep -c 'patch pvc control-postgres-data' "$TMP/unpin-contention.log")" -eq 3 ]
+ grep -q 'create -f -' "$TMP/unpin-contention.log"
+ grep -q 'delete --raw /api/v1/namespaces/control-plane/persistentvolumeclaims/control-postgres-data' "$TMP/unpin-contention.log"
+
+ # A terminating original or a persistently failing pin must fail closed
+ # before any scrub pod exists and before anything is deleted.
+ for mode in pin-terminating pin-patch-fail; do
+ if run_case "$mode" --expected-pvc-uid claim-uid-1; then
+ echo "FAIL: $mode was accepted" >&2; exit 1
+ fi
+ ! grep -q 'create -f -' "$TMP/$mode.log"
+ ! grep -q 'persistentvolumeclaims/control-postgres-data' "$TMP/$mode.log"
+ done
+
+ for mode in missing-expectation uid-mismatch concurrent uid-replaced-before-delete state-create-fail state-cas-fail state-substitution; do
- args=(--expected-pvc-uid claim-uid-1)
- [ "$mode" != missing-expectation ] || args=()
++ args=("$mode")
++ [ "$mode" = missing-expectation ] || args+=(--expected-pvc-uid claim-uid-1)
+ [ "$mode" != state-substitution ] || args+=(--resume)
- if run_case "$mode" "${args[@]}"; then
++ if run_case "${args[@]}"; then
+ echo "FAIL: $mode was accepted" >&2; exit 1
+ fi
+ done
+ ! grep -q 'scale deployment/host-context-controller' "$TMP/uid-mismatch.log"
+ ! grep -q 'scale deployment/host-context-controller' "$TMP/concurrent.log"
+ ! grep -q 'persistentvolumeclaims/control-postgres-data' "$TMP/uid-replaced-before-delete.log"
+ grep -q 'scale deployment/host-context-controller --replicas=0' "$TMP/uid-replaced-before-delete.log"
+ grep -q 'scale deployment/gfsc-writer deployment/gfsc-reader --replicas=0' "$TMP/uid-replaced-before-delete.log"
+ grep -q 'scale deployment/workflow-recipes deployment/trace-maintenance-worker --replicas=0' "$TMP/uid-replaced-before-delete.log"
+ grep -q 'scale deployment/host-context-controller --replicas=0' "$TMP/state-substitution.log"
+
+ run_case no-pvc --expect-no-pvc
+ ! grep -q 'create -f -' "$TMP/no-pvc.log"
+ grep -q -- '--from-literal=originalPvcUid=none' "$TMP/no-pvc.log"
+
+ printf 'PASS: control DB reset is UID-bound, scrub-pinned, crash-resumable, and quiesces DB-dependent controllers\n'
diff --cc tests/e2e/gfsCopyFixtures.ts
index 000000000,5b50b1c8d..f139373cb
mode 000000,100644..100644
--- a/tests/e2e/gfsCopyFixtures.ts
+++ b/tests/e2e/gfsCopyFixtures.ts
@@@ -1,0 -1,310 +1,316 @@@
+ import { seedGfsBlobWithKubectlCp } from './gfsBlobFixtureWriter'
+ import {
+ GFS_E2E_DRIVE,
+ UUID_RE,
+ assertFixtureName,
+ firstDataLine,
+ gfsWriterPod,
+ kubectlContext,
+ kubectlOut,
+ ridOf,
+ runControlPostgresSql,
+ splitSqlRow,
+ sqlLiteral,
+ } from './gfsFixtureCore'
+ import { cleanupGfsFixture } from './gfsResourceFixtures'
+
+ export interface GfsCopyTreeFixture {
+ sourceName: string
+ destinationName: string
+ sourceResourceId: string
+ destinationResourceId: string
+ standaloneFileName: string
+ standaloneFileResourceId: string
+ sourceUri: string
+ destinationUri: string
+ }
+
+ export interface GfsTreeSnapshotNode {
+ relativePath: string
+ resourceId: string
+ parentResourceId: string | null
+ name: string
+ kind: 'file' | 'directory'
+ bytes: number
+ version: number
+ content: string | null
+ }
+
+ export interface GfsHostGrantRow {
+ resourceId: string
+ permissions: string[]
+ inherit: boolean
+ }
+
+ export function cleanupGfsCopyTreeFixture(fixture: GfsCopyTreeFixture): void {
+ const failures: string[] = []
+ for (const name of [fixture.sourceName, fixture.destinationName]) {
+ try {
+ cleanupGfsFixture(name)
+ } catch (error) {
+ failures.push(`${name}: ${error instanceof Error ? error.message : String(error)}`)
+ }
+ }
- if (failures.length > 0) throw new Error(`GFS Copy fixture cleanup failed: ${failures.join('; ')}`)
++ if (failures.length > 0)
++ throw new Error(`GFS Copy fixture cleanup failed: ${failures.join('; ')}`)
+ }
+
+ function driveRoot(): string {
+ const row = firstDataLine(
+ runControlPostgresSql(`
+ INSERT INTO gfs_resources (drive, parent_resource_id, name, kind, path_cache)
+ VALUES (${sqlLiteral(GFS_E2E_DRIVE)}, NULL, '', 'directory', '/')
+ ON CONFLICT (drive) WHERE parent_resource_id IS NULL AND deleted_at IS NULL
+ DO UPDATE SET updated_at = gfs_resources.updated_at
+ RETURNING resource_id::text;
+ `)
+ )
+ if (!UUID_RE.test(row)) throw new Error(`failed to resolve GFS drive root: ${row}`)
+ return row
+ }
+
+ function insertResource(input: {
+ parentId: string
+ name: string
+ kind: 'file' | 'directory'
+ path: string
+ content?: Buffer
+ }): string {
+ const content = input.content ?? Buffer.alloc(0)
+ const row = firstDataLine(
+ runControlPostgresSql(`
+ INSERT INTO gfs_resources (drive, parent_resource_id, name, kind, path_cache, bytes)
+ VALUES (
+ ${sqlLiteral(GFS_E2E_DRIVE)}, ${sqlLiteral(input.parentId)}::uuid,
+ ${sqlLiteral(input.name)}, ${sqlLiteral(input.kind)}, ${sqlLiteral(input.path)},
+ ${input.kind === 'file' ? content.byteLength : 0}
+ ) RETURNING resource_id::text;
+ `)
+ )
+ if (!UUID_RE.test(row)) throw new Error(`failed to seed GFS resource ${input.path}: ${row}`)
+ if (input.kind === 'file') {
+ seedGfsBlobWithKubectlCp({
+ context: kubectlContext(),
+ writerPod: gfsWriterPod(),
+ blobKey: ridOf(row),
+ content,
+ timeoutMs: 20_000,
+ })
+ }
+ return row
+ }
+
+ /** Named precondition only: Copy and Rename are always performed by the agent. */
+ export function seedGfsCopyTreeFixture(name: string): GfsCopyTreeFixture {
+ assertFixtureName(name)
+ const sourceName = `${name}-source`
+ const destinationName = `${name}-destination`
+ const standaloneFileName = 'standalone.txt'
+ const seeded: string[] = []
+ try {
+ const rootId = driveRoot()
+ const sourceResourceId = insertResource({
+ parentId: rootId,
+ name: sourceName,
+ kind: 'directory',
+ path: `/${sourceName}`,
+ })
+ seeded.push(sourceName)
+ const destinationResourceId = insertResource({
+ parentId: rootId,
+ name: destinationName,
+ kind: 'directory',
+ path: `/${destinationName}`,
+ })
+ seeded.push(destinationName)
+ const standaloneFileResourceId = insertResource({
+ parentId: sourceResourceId,
+ name: standaloneFileName,
+ kind: 'file',
+ path: `/${sourceName}/${standaloneFileName}`,
+ content: Buffer.from(`issue-797 standalone ${name}\n`, 'utf8'),
+ })
+ const nestedId = insertResource({
+ parentId: sourceResourceId,
+ name: 'nested',
+ kind: 'directory',
+ path: `/${sourceName}/nested`,
+ })
+ insertResource({
+ parentId: nestedId,
+ name: 'empty',
+ kind: 'directory',
+ path: `/${sourceName}/nested/empty`,
+ })
+ insertResource({
+ parentId: nestedId,
+ name: 'alpha.txt',
+ kind: 'file',
+ path: `/${sourceName}/nested/alpha.txt`,
+ content: Buffer.from(`issue-797 alpha ${name}\n`, 'utf8'),
+ })
+ const deeperId = insertResource({
+ parentId: nestedId,
+ name: 'deeper',
+ kind: 'directory',
+ path: `/${sourceName}/nested/deeper`,
+ })
+ insertResource({
+ parentId: deeperId,
+ name: 'beta.txt',
+ kind: 'file',
+ path: `/${sourceName}/nested/deeper/beta.txt`,
+ content: Buffer.from(`issue-797 beta ${name}\n`, 'utf8'),
+ })
+ return {
+ sourceName,
+ destinationName,
+ sourceResourceId,
+ destinationResourceId,
+ standaloneFileName,
+ standaloneFileResourceId,
+ sourceUri: `gfs://${GFS_E2E_DRIVE}/${ridOf(sourceResourceId)}`,
+ destinationUri: `gfs://${GFS_E2E_DRIVE}/${ridOf(destinationResourceId)}`,
+ }
+ } catch (error) {
+ const teardownFailures: string[] = []
+ for (const fixtureName of seeded.reverse()) {
+ try {
+ cleanupGfsFixture(fixtureName)
+ } catch (cleanupError) {
+ teardownFailures.push(
+ `${fixtureName}: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`
+ )
+ }
+ }
+ if (teardownFailures.length > 0) {
+ throw new Error(
+ `GFS copy-tree seeding failed (${error instanceof Error ? error.message : String(error)}) ` +
+ `AND teardown of partial state failed: ${teardownFailures.join('; ')}`
+ )
+ }
+ throw error
+ }
+ }
+
+ function readContent(resourceId: string, blobKey: string | null): string {
+ const path = blobKey
+ ? (() => {
+ if (!/^[0-9a-f]{32}\/[0-9a-f-]{36}$/i.test(blobKey)) {
+ throw new Error(`invalid GFS generation key in snapshot: ${blobKey}`)
+ }
+ return `/data/gfs/.generations/${blobKey}`
+ })()
+ : `/data/gfs/${ridOf(resourceId)}`
+ return kubectlOut(['-n', 'gfs', 'exec', gfsWriterPod(), '--', 'cat', path], 20_000)
+ }
+
+ export function getGfsTreeSnapshot(rootId: string): GfsTreeSnapshotNode[] {
+ if (!UUID_RE.test(rootId)) throw new Error(`invalid GFS root id: ${rootId}`)
+ const rows = runControlPostgresSql(`
+ WITH RECURSIVE tree AS (
+ SELECT resource_id, parent_resource_id, name, kind, bytes, version, blob_key,
+ '.'::text AS relative_path
+ FROM gfs_resources
+ WHERE drive = ${sqlLiteral(GFS_E2E_DRIVE)}
+ AND resource_id = ${sqlLiteral(rootId)}::uuid AND deleted_at IS NULL
+ UNION ALL
+ SELECT child.resource_id, child.parent_resource_id, child.name, child.kind,
+ child.bytes, child.version, child.blob_key, tree.relative_path || '/' || child.name
+ FROM gfs_resources child JOIN tree ON child.parent_resource_id = tree.resource_id
+ WHERE child.drive = ${sqlLiteral(GFS_E2E_DRIVE)} AND child.deleted_at IS NULL
+ )
+ SELECT relative_path || '|' || resource_id::text || '|' ||
+ coalesce(parent_resource_id::text, '') || '|' || name || '|' || kind || '|' ||
+ bytes::text || '|' || version::text || '|' || coalesce(blob_key, '')
+ FROM tree ORDER BY relative_path;
+ `)
+ .split('\n')
+ .map(line => line.trim())
+ .filter(Boolean)
+
+ return rows.map(row => {
+ const parts = splitSqlRow(row)
+ if (parts.length !== 8) throw new Error(`invalid GFS snapshot row shape: ${row}`)
+ const [relativePath, resourceId, parentId, name, kind, bytes, version, blobKey] = parts as [
+ string,
+ string,
+ string,
+ string,
+ string,
+ string,
+ string,
+ string,
+ ]
+ if (!UUID_RE.test(resourceId) || (parentId && !UUID_RE.test(parentId))) {
+ throw new Error(`invalid GFS snapshot row: ${row}`)
+ }
+ const normalizedKind = kind === 'directory' ? 'directory' : 'file'
+ return {
+ relativePath,
+ resourceId,
+ parentResourceId: parentId || null,
+ name,
+ kind: normalizedKind,
+ bytes: Number(bytes),
+ version: Number(version),
+ content: normalizedKind === 'file' ? readContent(resourceId, blobKey || null) : null,
+ }
+ })
+ }
+
+ export function getGfsTreeAclShareCounts(rootId: string): { grants: number; shares: number } {
+ if (!UUID_RE.test(rootId)) throw new Error(`invalid GFS root id: ${rootId}`)
+ const row = firstDataLine(
+ runControlPostgresSql(`
+ WITH RECURSIVE tree AS (
+ SELECT resource_id FROM gfs_resources
+ WHERE drive = ${sqlLiteral(GFS_E2E_DRIVE)}
+ AND resource_id = ${sqlLiteral(rootId)}::uuid AND deleted_at IS NULL
+ UNION ALL
+ SELECT child.resource_id FROM gfs_resources child
+ JOIN tree ON child.parent_resource_id = tree.resource_id
+ WHERE child.drive = ${sqlLiteral(GFS_E2E_DRIVE)} AND child.deleted_at IS NULL
+ )
+ SELECT (SELECT count(*) FROM gfs_grants WHERE resource_id IN (SELECT resource_id FROM tree))::text || '|' ||
+ (SELECT count(*) FROM gfs_shares WHERE resource_id IN (SELECT resource_id FROM tree))::text;
+ `)
+ )
+ const parts = splitSqlRow(row)
+ if (parts.length !== 2) throw new Error(`invalid GFS ACL/share count row: ${row}`)
+ const [grants, shares] = parts as [string, string]
+ return { grants: Number(grants), shares: Number(shares) }
+ }
+
+ export function getGfsHostGrantsUnderTree(rootId: string, subjectId: string): GfsHostGrantRow[] {
+ if (!UUID_RE.test(rootId) || !/^1st:[a-z0-9-]+\/[a-z0-9-]+$/.test(subjectId)) {
+ throw new Error('invalid GFS host-grant tree query')
+ }
+ return runControlPostgresSql(`
+ WITH RECURSIVE tree AS (
+ SELECT resource_id FROM gfs_resources
+ WHERE drive = ${sqlLiteral(GFS_E2E_DRIVE)}
+ AND resource_id = ${sqlLiteral(rootId)}::uuid AND deleted_at IS NULL
+ UNION ALL
+ SELECT child.resource_id FROM gfs_resources child
+ JOIN tree ON child.parent_resource_id = tree.resource_id
+ WHERE child.drive = ${sqlLiteral(GFS_E2E_DRIVE)} AND child.deleted_at IS NULL
+ )
+ SELECT resource_id::text || '|' || array_to_string(permissions, ',') || '|' || inherit::text
+ FROM gfs_grants WHERE resource_id IN (SELECT resource_id FROM tree)
+ AND subject_type = 'host' AND subject_id = ${sqlLiteral(subjectId)} ORDER BY resource_id;
- `).split('\n').map(line => line.trim()).filter(Boolean).map(row => {
- const parts = splitSqlRow(row)
- if (parts.length !== 3 || !UUID_RE.test(parts[0] ?? '')) throw new Error(`invalid host grant row: ${row}`)
- return {
- resourceId: parts[0]!,
- permissions: parts[1] ? parts[1].split(',') : [],
- inherit: parts[2] === 't' || parts[2] === 'true',
- }
- })
++ `)
++ .split('\n')
++ .map(line => line.trim())
++ .filter(Boolean)
++ .map(row => {
++ const parts = splitSqlRow(row)
++ if (parts.length !== 3 || !UUID_RE.test(parts[0] ?? ''))
++ throw new Error(`invalid host grant row: ${row}`)
++ return {
++ resourceId: parts[0]!,
++ permissions: parts[1] ? parts[1].split(',') : [],
++ inherit: parts[2] === 't' || parts[2] === 'true',
++ }
++ })
+ }
diff --cc tests/e2e/gfsResourceFixtures.ts
index 933644345,05d6d71de..6f97f4832
--- a/tests/e2e/gfsResourceFixtures.ts
+++ b/tests/e2e/gfsResourceFixtures.ts
@@@ -41,12 -41,19 +41,16 @@@ function seedGfsBlob(resourceId: string
}
}
- function cleanupGfsBlob(resourceId: string): void {
- const blobKey = ridOf(resourceId)
- kubectlOut(
- ['-n', 'gfs', 'exec', gfsWriterPod(), '--', 'rm', '-f', `/data/gfs/${blobKey}`],
- 20_000
- )
+ function cleanupGfsBlob(resourceId: string, blobKey?: string | null): void {
+ const physicalPath = blobKey
+ ? (() => {
+ if (!/^[0-9a-f]{32}\/[0-9a-f-]{36}$/i.test(blobKey)) {
+ throw new Error(`refusing to clean invalid GFS generation key: ${blobKey}`)
+ }
+ return `/data/gfs/.generations/${blobKey}`
+ })()
+ : `/data/gfs/${ridOf(resourceId)}`
- kubectlOut(
- ['-n', 'gfs', 'exec', gfsWriterPod(), '--', 'rm', '-f', physicalPath],
- 20_000
- )
++ kubectlOut(['-n', 'gfs', 'exec', gfsWriterPod(), '--', 'rm', '-f', physicalPath], 20_000)
}
export function seedGfsDirectoryFixture(name: string): GfsDirectoryFixture {
@@@ -188,7 -195,7 +192,8 @@@ export function seedGfsGrant(input:
throw new Error(`subjectId is required for ${input.subjectType} GFS grants`)
}
const permissions = `ARRAY[${input.permissions.map(sqlLiteral).join(', ')}]::text[]`
- runControlPostgresSql(`
- const grantId = firstDataLine(runControlPostgresSql(`
++ const grantId = firstDataLine(
++ runControlPostgresSql(`
INSERT INTO gfs_grants (
drive, resource_id, subject_type, subject_id, permissions, inherit, granted_by
)
@@@ -206,8 -213,11 +211,12 @@@
permissions = EXCLUDED.permissions,
inherit = EXCLUDED.inherit,
granted_by = EXCLUDED.granted_by,
- updated_at = now();
+ updated_at = now()
+ RETURNING id::text;
- `))
+ `)
++ )
+ if (!UUID_RE.test(grantId)) throw new Error(`failed to seed GFS grant: ${grantId}`)
+ return grantId
}
export function getGfsGrantSummary(input: {
@@@ -303,11 -345,15 +344,15 @@@ export function cleanupGfsFixture(name
`)
.split('\n')
.map(line => line.trim())
- .filter(line => UUID_RE.test(line))
+ .filter(Boolean)
+ .map(splitSqlRow)
- .filter((parts): parts is [string, string] =>
- parts.length === 2 && UUID_RE.test(parts[0] ?? '')
++ .filter(
++ (parts): parts is [string, string] => parts.length === 2 && UUID_RE.test(parts[0] ?? '')
+ )
const cleanupErrors: unknown[] = []
- for (const resourceId of resourceIds) {
+ for (const [resourceId, blobKey] of resources) {
try {
- cleanupGfsBlob(resourceId)
+ cleanupGfsBlob(resourceId, blobKey || null)
} catch (error) {
cleanupErrors.push(error)
}
diff --cc tests/e2e/package-lock.json
index 3078dafd7,3078dafd7..d1432aa50
--- a/tests/e2e/package-lock.json
+++ b/tests/e2e/package-lock.json
@@@ -1,12 -1,12 +1,12 @@@
{
"name": "clerum-e2e-tests",
-- "version": "0.1.51",
++ "version": "0.1.52",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-e2e-tests",
-- "version": "0.1.51",
++ "version": "0.1.52",
"devDependencies": {
"@types/jsonwebtoken": "^9.0.10",
"@types/node": "^22.0.0",
diff --cc tests/e2e/package.json
index b28d41578,b28d41578..5bd15e893
--- a/tests/e2e/package.json
+++ b/tests/e2e/package.json
@@@ -1,6 -1,6 +1,6 @@@
{
"name": "clerum-e2e-tests",
-- "version": "0.1.51",
++ "version": "0.1.52",
"private": true,
"type": "module",
"scripts": {
diff --cc workflow-recipes/package-lock.json
index 8fc02f037,8fc02f037..f73e6fb39
--- a/workflow-recipes/package-lock.json
+++ b/workflow-recipes/package-lock.json
@@@ -1,12 -1,12 +1,12 @@@
{
"name": "workload-recipes-controller",
-- "version": "0.1.255",
++ "version": "0.1.256",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "workload-recipes-controller",
-- "version": "0.1.255",
++ "version": "0.1.256",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@aws-sdk/client-s3": "^3.1009.0",
diff --cc workflow-recipes/package.json
index b674d1263,b674d1263..c618b11d4
--- a/workflow-recipes/package.json
+++ b/workflow-recipes/package.json
@@@ -1,6 -1,6 +1,6 @@@
{
"name": "workload-recipes-controller",
-- "version": "0.1.255",
++ "version": "0.1.256",
"description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface",
"main": "dist/main.js",
"engines": {