Skip to content

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

TypeScript

feat(gfs): per-agent access and atomic copy — control-plane backend

Alfredo Lopez5e6c990f805f
diff --git a/control-api/src/db.ts b/control-api/src/db.ts
index a33135440..f2a21da38 100644
--- a/control-api/src/db.ts
+++ b/control-api/src/db.ts
@@ -2072,9 +2072,10 @@ async function applyUserNotificationPreferencesPreferredAccount(db: DbClient): P
async function applyGfsPermissionStoreSchema(db: DbClient): Promise<void> {
// Global File System (gfs) permission store — the governance plane's source
// of truth for resource metadata, folder grants, URI-bound shares, and the
- // append-only hash-chained audit log. File bytes live flat by resource_id in
- // the gfsc-mounted volume; the human path is metadata here (path_cache),
- // never mirrored on disk. There is deliberately NO tenant_id column —
+ // append-only hash-chained audit log. File bytes use opaque internal
+ // resource-generation keys in the gfsc-mounted volume; the human path is
+ // metadata here (path_cache), never mirrored on disk. There is deliberately
+ // NO tenant_id column —
// multi-tenancy is the managed edition (P6), not the open core.
await db.query(`
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
@@ -4759,6 +4760,270 @@ export const CONTROL_API_MIGRATIONS: DbMigration[] = [
`)
},
},
+ {
+ version: '0071_gfs_immutable_blob_generations',
+ apply: async db => {
+ await db.query(`
+ ALTER TABLE gfs_resources
+ ADD COLUMN IF NOT EXISTS blob_key TEXT NULL,
+ ADD COLUMN IF NOT EXISTS content_sha256 TEXT NULL;
+
+ DO $$ BEGIN
+ ALTER TABLE gfs_resources
+ ADD CONSTRAINT gfs_resources_blob_metadata_pair
+ CHECK ((blob_key IS NULL AND content_sha256 IS NULL)
+ OR (blob_key ~ '^[0-9a-f]{32}/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'
+ AND split_part(blob_key, '/', 1) = replace(resource_id::text, '-', '')
+ AND content_sha256 ~ '^[0-9a-f]{64}$'));
+ EXCEPTION WHEN duplicate_object THEN NULL;
+ END $$;
+
+ CREATE UNIQUE INDEX IF NOT EXISTS gfs_resources_blob_key_uniq
+ ON gfs_resources (blob_key)
+ WHERE blob_key IS NOT NULL;
+
+ CREATE TABLE IF NOT EXISTS gfs_blob_manifests (
+ blob_key TEXT PRIMARY KEY,
+ request_id UUID NOT NULL,
+ resource_id UUID NOT NULL,
+ candidate_kind TEXT NOT NULL DEFAULT 'generation'
+ CHECK (candidate_kind IN ('generation', 'legacy_flat')),
+ content_sha256 TEXT NULL,
+ bytes BIGINT NOT NULL CHECK (bytes >= 0),
+ state TEXT NOT NULL CHECK (state IN ('staged', 'committed', 'deleting')),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ CONSTRAINT gfs_blob_manifests_blob_key_valid CHECK (
+ (candidate_kind = 'generation'
+ AND blob_key ~ '^[0-9a-f]{32}/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'
+ AND split_part(blob_key, '/', 1) = replace(resource_id::text, '-', '')
+ AND content_sha256 ~ '^[0-9a-f]{64}$')
+ OR
+ (candidate_kind = 'legacy_flat'
+ AND blob_key = replace(resource_id::text, '-', '')
+ AND content_sha256 IS NULL)
+ )
+ );
+
+ CREATE INDEX IF NOT EXISTS gfs_blob_manifests_cleanup_idx
+ ON gfs_blob_manifests (state, updated_at, blob_key);
+
+ DROP TRIGGER IF EXISTS gfs_resources_perm_invalidate ON gfs_resources;
+ CREATE TRIGGER gfs_resources_perm_invalidate
+ AFTER UPDATE OF parent_resource_id, name, path_cache, deleted_at
+ OR DELETE OR TRUNCATE ON gfs_resources
+ FOR EACH STATEMENT EXECUTE FUNCTION gfs_notify_perm_invalidate();
+
+ GRANT SELECT, INSERT, UPDATE, DELETE ON gfs_blob_manifests TO gfs_controller;
+ GRANT SELECT (blob_key, content_sha256) ON gfs_resources TO gfs_controller;
+ `)
+ },
+ },
+ {
+ version: '0072_gfs_reader_database_role',
+ apply: async db => {
+ await db.query(`
+ DO $$
+ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'gfs_controller_reader') THEN
+ CREATE ROLE gfs_controller_reader NOLOGIN;
+ END IF;
+ END
+ $$;
+
+ ALTER ROLE gfs_controller_reader
+ NOLOGIN NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS;
+
+ DO $$
+ DECLARE inherited_role RECORD;
+ BEGIN
+ FOR inherited_role IN
+ SELECT granted.rolname
+ FROM pg_auth_members membership
+ JOIN pg_roles granted ON granted.oid = membership.roleid
+ JOIN pg_roles member_role ON member_role.oid = membership.member
+ WHERE member_role.rolname = 'gfs_controller_reader'
+ LOOP
+ EXECUTE format('REVOKE %I FROM gfs_controller_reader', inherited_role.rolname);
+ END LOOP;
+ END
+ $$;
+
+ REVOKE ALL PRIVILEGES ON gfs_resources, gfs_grants, gfs_shares,
+ gfs_blob_manifests, gfs_audit FROM gfs_controller_reader;
+ REVOKE ALL PRIVILEGES ON SEQUENCE gfs_audit_sequence_no_seq FROM gfs_controller_reader;
+ REVOKE ALL PRIVILEGES ON control_admin_users, team_members FROM gfs_controller_reader;
+
+ GRANT SELECT ON gfs_resources, gfs_grants, gfs_shares TO gfs_controller_reader;
+ GRANT SELECT (id, status) ON control_admin_users TO gfs_controller_reader;
+ GRANT SELECT (team_id, user_id, status) ON team_members TO gfs_controller_reader;
+ GRANT INSERT ON gfs_audit TO gfs_controller_reader;
+ GRANT USAGE, SELECT ON SEQUENCE gfs_audit_sequence_no_seq TO gfs_controller_reader;
+
+ REVOKE INSERT, UPDATE, DELETE, TRUNCATE ON gfs_resources FROM gfs_controller_reader;
+ REVOKE INSERT, UPDATE, DELETE, TRUNCATE ON gfs_grants FROM gfs_controller_reader;
+ REVOKE INSERT, UPDATE, DELETE, TRUNCATE ON gfs_shares FROM gfs_controller_reader;
+ REVOKE ALL PRIVILEGES ON gfs_blob_manifests FROM gfs_controller_reader;
+ REVOKE UPDATE, DELETE, TRUNCATE ON gfs_audit FROM gfs_controller_reader;
+ `)
+ },
+ },
+ {
+ version: '0073_gfs_audit_decision_evidence',
+ apply: async db => {
+ await db.query(`
+ ALTER TABLE gfs_audit
+ ADD COLUMN IF NOT EXISTS record_type TEXT NOT NULL DEFAULT 'legacy',
+ ADD COLUMN IF NOT EXISTS matched_subject TEXT NULL,
+ ADD COLUMN IF NOT EXISTS authorization_source TEXT NULL,
+ ADD COLUMN IF NOT EXISTS cached_authorization_source TEXT NULL,
+ ADD COLUMN IF NOT EXISTS mutation_outcome TEXT NULL;
+
+ DO $$ BEGIN
+ ALTER TABLE gfs_audit
+ ADD CONSTRAINT gfs_audit_record_type_valid
+ CHECK (record_type IN ('legacy', 'authorization_decision', 'mutation_outcome'));
+ EXCEPTION WHEN duplicate_object THEN NULL;
+ END $$;
+
+ DO $$ BEGIN
+ ALTER TABLE gfs_audit
+ ADD CONSTRAINT gfs_audit_authorization_source_valid
+ CHECK (authorization_source IS NULL OR authorization_source IN (
+ 'direct_grant', 'inherited_grant', 'direct_share',
+ 'inherited_share', 'operator', 'cache'
+ ));
+ EXCEPTION WHEN duplicate_object THEN NULL;
+ END $$;
+
+ DO $$ BEGIN
+ ALTER TABLE gfs_audit
+ ADD CONSTRAINT gfs_audit_cached_authorization_source_valid
+ CHECK (
+ (authorization_source = 'cache'
+ AND cached_authorization_source IS NOT NULL
+ AND cached_authorization_source IN (
+ 'direct_grant', 'inherited_grant', 'direct_share',
+ 'inherited_share', 'operator'
+ ))
+ OR
+ (authorization_source IS DISTINCT FROM 'cache'
+ AND cached_authorization_source IS NULL)
+ );
+ EXCEPTION WHEN duplicate_object THEN NULL;
+ END $$;
+
+ DO $$ BEGIN
+ ALTER TABLE gfs_audit
+ ADD CONSTRAINT gfs_audit_mutation_outcome_valid
+ CHECK (mutation_outcome IS NULL OR mutation_outcome IN ('succeeded', 'failed'));
+ EXCEPTION WHEN duplicate_object THEN NULL;
+ END $$;
+
+ DO $$ BEGIN
+ ALTER TABLE gfs_audit
+ ADD CONSTRAINT gfs_audit_record_type_fields_valid
+ CHECK (
+ (record_type = 'legacy' AND mutation_outcome IS NULL)
+ OR
+ (record_type = 'authorization_decision' AND mutation_outcome IS NULL)
+ OR
+ (record_type = 'mutation_outcome' AND mutation_outcome IS NOT NULL)
+ );
+ EXCEPTION WHEN duplicate_object THEN NULL;
+ END $$;
+
+ GRANT INSERT ON gfs_audit TO gfs_controller, gfs_controller_reader;
+ GRANT USAGE, SELECT ON SEQUENCE gfs_audit_sequence_no_seq
+ TO gfs_controller, gfs_controller_reader;
+ REVOKE UPDATE, DELETE, TRUNCATE ON gfs_audit
+ FROM gfs_controller, gfs_controller_reader;
+ `)
+ },
+ },
+ {
+ version: '0074_gfs_runtime_role_exact_contract',
+ apply: async db => {
+ await db.query(`
+ -- Reconcile existing clusters without changing credential state.
+ -- Deploy provisioning remains the sole credential-state owner.
+ ALTER ROLE gfs_controller
+ NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS;
+ ALTER ROLE gfs_controller_reader
+ NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS;
+
+ DO $$
+ DECLARE runtime_role TEXT;
+ DECLARE inherited_role RECORD;
+ BEGIN
+ FOREACH runtime_role IN ARRAY ARRAY['gfs_controller', 'gfs_controller_reader']
+ LOOP
+ FOR inherited_role IN
+ SELECT granted.rolname
+ FROM pg_auth_members membership
+ JOIN pg_roles granted ON granted.oid = membership.roleid
+ JOIN pg_roles member_role ON member_role.oid = membership.member
+ WHERE member_role.rolname = runtime_role
+ LOOP
+ EXECUTE format('REVOKE %I FROM %I', inherited_role.rolname, runtime_role);
+ END LOOP;
+ END LOOP;
+ END
+ $$;
+
+ -- Table-level REVOKE does not erase column ACLs in PostgreSQL. Clear
+ -- every column privilege explicitly before rebuilding the envelope.
+ DO $$
+ DECLARE protected_column RECORD;
+ BEGIN
+ FOR protected_column IN
+ SELECT table_name, column_name
+ FROM information_schema.columns
+ WHERE table_schema = 'public'
+ AND table_name = ANY(ARRAY[
+ 'gfs_resources', 'gfs_grants', 'gfs_shares',
+ 'gfs_blob_manifests', 'gfs_audit',
+ 'control_admin_users', 'team_members'
+ ])
+ LOOP
+ EXECUTE format(
+ 'REVOKE SELECT (%1$I), INSERT (%1$I), UPDATE (%1$I), REFERENCES (%1$I) ON TABLE %2$I FROM gfs_controller, gfs_controller_reader, PUBLIC',
+ protected_column.column_name,
+ protected_column.table_name
+ );
+ END LOOP;
+ END
+ $$;
+
+ -- Remove historical or manually-added grants before rebuilding the
+ -- exact writer and reader envelopes. PUBLIC receives no GFS access.
+ REVOKE ALL PRIVILEGES ON gfs_resources, gfs_grants, gfs_shares,
+ gfs_blob_manifests, gfs_audit FROM gfs_controller, gfs_controller_reader, PUBLIC;
+ REVOKE ALL PRIVILEGES ON SEQUENCE gfs_audit_sequence_no_seq
+ FROM gfs_controller, gfs_controller_reader, PUBLIC;
+ REVOKE ALL PRIVILEGES ON control_admin_users, team_members
+ FROM gfs_controller, gfs_controller_reader;
+ REVOKE SELECT, INSERT, UPDATE, DELETE, TRUNCATE ON control_admin_users, team_members
+ FROM PUBLIC;
+
+ GRANT SELECT, INSERT, UPDATE ON gfs_resources TO gfs_controller;
+ GRANT SELECT ON gfs_grants, gfs_shares TO gfs_controller;
+ GRANT SELECT, INSERT, UPDATE, DELETE ON gfs_blob_manifests TO gfs_controller;
+ GRANT INSERT ON gfs_audit TO gfs_controller;
+ GRANT USAGE, SELECT ON SEQUENCE gfs_audit_sequence_no_seq TO gfs_controller;
+
+ GRANT SELECT ON gfs_resources, gfs_grants, gfs_shares TO gfs_controller_reader;
+ GRANT INSERT ON gfs_audit TO gfs_controller_reader;
+ GRANT USAGE, SELECT ON SEQUENCE gfs_audit_sequence_no_seq TO gfs_controller_reader;
+
+ -- Subject resolution is deliberately column-scoped for both roles.
+ GRANT SELECT (id, status) ON control_admin_users
+ TO gfs_controller, gfs_controller_reader;
+ GRANT SELECT (team_id, user_id, status) ON team_members
+ TO gfs_controller, gfs_controller_reader;
+ `)
+ },
+ },
]
async function consolidateWorkflowAllowedUsersToTriggers(db: DbClient): Promise<void> {
@@ -4951,15 +5216,28 @@ export async function assertDbReady(db: DbClient = pool): Promise<void> {
export async function withTransaction<T>(work: (db: DbClient) => Promise<T>): Promise<T> {
const client = (await pool.connect()) as PoolClient
+ let transactionStarted = false
+ let commitSent = false
+ let releaseError: Error | boolean | undefined
try {
await client.query('BEGIN')
+ transactionStarted = true
const result = await work(client)
+ commitSent = true
await client.query('COMMIT')
return result
} catch (error) {
- await client.query('ROLLBACK')
+ if (commitSent || !transactionStarted) {
+ releaseError = error instanceof Error ? error : true
+ } else {
+ try {
+ await client.query('ROLLBACK')
+ } catch (rollbackError) {
+ releaseError = rollbackError instanceof Error ? rollbackError : true
+ }
+ }
throw error
} finally {
- client.release()
+ client.release(releaseError)
}
}
diff --git a/control-api/src/gfs/hostSubject.ts b/control-api/src/gfs/hostSubject.ts
index c7f093ce6..c17afd21e 100644
--- a/control-api/src/gfs/hostSubject.ts
+++ b/control-api/src/gfs/hostSubject.ts
@@ -18,8 +18,6 @@ export function makeHostSubjectId(
namespace: string,
name: string
): string | null {
- const normalizedNamespace = namespace.trim()
- const normalizedName = name.trim()
- if (!isK8sName(normalizedNamespace) || !isK8sName(normalizedName)) return null
- return `${party}:${normalizedNamespace}/${normalizedName}`
+ if (!isK8sName(namespace) || !isK8sName(name)) return null
+ return `${party}:${namespace}/${name}`
}
diff --git a/control-api/src/gfs/legacyStandaloneGrantMigration.ts b/control-api/src/gfs/legacyStandaloneGrantMigration.ts
new file mode 100644
index 000000000..05e3fcd4c
--- /dev/null
+++ b/control-api/src/gfs/legacyStandaloneGrantMigration.ts
@@ -0,0 +1,233 @@
+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 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 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)) {
+ 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 --git a/control-api/src/gfs/provisionerScopePolicy.ts b/control-api/src/gfs/provisionerScopePolicy.ts
index f9bfc2e40..73a102747 100644
--- a/control-api/src/gfs/provisionerScopePolicy.ts
+++ b/control-api/src/gfs/provisionerScopePolicy.ts
@@ -4,9 +4,12 @@ import type { HostParty } from '../auth/issuerSubjectClass'
export const GFS_READ_SCOPE: GfsScope = 'gfs.read'
export const GFS_WRITE_SCOPE: GfsScope = 'gfs.write'
-const THIRD_PARTY_PROVISIONER_SCOPES = new Set<GfsScope>([GFS_READ_SCOPE, GFS_WRITE_SCOPE])
+const HOST_PROVISIONER_SCOPES = new Set<GfsScope>([GFS_READ_SCOPE, GFS_WRITE_SCOPE])
-export function provisionerScopesAllowed(party: HostParty, scopes: readonly GfsScope[]): boolean {
- if (party !== '3rd') return true
- return scopes.every(scope => THIRD_PARTY_PROVISIONER_SCOPES.has(scope))
+export function provisionerScopesAllowed(_party: HostParty, scopes: readonly GfsScope[]): boolean {
+ // Both provisioners mint host credentials. Host authority is deliberately
+ // limited to the data plane: read and write. Governance remains on the
+ // operator/user plane, so neither first-party HCC agents nor third-party WRC
+ // workloads can mint delete/share/manage-acl authority into their runtime.
+ return scopes.every(scope => HOST_PROVISIONER_SCOPES.has(scope))
}
diff --git a/control-api/src/gfs/seedResources.ts b/control-api/src/gfs/seedResources.ts
index 4aa4dde76..c0cc66771 100644
--- a/control-api/src/gfs/seedResources.ts
+++ b/control-api/src/gfs/seedResources.ts
@@ -1,7 +1,7 @@
/**
* Materializes a GlobalFileSystem's `layout.rootDirectories` as `gfs_resources`
- * rows. The governance plane (control-api) is the ONLY writer of resource rows
- * (CC6); HCC's gfsReconciler triggers this after the drive reaches Ready.
+ * rows. Control API owns this root bootstrap; governed runtime mutations are
+ * applied by the GFSC writer. HCC triggers seeding after the drive reaches Ready.
*
* Drive-root model (operator decision): each drive has ONE synthetic root
* resource (parentResourceId = null, name = '', kind = directory). Every
@@ -15,8 +15,19 @@
*/
export const GFS_ROOT_NAME = ''
+const NAME_MAX = 255
+// eslint-disable-next-line no-control-regex
+const CONTROL_CHARS = /[\x00-\x1f\x7f]/
+
+export class InvalidRootDirectoriesError extends Error {
+ constructor() {
+ super('invalid_rootDirectories')
+ this.name = 'InvalidRootDirectoriesError'
+ }
+}
export interface SeedResourceStore {
+ acquireStructureLock(drive: string): Promise<void>
/**
* Ensure a directory resource exists at (drive, parentResourceId, name) and
* return its resourceId. parentResourceId is null ONLY for the synthetic
@@ -31,8 +42,30 @@ export interface SeedResourceStore {
}
function normalizeSegments(path: string): string[] {
- // rootDirectories are absolute ('/org', '/system/published-workflow-artifacts').
- return path.split('/').filter(segment => segment.length > 0)
+ if (path === '/') return []
+ if (
+ path.length === 0 ||
+ !path.startsWith('/') ||
+ path.endsWith('/') ||
+ path.includes('//') ||
+ path !== path.normalize('NFC')
+ ) {
+ throw new InvalidRootDirectoriesError()
+ }
+ const segments = path.slice(1).split('/')
+ if (
+ segments.some(
+ segment =>
+ segment.length === 0 ||
+ segment.length > NAME_MAX ||
+ segment === '.' ||
+ segment === '..' ||
+ CONTROL_CHARS.test(segment)
+ )
+ ) {
+ throw new InvalidRootDirectoriesError()
+ }
+ return segments
}
/**
@@ -45,6 +78,8 @@ export async function seedRootDirectories(
drive: string,
rootDirectories: string[]
): Promise<{ rootResourceId: string; byPath: Record<string, string> }> {
+ const normalizedPaths = rootDirectories.map(path => ({ path, segments: normalizeSegments(path) }))
+ await store.acquireStructureLock(drive)
const rootResourceId = await store.ensureDirectory({
drive,
parentResourceId: null,
@@ -53,8 +88,7 @@ export async function seedRootDirectories(
})
const byPath: Record<string, string> = {}
- for (const path of rootDirectories) {
- const segments = normalizeSegments(path)
+ for (const { path, segments } of normalizedPaths) {
if (segments.length === 0) continue // '/' is the root itself, already ensured
let parentResourceId = rootResourceId
let accumulated = ''
@@ -87,6 +121,13 @@ 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]
+ )
+ }
+
async ensureDirectory(input: {
drive: string
parentResourceId: string | null
@@ -96,6 +137,20 @@ export class DbSeedResourceStore implements SeedResourceStore {
const { drive, parentResourceId, name, pathCache } = input
if (parentResourceId === null) {
+ const locked = await this.db.query(
+ `SELECT resource_id, drive, parent_resource_id, name, kind, path_cache, deleted_at
+ FROM gfs_resources
+ WHERE drive = $1 AND parent_resource_id IS NULL AND deleted_at IS NULL
+ ORDER BY resource_id FOR UPDATE`,
+ [drive]
+ )
+ if (locked.rows.length > 0) {
+ const root = directoryRowOf(locked.rows[0])
+ if (root.name !== GFS_ROOT_NAME || root.kind !== 'directory' || root.path_cache !== '/') {
+ throw new Error('[gfs] seed: existing drive root is not canonical')
+ }
+ return root.resource_id
+ }
const inserted = await this.db.query(
`INSERT INTO gfs_resources (drive, parent_resource_id, name, kind, path_cache)
VALUES ($1, NULL, $2, 'directory', $3)
@@ -105,11 +160,44 @@ export class DbSeedResourceStore implements SeedResourceStore {
)
if (inserted.rows.length > 0) return resourceIdOf(inserted.rows[0])
const existing = await this.db.query(
- `SELECT resource_id FROM gfs_resources
- WHERE drive = $1 AND parent_resource_id IS NULL AND deleted_at IS NULL`,
+ `SELECT resource_id, name, kind, path_cache FROM gfs_resources
+ WHERE drive = $1 AND parent_resource_id IS NULL AND deleted_at IS NULL FOR UPDATE`,
[drive]
)
- return resourceIdOf(existing.rows[0])
+ const root = directoryRowOf(existing.rows[0])
+ if (root.name !== GFS_ROOT_NAME || root.kind !== 'directory' || root.path_cache !== '/') {
+ throw new Error('[gfs] seed: existing drive root is not canonical')
+ }
+ return root.resource_id
+ }
+
+ const observedChain = await this.loadDirectoryChain(parentResourceId)
+ const observedPath = canonicalDirectoryPath(observedChain, drive)
+ const locked = await this.db.query(
+ `SELECT resource_id, drive, parent_resource_id, name, kind, path_cache, deleted_at
+ FROM gfs_resources
+ WHERE resource_id = ANY($1::uuid[])
+ OR (drive = $2 AND parent_resource_id = $3::uuid AND name = $4 AND deleted_at IS NULL)
+ ORDER BY resource_id FOR UPDATE`,
+ [observedChain.map(row => row.resource_id).sort(), drive, parentResourceId, name]
+ )
+ const chain = await this.loadDirectoryChain(parentResourceId)
+ const canonicalParentPath = canonicalDirectoryPath(chain, drive)
+ if (canonicalParentPath !== observedPath) {
+ throw new Error('[gfs] seed: parent changed while acquiring row locks')
+ }
+ const expectedPath = canonicalParentPath === '/' ? `/${name}` : `${canonicalParentPath}/${name}`
+ if (pathCache !== expectedPath) {
+ throw new Error('[gfs] seed: requested path does not match the canonical parent tree')
+ }
+ const sibling = locked.rows
+ .map(directoryRowOf)
+ .find(row => row.parent_resource_id === parentResourceId && row.name === name)
+ if (sibling) {
+ if (sibling.kind !== 'directory' || sibling.path_cache !== expectedPath) {
+ throw new Error('[gfs] seed: existing directory is not canonical')
+ }
+ return sibling.resource_id
}
const inserted = await this.db.query(
@@ -121,12 +209,70 @@ export class DbSeedResourceStore implements SeedResourceStore {
)
if (inserted.rows.length > 0) return resourceIdOf(inserted.rows[0])
const existing = await this.db.query(
- `SELECT resource_id FROM gfs_resources
+ `SELECT resource_id, drive, parent_resource_id, name, kind, path_cache, deleted_at
+ FROM gfs_resources
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.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 --git a/control-api/src/routes/admin/hostsOverview.ts b/control-api/src/routes/admin/hostsOverview.ts
index f9e50f83f..cbf9f0990 100644
--- a/control-api/src/routes/admin/hostsOverview.ts
+++ b/control-api/src/routes/admin/hostsOverview.ts
@@ -9,6 +9,7 @@ import {
listUsers,
listUsersByAgent,
} from '../../services/directory/index.js'
+import { buildAgentDirectoryEntry } from '../../services/directory/accessReconciliation.js'
import { listHostSecrets } from './hostSecrets.js'
export function createAdminHostsOverviewRouter(gateway: K8sGateway): Router {
@@ -26,10 +27,14 @@ export function createAdminHostsOverviewRouter(gateway: K8sGateway): Router {
const selected = hosts
.map(h => ({ name: h.metadata?.name, namespace: h.metadata?.namespace }))
.filter(h => Boolean(h.name))
+ const agents = hosts
+ .map(host => buildAgentDirectoryEntry(host, config.hostsNamespace))
+ .filter(agent => agent !== null)
+ .sort((a, b) => a.name.localeCompare(b.name))
const overviews = await Promise.all(
selected.map(h => gateway.getHostOverview(h.name as string, h.namespace))
)
- res.status(200).json({ items: overviews })
+ res.status(200).json({ items: overviews, agents })
})
)
@@ -38,7 +43,14 @@ export function createAdminHostsOverviewRouter(gateway: K8sGateway): Router {
enforceNamespace(config.hostsNamespace),
asyncHandler(async (req, res) => {
const overview = await gateway.getHostOverview(req.params.name, config.hostsNamespace)
- res.status(200).json(overview)
+ const host =
+ overview && typeof overview === 'object' && 'host' in overview
+ ? (overview as { host?: unknown }).host
+ : null
+ res.status(200).json({
+ ...overview,
+ agent: buildAgentDirectoryEntry(host, config.hostsNamespace),
+ })
})
)
diff --git a/control-api/src/routes/external/teams.ts b/control-api/src/routes/external/teams.ts
index e6e0645fb..9998a8c2c 100644
--- a/control-api/src/routes/external/teams.ts
+++ b/control-api/src/routes/external/teams.ts
@@ -12,7 +12,6 @@ import {
import { resolveMcpServersForAgents } from '../../services/access/mcpInvocable.js'
import {
filterAccessValues,
- listActiveAgentNames,
listActiveContextIds,
} from '../../services/directory/accessReconciliation.js'
import {
@@ -130,35 +129,34 @@ export function createExternalTeamsRouter(gateway: K8sGateway): Router {
async (req, res, next) => {
try {
const base = await getTeamAgents(req.params.teamId)
- let active: Set<string> | null = null
- try {
- active = new Set(await listActiveAgentNames(gateway))
- } catch (err) {
- console.warn(
- `[external/teams] agent reconciliation failed for ${req.params.teamId}:`,
- err
- )
- }
- const activeAgentNames = filterAccessValues(base.agentNames, active)
+ // getTeamAgents is the authorization boundary. Resolve only those
+ // exact names so hidden Hosts are never queried for DTO enrichment.
+ const authorizedAgentNames = filterAccessValues(base.agentNames, null)
let agents: Awaited<ReturnType<typeof resolveMcpServersForAgents>> = []
+ let agentNames = authorizedAgentNames
try {
- // Authorization model: base.agentNames already reflects which agents
+ // Authorization model: authorizedAgentNames already reflects which agents
// this team is allowed to use. resolveMcpServersForAgents treats
// agent access as the gate — no context-level scoping needed.
agents = await resolveMcpServersForAgents(gateway, {
mcpServersNamespace: config.mcpServersNamespace,
hostsNamespace: config.hostsNamespace,
- agentNames: activeAgentNames,
+ agentNames: authorizedAgentNames,
})
+ // A successful lookup can safely remove genuinely missing or invalid
+ // Hosts. Only the DTOs resolved from the authorized input are used.
+ agentNames = agents.map(agent => agent.name)
} catch (err) {
- // Spec §7.2: never fail the catalog purely because K8s listing failed.
+ // Spec §7.2: never fail the catalog purely because Kubernetes is
+ // unavailable. Preserve the names authorized by the directory DB;
+ // omit enriched DTOs because their live Host identity is unverified.
console.warn(
`[external/teams] MCP server enrichment failed for team ${req.params.teamId}:`,
err
)
agents = []
}
- return res.status(200).json({ ...base, agentNames: activeAgentNames, agents })
+ return res.status(200).json({ ...base, agentNames, agents })
} catch (error) {
return next(error)
}
diff --git a/control-api/src/routes/external/users.ts b/control-api/src/routes/external/users.ts
index 805a9f841..eb91c4acb 100644
--- a/control-api/src/routes/external/users.ts
+++ b/control-api/src/routes/external/users.ts
@@ -217,35 +217,35 @@ export function createExternalUsersRouter(gateway: K8sGateway): Router {
async (req, res, next) => {
try {
const base = await getUserAgents(req.params.userId)
- let active: Set<string> | null = null
- try {
- active = new Set(await listActiveAgentNames(gateway))
- } catch (err) {
- console.warn(
- `[external/users] agent reconciliation failed for ${req.params.userId}:`,
- err
- )
- }
- const activeAgentNames = filterAccessValues(base.agentNames, active)
+ // getUserAgents is the authorization boundary. Only its normalized
+ // result may be resolved against Kubernetes; never list hidden Hosts
+ // to build directory DTOs and filter afterward.
+ const authorizedAgentNames = filterAccessValues(base.agentNames, null)
let agents: Awaited<ReturnType<typeof resolveMcpServersForAgents>> = []
+ let agentNames = authorizedAgentNames
try {
- // Authorization model: base.agentNames already reflects which agents
+ // Authorization model: authorizedAgentNames already reflects which agents
// this user is allowed to use. resolveMcpServersForAgents treats agent
// access as the gate — no additional context-level scoping needed.
agents = await resolveMcpServersForAgents(gateway, {
mcpServersNamespace: config.mcpServersNamespace,
hostsNamespace: config.hostsNamespace,
- agentNames: activeAgentNames,
+ agentNames: authorizedAgentNames,
})
+ // A successful lookup can safely remove genuinely missing or invalid
+ // Hosts. Only the DTOs resolved from the authorized input are used.
+ agentNames = agents.map(agent => agent.name)
} catch (err) {
- // Spec §7.2: never fail the catalog purely because K8s listing failed.
+ // Spec §7.2: never fail the catalog purely because Kubernetes is
+ // unavailable. Preserve the names authorized by the directory DB;
+ // omit enriched DTOs because their live Host identity is unverified.
console.warn(
`[external/users] MCP server enrichment failed for ${req.params.userId}:`,
err
)
agents = []
}
- return res.status(200).json({ ...base, agentNames: activeAgentNames, agents })
+ return res.status(200).json({ ...base, agentNames, agents })
} catch (error) {
return next(error)
}
diff --git a/control-api/src/routes/gfs/grants.ts b/control-api/src/routes/gfs/grants.ts
index 4b206cea7..785ca1630 100644
--- a/control-api/src/routes/gfs/grants.ts
+++ b/control-api/src/routes/gfs/grants.ts
@@ -34,6 +34,8 @@ export interface GrantsDb {
const DEFAULT_DRIVE = 'main'
export const PERMISSIONS = ['read', 'write', 'delete', 'manage_acl', 'share'] as const
export type GfsPermission = (typeof PERMISSIONS)[number]
+const MANAGED_FIRST_PARTY_HOST_PERMISSIONS = new Set<GfsPermission>(['read', 'write'])
+const LEGACY_STANDALONE_HOST_SUBJECT_ID = '1st:mcp-host/standalone'
const SUBJECT_TYPES = ['operator', 'user', 'team', 'host', 'context'] as const
export type GfsSubjectType = (typeof SUBJECT_TYPES)[number]
export const UUID_RE =
@@ -234,7 +236,7 @@ export async function assertMayGrant(
resourceId: string,
permissions: GfsPermission[],
target: GfsSubject,
- opts: { isShare: boolean }
+ opts: { isShare: boolean; allowLegacyRetirement?: boolean }
): Promise<void> {
await assertMayGrantBatch(db, caller, drive, resourceId, permissions, [target], opts)
}
@@ -334,16 +336,45 @@ function assertTargetPolicy(
caller: GfsCaller,
permissions: readonly GfsPermission[],
target: GfsSubject,
- opts: { isShare: boolean }
+ opts: { isShare: boolean; allowLegacyRetirement?: boolean }
): void {
+ const isLegacyStandaloneSubject =
+ target.type === 'host' && target.id === LEGACY_STANDALONE_HOST_SUBJECT_ID
+ const isLegacyRetirement = isLegacyStandaloneSubject && opts.allowLegacyRetirement === true
+
+ // The historical fleet-wide subject remains parseable so operators can
+ // inventory, migrate, and revoke its stored rows. It must never receive a
+ // new grant after the individual-Host cutover — single or bulk. Revocation
+ // callers opt in explicitly via allowLegacyRetirement; every create and
+ // delegation path remains fail-closed.
+ if (isLegacyStandaloneSubject && !isLegacyRetirement) {
+ throw new GfsGrantError(403, 'legacy_standalone_subject_reserved')
+ }
// Agent (host) restriction (spec §Delegation): manage_acl/share are never
// grantable to a host by a folder owner — only the operator can. `share` as a
- // share-grant is for users/teams only, never a host.
+ // share-grant is for users/teams only, never a host. Caller authority is
+ // adjudicated before the per-target permission envelope below.
const grantsManagerBit = permissions.includes('manage_acl') || permissions.includes('share')
if (!caller.isOperator && target.type === 'host' && grantsManagerBit) {
throw new GfsGrantError(403, 'agent_manager_forbidden')
}
- if (opts.isShare && target.type === 'host') {
+ // HCC-issued first-party Host credentials intentionally carry data-plane
+ // authority only. Enforce the same boundary on stored grants before the
+ // operator bypass so a future token-policy regression cannot activate a
+ // dormant destructive/governance grant. Third-party hosts retain their
+ // existing grant compatibility; their runtime token scopes are constrained
+ // independently by provisionerScopePolicy. Revocation (the only caller that
+ // sets allowLegacyRetirement) is exempt: an over-privileged stored row from
+ // before this envelope existed must remain deletable, never locked in.
+ if (
+ target.type === 'host' &&
+ target.id?.startsWith('1st:') &&
+ opts.allowLegacyRetirement !== true &&
+ permissions.some(permission => !MANAGED_FIRST_PARTY_HOST_PERMISSIONS.has(permission))
+ ) {
+ throw new GfsGrantError(403, 'managed_agent_permission_forbidden')
+ }
+ if (opts.isShare && target.type === 'host' && !isLegacyRetirement) {
throw new GfsGrantError(403, 'share_to_agent_forbidden')
}
// A non-operator may not grant/share TO the operator subject — the operator is
@@ -392,7 +423,7 @@ export async function assertMayGrantBatch(
resourceId: string,
permissions: readonly GfsPermission[],
targets: readonly GfsSubject[],
- opts: { isShare: boolean }
+ opts: { isShare: boolean; allowLegacyRetirement?: boolean }
): Promise<void> {
for (const target of targets) {
assertTargetPolicy(caller, permissions, target, opts)
@@ -940,7 +971,7 @@ export async function handleGrantDelete(
String(row.resource_id),
(row.permissions as GfsPermission[]) ?? ['manage_acl'],
subject,
- { isShare: false }
+ { isShare: false, allowLegacyRetirement: true }
)
} catch (error) {
if (!(error instanceof GfsGrantError)) throw error
diff --git a/control-api/src/routes/gfs/index.ts b/control-api/src/routes/gfs/index.ts
index 8b2183501..bf88da8d7 100644
--- a/control-api/src/routes/gfs/index.ts
+++ b/control-api/src/routes/gfs/index.ts
@@ -8,6 +8,7 @@ import { registerGfsSeedRoute } from './seed.js'
import { registerGfsShareRoutes } from './shares.js'
import { registerGfsTokenRoute } from './token.js'
import { registerGfsTreeRoutes } from './tree.js'
+import { registerLegacyStandaloneGrantReportRoute } from './legacyStandaloneGrants.js'
/**
* gfs (Global File System) router — mounted under /api/v1 BEFORE the internal
@@ -23,6 +24,7 @@ export function createGfsRouter(): Router {
registerGfsTreeRoutes(router)
registerGfsSeedRoute(router)
registerGfsGrantRoutes(router)
+ registerLegacyStandaloneGrantReportRoute(router)
registerGfsShareRoutes(router)
registerGfsResourceRoutes(router)
registerGfsProxyRoute(router)
diff --git a/control-api/src/routes/gfs/legacyStandaloneGrants.ts b/control-api/src/routes/gfs/legacyStandaloneGrants.ts
new file mode 100644
index 000000000..1a462c880
--- /dev/null
+++ b/control-api/src/routes/gfs/legacyStandaloneGrants.ts
@@ -0,0 +1,65 @@
+import type { Request, Response, Router } from 'express'
+import { pool } from '../../db.js'
+import { asyncHandler } from '../../http/asyncHandler.js'
+import { requireAuthForControlUI } from '../../middleware/controlUIAuth.js'
+
+export const LEGACY_STANDALONE_HOST_SUBJECT_ID = '1st:mcp-host/standalone'
+const LEGACY_GRANT_REPORT_LIMIT = 1000
+
+export interface LegacyStandaloneGrantsDb {
+ query(text: string, values?: unknown[]): Promise<{ rows: unknown[] }>
+}
+
+export interface LegacyStandaloneGrant {
+ id: string
+ drive: string
+ resourceId: string
+ permissions: string[]
+ inherit: boolean
+}
+
+/**
+ * Read-only inventory for the bounded operator migration tool. Candidate Hosts
+ * deliberately come from the trusted Host directory instead of PostgreSQL.
+ */
+export async function listLegacyStandaloneGrants(
+ db: LegacyStandaloneGrantsDb = pool
+): Promise<LegacyStandaloneGrant[]> {
+ const result = await db.query(
+ `SELECT id, drive, resource_id, permissions, inherit
+ FROM gfs_grants
+ WHERE subject_type = 'host' AND subject_id = $1
+ ORDER BY drive ASC, resource_id ASC, id ASC
+ LIMIT $2`,
+ [LEGACY_STANDALONE_HOST_SUBJECT_ID, LEGACY_GRANT_REPORT_LIMIT + 1]
+ )
+ if (result.rows.length > LEGACY_GRANT_REPORT_LIMIT) {
+ throw new Error('legacy_grant_report_limit_exceeded')
+ }
+ return (result.rows as Array<Record<string, unknown>>).map(row => ({
+ id: String(row.id),
+ drive: String(row.drive),
+ resourceId: String(row.resource_id),
+ permissions: Array.isArray(row.permissions) ? row.permissions.map(String).sort() : [],
+ inherit: Boolean(row.inherit),
+ }))
+}
+
+export async function handleLegacyStandaloneGrantReport(
+ _req: Request,
+ res: Response
+): Promise<void> {
+ const grants = await listLegacyStandaloneGrants()
+ res.status(200).json({
+ sourceSubject: `host:${LEGACY_STANDALONE_HOST_SUBJECT_ID}`,
+ grants,
+ })
+}
+
+export function registerLegacyStandaloneGrantReportRoute(router: Router): void {
+ router.get(
+ '/gfs/grants/legacy-standalone',
+ requireAuthForControlUI,
+ asyncHandler(handleLegacyStandaloneGrantReport)
+ )
+}
diff --git a/control-api/src/routes/gfs/provisionerToken.ts b/control-api/src/routes/gfs/provisionerToken.ts
index 5493b5a57..79b2ca673 100644
--- a/control-api/src/routes/gfs/provisionerToken.ts
+++ b/control-api/src/routes/gfs/provisionerToken.ts
@@ -22,6 +22,8 @@ import { requireInternalControlJwt } from '../../middleware/internalControlJwt.j
*/
const DEFAULT_DRIVE = 'main'
+const LEGACY_STANDALONE_HCC_NAMESPACE = 'mcp-host'
+const LEGACY_STANDALONE_HCC_NAME = 'standalone'
/** Validate requested scopes against GFS_SCOPES; default to read-only (P3). */
function parseScopes(value: unknown): GfsScope[] {
@@ -76,6 +78,17 @@ export function registerGfsProvisionerTokenRoute(router: Router): void {
res.status(400).json({ error: 'subject_invalid' })
return
}
+ // `host:1st:mcp-host/standalone` is historical fleet-wide grant state,
+ // not an individual Host identity. Keep it readable for the bounded
+ // cleanup/migration flow, but never mint a new HCC credential for it.
+ if (
+ provisioner.iss === 'hcc' &&
+ namespace === LEGACY_STANDALONE_HCC_NAMESPACE &&
+ name === LEGACY_STANDALONE_HCC_NAME
+ ) {
+ res.status(409).json({ error: 'subject_reserved' })
+ return
+ }
if (!config.allowedIssuanceNamespaces.includes(namespace)) {
res.status(400).json({ error: 'invalid_issuance_namespace' })
return
diff --git a/control-api/src/routes/gfs/resources.ts b/control-api/src/routes/gfs/resources.ts
index b7211de41..5c2ee7ae9 100644
--- a/control-api/src/routes/gfs/resources.ts
+++ b/control-api/src/routes/gfs/resources.ts
@@ -1,12 +1,18 @@
+/**
+ * User-plane resource PATCH (rename/move). The structural protocol below
+ * (advisory structure lock, ancestor-chain revalidation, sorted FOR UPDATE row
+ * locks, subtree path recompute) mirrors gfs-controller/src/db/writeStore.ts —
+ * the two live in different packages, and a shared @clerum/gfs-authz
+ * extraction of the drive-lock + tree-walk skeleton is a known follow-up.
+ */
import type { Request, Response, Router } from 'express'
-import { pool } from '../../db.js'
+import { withTransaction } from '../../db.js'
import { asyncHandler } from '../../http/asyncHandler.js'
import { requireAuthForControlUI } from '../../middleware/controlUIAuth.js'
import {
type GfsCaller,
type GrantsDb,
UUID_RE,
- ancestorsOf,
auditMutation,
checkAccess,
driveOf,
@@ -14,24 +20,9 @@ import {
resolveCaller,
} from './grants.js'
-/**
- * gfs resource mutation — PATCH /resources/:id = rename and/or move (spec
- * community.md §Move, rename, delete). A move is a pure DB reparent (bytes are
- * flat by resourceId). control-api is the sole writer of resource rows (CC6);
- * the move rules mirror the writer-routed gfs-controller/src/api/move.ts (the
- * two live in different packages — a shared @clerum/gfs-authz extraction is a
- * known follow-up).
- *
- * Authorization (no operator bypass for non-operators): rename → write on the
- * resource; move → write+delete on the source parent + write on the destination
- * parent. Cross-drive move → 403 cross_boundary. Optimistic concurrency: a
- * stale If-Match (or a concurrent version bump) → 412 precondition_failed.
- */
-
const NAME_MAX = 255
// eslint-disable-next-line no-control-regex
const CONTROL_CHARS = /[\x00-\x1f\x7f]/
-
export class ResourcePatchError extends Error {
constructor(
readonly status: number,
@@ -65,28 +56,121 @@ 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(
- `SELECT resource_id, drive, parent_resource_id, name, kind, version
- FROM gfs_resources WHERE resource_id = $1::uuid AND deleted_at IS NULL`,
+ `SELECT resource_id, drive, parent_resource_id, name, kind, version, deleted_at
+ FROM gfs_resources WHERE resource_id = $1::uuid`,
[resourceId]
)
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 }
+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.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()
+ 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)
+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,
@@ -95,47 +179,80 @@ export async function applyResourcePatch(
patch: ResourcePatch,
audit: (params: Parameters<typeof auditMutation>[1]) => Promise<void>
): Promise<{ version: number }> {
- const resource = await loadResource(db, resourceId)
- if (!resource || resource.drive !== drive) {
- throw new ResourcePatchError(404, 'not_found')
- }
+ await acquireStructureLock(db, drive)
+ const observedResource = await loadResource(db, resourceId)
+ if (!observedResource || observedResource.deleted_at !== null || observedResource.drive !== drive)
+ throw new ResourcePatchError(404, 'not_found')
const wantsRename = patch.newName !== undefined
const wantsMove = patch.newParentId !== undefined
- if (!wantsRename && !wantsMove) {
- throw new ResourcePatchError(400, 'path_invalid')
- }
-
- // Optimistic concurrency: a provided If-Match must equal the current version.
- if (patch.ifMatch !== undefined) {
- const ifMatch = Number(patch.ifMatch)
- if (!Number.isInteger(ifMatch) || ifMatch !== resource.version) {
- throw new ResourcePatchError(412, 'precondition_failed')
- }
- }
-
- const name = wantsRename ? validateName(patch.newName) : resource.name
- let newParentId: string | null = resource.parent_resource_id
+ if (!wantsRename && !wantsMove) throw new ResourcePatchError(400, 'path_invalid')
const op = wantsMove
? wantsRename
? 'resource.rename+move'
: '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
+ 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' })
+ 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')
+ 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
): Promise<void> => {
if (!(await checkAccess(db, caller, drive, rid, bit))) {
- 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, 'forbidden')
}
}
@@ -145,27 +262,29 @@ export async function applyResourcePatch(
}
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')
+ const destinationChain = await loadAncestorChain(db, dest)
+ assertLiveDirectoryChain(destinationChain, drive)
+ 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)
newParentId = dest
+ parentChain = destinationChain
}
-
- // Apply with a version guard (catches a concurrent bump → precondition_failed).
let updated
try {
updated = await db.query(
@@ -176,25 +295,18 @@ export async function applyResourcePatch(
[name, newParentId, resourceId, resource.version]
)
} catch (err) {
- // Sibling uniqueness violation in the destination directory.
if ((err as { code?: string }).code === '23505') {
throw new ResourcePatchError(409, 'already_exists')
}
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)
- await audit({
- actorKey: caller.actorKey,
- targetKey: caller.actorKey,
- op,
- drive,
- resourceId,
- outcome: 'allowed',
- })
+ 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' })
return { version }
}
@@ -207,9 +319,7 @@ export async function handlePatch(req: Request, res: Response): Promise<void> {
const caller = resolveCaller(req)
const id = String(req.params.id)
if (!UUID_RE.test(id)) {
- res
- .status(400)
- .json({ ok: false, error: { code: 'path_invalid', message: 'invalid resource id' } })
+ res.status(400).json({ ok: false, error: { code: 'path_invalid', message: 'invalid resource id' } })
return
}
const body = (req.body ?? {}) as ResourcePatch
@@ -218,9 +328,23 @@ export async function handlePatch(req: Request, res: Response): Promise<void> {
)
const requestId = requestIdOf(req)
const sourceIp = req.ip
- const { version } = await applyResourcePatch(pool, caller, drive, id, body, async params => {
- await auditMutation(pool, { ...params, requestId, sourceIp })
+ let denied: ResourcePatchError | undefined
+ const patched = await withTransaction(async db => {
+ try {
+ return await applyResourcePatch(db, caller, drive, id, body, async params => {
+ await auditMutation(db, { ...params, requestId, sourceIp })
+ })
+ } catch (err) {
+ if (err instanceof ResourcePatchError && err.status === 403) {
+ denied = err
+ return null
+ }
+ throw err
+ }
})
+ if (denied) throw denied
+ if (!patched) throw new ResourcePatchError(500, 'internal_error')
+ const { version } = patched
res.status(200).json({ ok: true, data: { resourceId: id, version } })
} catch (err) {
if (err instanceof ResourcePatchError) {
diff --git a/control-api/src/routes/gfs/seed.ts b/control-api/src/routes/gfs/seed.ts
index 7041cf500..9479a1ed3 100644
--- a/control-api/src/routes/gfs/seed.ts
+++ b/control-api/src/routes/gfs/seed.ts
@@ -1,7 +1,8 @@
-import type { Router } from 'express'
-import { pool } from '../../db.js'
+import type { Request, Response, Router } from 'express'
+import { withTransaction } from '../../db.js'
import {
DbSeedResourceStore,
+ InvalidRootDirectoriesError,
SeedResourceStore,
seedRootDirectories,
} from '../../gfs/seedResources.js'
@@ -15,9 +16,9 @@ export interface HttpResult {
/**
* POST /api/v1/gfs/seed — internal endpoint (HCC → control-api). Materializes a
- * GlobalFileSystem's rootDirectories as gfs_resources rows. The governance
- * plane (control-api) is the ONLY writer of resource rows (CC6); HCC's
- * gfsReconciler calls this after the drive reaches Ready. Idempotent.
+ * GlobalFileSystem's rootDirectories as gfs_resources rows. Control API owns
+ * this bootstrap; governed runtime mutations are applied by the GFSC writer.
+ * HCC calls this after the drive reaches Ready. Idempotent.
*/
export async function seedRootDirectoriesToHttp(
store: SeedResourceStore,
@@ -30,17 +31,28 @@ export async function seedRootDirectoriesToHttp(
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 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(async (req, res) => {
- const result = await seedRootDirectoriesToHttp(new DbSeedResourceStore(pool), req.body)
- res.status(result.status).json(result.body)
- })
+ asyncHandler(handleSeed)
)
}
diff --git a/control-api/src/routes/gfs/shares.ts b/control-api/src/routes/gfs/shares.ts
index 120be637b..66890c290 100644
--- a/control-api/src/routes/gfs/shares.ts
+++ b/control-api/src/routes/gfs/shares.ts
@@ -252,7 +252,7 @@ export async function handleShareDelete(req: Request, res: Response): Promise<vo
String(row.resource_id),
(row.permissions as GfsPermission[]) ?? ['share'],
subject,
- { isShare: true }
+ { isShare: true, allowLegacyRetirement: true }
)
} catch (error) {
if (!(error instanceof GfsGrantError)) throw error
diff --git a/control-api/src/services/access/mcpInvocable.ts b/control-api/src/services/access/mcpInvocable.ts
index 59b40f90a..b8dc38219 100644
--- a/control-api/src/services/access/mcpInvocable.ts
+++ b/control-api/src/services/access/mcpInvocable.ts
@@ -13,18 +13,22 @@
* - `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,
+} from '../directory/accessReconciliation.js'
export interface InvocableMcpServer {
name: string
url: string
}
-export interface AgentWithMcpServers {
- name: string
+export interface AgentWithMcpServers extends AgentDirectoryEntry {
contextRef: string | null
mcpServers: Array<{ name: string }>
}
@@ -43,8 +47,39 @@ interface McpServerCR {
}
interface HostCR {
- metadata?: { name?: string }
- spec?: { contextRef?: string }
+ metadata?: {
+ name?: string
+ namespace?: string
+ deletionTimestamp?: string | null
+ }
+ spec?: { contextRef?: string; enabled?: boolean; host?: string }
+}
+
+/**
+ * Recognize the stable Kubernetes "resource does not exist" signal without
+ * confusing RBAC, API availability, or transport failures with deletion.
+ * The client and gateway wrappers used by Control API expose 404 in several
+ * compatible shapes, so classification must inspect the status fields rather
+ * than error text.
+ */
+export function isK8sResourceNotFound(error: unknown): boolean {
+ if (!error || typeof error !== 'object') return false
+ const candidate = error as {
+ name?: unknown
+ statusCode?: unknown
+ code?: unknown
+ body?: { code?: unknown }
+ response?: { status?: unknown; statusCode?: unknown; body?: { code?: unknown } }
+ }
+ return (
+ candidate.name === 'K8sNotFoundError' ||
+ candidate.statusCode === 404 ||
+ candidate.code === 404 ||
+ candidate.body?.code === 404 ||
+ candidate.response?.status === 404 ||
+ candidate.response?.statusCode === 404 ||
+ candidate.response?.body?.code === 404
+ )
}
function asArray<T>(value: unknown): T[] {
@@ -172,7 +207,9 @@ export async function resolveInvocableMcpServersForContexts(
* is required. Passing an unauthorized agentName leaks that agent's MCP
* server names.
*
- * Returns one entry per input `agentNames` in the same order.
+ * Returns valid, active entries in the same order as `agentNames`. Each Host is
+ * fetched by its already-authorized name; this resolver never lists or
+ * serializes Hosts outside the caller's authorization result.
*/
export async function resolveMcpServersForAgents(
gateway: K8sGateway,
@@ -185,44 +222,88 @@ export async function resolveMcpServersForAgents(
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 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)
+ )
+ } 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)
}
- const allowedByContext =
- scopedContextIds.size === 0
- ? new Map<string, Set<string>>()
- : await loadAllowedNamesByContext(gateway, mcpServersNamespace, scopedContextIds)
+ let allowedByContext = new Map<string, Set<string>>()
+ if (scopedContextIds.size > 0) {
+ try {
+ allowedByContext = await loadAllowedNamesByContext(
+ gateway,
+ mcpServersNamespace,
+ scopedContextIds
+ )
+ } catch (err) {
+ // Preserve the authorized directory DTOs with an empty tool catalog —
+ // loudly, so a Context-read outage is distinguishable from "no tools".
+ console.error(
+ '[mcpInvocable] context allowlist load failed; directory served with empty tool catalogs:',
+ err instanceof Error ? err.message : String(err)
+ )
+ }
+ }
- return agentNames.map(agentName => {
- const host = hostByName.get(agentName)
+ return visibleHosts.map(({ host, directoryEntry }) => {
const contextRef = host?.spec?.contextRef ?? null
if (!contextRef) {
- return { name: agentName, contextRef, mcpServers: [] }
+ return { ...directoryEntry, contextRef, mcpServers: [] }
}
const allowed = allowedByContext.get(contextRef)
if (!allowed || allowed.size === 0) {
- return { name: agentName, contextRef, mcpServers: [] }
+ return { ...directoryEntry, contextRef, mcpServers: [] }
}
const invocable = filterInvocable(allowed, serverList, mcpServersNamespace)
const names = [...invocable].sort((a, b) => a.localeCompare(b))
return {
- name: agentName,
+ ...directoryEntry,
contextRef,
mcpServers: names.map(name => ({ name })),
}
diff --git a/control-api/src/services/directory/accessReconciliation.ts b/control-api/src/services/directory/accessReconciliation.ts
index 077fc75fc..60b77d793 100644
--- a/control-api/src/services/directory/accessReconciliation.ts
+++ b/control-api/src/services/directory/accessReconciliation.ts
@@ -1,9 +1,14 @@
import { config } from '../../config.js'
+import { makeHostSubjectId } from '../../gfs/hostSubject.js'
import type { K8sGateway } from '../../k8s.js'
type HostResource = {
- metadata?: { name?: string }
- spec?: { enabled?: boolean }
+ metadata?: {
+ name?: string
+ namespace?: string
+ deletionTimestamp?: string | null
+ }
+ spec?: { enabled?: boolean; host?: string }
}
type ContextResource = {
@@ -16,8 +21,62 @@ 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 (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() : ''
+ 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 {
+ constructor(public readonly limit: number) {
+ super(`deleted agent history exceeds the ${limit}-entry limit`)
+ this.name = 'DeletedAgentHistoryLimitError'
+ }
+}
+
export function normalizeUnique(values: unknown[]): string[] {
const seen = new Set<string>()
const normalized: string[] = []
@@ -30,6 +89,14 @@ export function normalizeUnique(values: unknown[]): string[] {
return normalized
}
+export function accessValueSetsEqual(left: unknown[], right: unknown[]): boolean {
+ const normalizedLeft = normalizeUnique(left)
+ const normalizedRight = normalizeUnique(right)
+ if (normalizedLeft.length !== normalizedRight.length) return false
+ const rightSet = new Set(normalizedRight)
+ return normalizedLeft.every(value => rightSet.has(value))
+}
+
export function filterAccessValues(
values: unknown,
activeValues: ReadonlySet<string> | null
@@ -69,12 +136,46 @@ export function mergeActiveUpdateWithDeletedHistory(
return normalizeUnique([...activeRequested, ...retainedDeletedHistory])
}
+/** Agent grants must never silently discard retained deleted-host history. */
+export function mergeActiveAgentUpdateWithDeletedHistory(
+ requestedValues: unknown[],
+ activeValues: Iterable<string>,
+ deletedHistory: unknown[]
+): string[] {
+ const activeSet = new Set(normalizeUnique(Array.from(activeValues)))
+ const retainedDeletedHistory = normalizeUnique(deletedHistory).filter(
+ value => !activeSet.has(value)
+ )
+ if (retainedDeletedHistory.length > MAX_DELETED_ACCESS_HISTORY) {
+ throw new DeletedAgentHistoryLimitError(MAX_DELETED_ACCESS_HISTORY)
+ }
+ const activeRequested = normalizeUnique(requestedValues).filter(value => activeSet.has(value))
+ return normalizeUnique([...activeRequested, ...retainedDeletedHistory])
+}
+
+// A namespace-scoped list query already guarantees every returned Host lives
+// in the queried namespace, so a resource that omits `metadata.namespace` is
+// still first-party. Default it to the scoped namespace before running the
+// strict directory-entry filter. buildAgentDirectoryEntry itself stays strict
+// (an absent namespace is rejected) for callers that resolve a single Host
+// from a broader or untrusted source.
+function withScopedNamespace(host: HostResource, scopedNamespace: string): HostResource {
+ if (host?.metadata?.namespace) return host
+ return { ...host, metadata: { ...host?.metadata, namespace: scopedNamespace } }
+}
+
export async function listActiveAgentNames(gateway: K8sGateway): Promise<string[]> {
const listed = await gateway.listResource('hosts', config.hostsNamespace)
const hosts = Array.isArray(listed) ? (listed as HostResource[]) : []
return normalizeUnique(
hosts
- .map(host => host?.metadata?.name)
+ .map(
+ host =>
+ buildAgentDirectoryEntry(
+ withScopedNamespace(host, config.hostsNamespace),
+ config.hostsNamespace
+ )?.name
+ )
.filter((value): value is string => typeof value === 'string')
)
}
diff --git a/control-api/test/accessReconciliation.test.ts b/control-api/test/accessReconciliation.test.ts
index bf02dd169..0a995ad59 100644
--- a/control-api/test/accessReconciliation.test.ts
+++ b/control-api/test/accessReconciliation.test.ts
@@ -1,7 +1,13 @@
-import { describe, expect, it } from 'vitest'
+import { describe, expect, it, vi } from 'vitest'
+import type { K8sGateway } from '../src/k8s.js'
import {
+ DeletedAgentHistoryLimitError,
MAX_DELETED_ACCESS_HISTORY,
+ accessValueSetsEqual,
+ buildAgentDirectoryEntry,
filterAccessValues,
+ listActiveAgentNames,
+ mergeActiveAgentUpdateWithDeletedHistory,
mergeActiveUpdateWithDeletedHistory,
normalizeUnique,
} from '../src/services/directory/accessReconciliation.js'
@@ -29,4 +35,114 @@ describe('access reconciliation helpers', () => {
expect(merged.at(-1)).toBe(`deleted-${MAX_DELETED_ACCESS_HISTORY}`)
expect(merged).not.toContain(`deleted-${MAX_DELETED_ACCESS_HISTORY + 1}`)
})
+
+ 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}`
+ )
+
+ expect(mergeActiveAgentUpdateWithDeletedHistory(['active-a'], ['active-a'], atLimit)).toEqual([
+ 'active-a',
+ ...atLimit,
+ ])
+ expect(() =>
+ mergeActiveAgentUpdateWithDeletedHistory(
+ ['active-a'],
+ ['active-a'],
+ [...atLimit, 'deleted-over-limit']
+ )
+ ).toThrow(DeletedAgentHistoryLimitError)
+ })
})
diff --git a/control-api/test/db.gfsAuditDecisionEvidenceMigration.test.ts b/control-api/test/db.gfsAuditDecisionEvidenceMigration.test.ts
new file mode 100644
index 000000000..eeae409c4
--- /dev/null
+++ b/control-api/test/db.gfsAuditDecisionEvidenceMigration.test.ts
@@ -0,0 +1,30 @@
+import { readFileSync } from 'node:fs'
+import { describe, expect, it } from 'vitest'
+
+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 --git a/control-api/test/db.gfsBlobGenerationMigration.test.ts b/control-api/test/db.gfsBlobGenerationMigration.test.ts
new file mode 100644
index 000000000..1c6619078
--- /dev/null
+++ b/control-api/test/db.gfsBlobGenerationMigration.test.ts
@@ -0,0 +1,21 @@
+import { readFileSync } from 'node:fs'
+import { describe, expect, it } from 'vitest'
+
+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))
+
+ 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 --git a/control-api/test/db.gfsReaderRoleMigration.test.ts b/control-api/test/db.gfsReaderRoleMigration.test.ts
new file mode 100644
index 000000000..ba420391b
--- /dev/null
+++ b/control-api/test/db.gfsReaderRoleMigration.test.ts
@@ -0,0 +1,34 @@
+import { readFileSync } from 'node:fs'
+import { describe, expect, it } from 'vitest'
+
+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(
+ '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 --git a/control-api/test/db.gfsRuntimeRoleContractMigration.test.ts b/control-api/test/db.gfsRuntimeRoleContractMigration.test.ts
new file mode 100644
index 000000000..6d114ca47
--- /dev/null
+++ b/control-api/test/db.gfsRuntimeRoleContractMigration.test.ts
@@ -0,0 +1,47 @@
+import { readFileSync } from 'node:fs'
+import { describe, expect, it } from 'vitest'
+
+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 --git a/control-api/test/db.ready.test.ts b/control-api/test/db.ready.test.ts
index 2d99f91c1..4fcb65b17 100644
--- a/control-api/test/db.ready.test.ts
+++ b/control-api/test/db.ready.test.ts
@@ -2,12 +2,12 @@ import { describe, expect, it, vi } from 'vitest'
import { assertDbReady } from '../src/db.js'
describe('assertDbReady', () => {
- it('accepts a database migrated through the authoritative approval step binding', async () => {
+ it('accepts a database migrated through the authoritative GFS runtime role contract', async () => {
const query = vi.fn().mockResolvedValue({ rows: [{ ready: true }], rowCount: 1 })
await expect(assertDbReady({ query })).resolves.toBeUndefined()
expect(query).toHaveBeenCalledWith(expect.stringContaining('schema_migrations'), [
- '0070_member_registration_runtime_delete_revoke',
+ '0074_gfs_runtime_role_exact_contract',
])
})
@@ -15,7 +15,7 @@ describe('assertDbReady', () => {
const query = vi.fn().mockResolvedValue({ rows: [{ ready: false }], rowCount: 1 })
await expect(assertDbReady({ query })).rejects.toThrow(
- 'migration 0070_member_registration_runtime_delete_revoke is required'
+ 'migration 0074_gfs_runtime_role_exact_contract is required'
)
})
})
diff --git a/control-api/test/db.realPostgresMigration.integration.test.ts b/control-api/test/db.realPostgresMigration.integration.test.ts
index 15115ce21..9746b6102 100644
--- a/control-api/test/db.realPostgresMigration.integration.test.ts
+++ b/control-api/test/db.realPostgresMigration.integration.test.ts
@@ -409,6 +409,7 @@ describeRealPostgres('control-api real Postgres migrations', () => {
expectedControlApiRelations[relation] ?? []
)
}
+ expectPrivileges([...(controlApiRelations.gfs_blob_manifests ?? new Set())], [])
const maintenanceRelations = await relationPrivileges(dbPool, 'trace_maintenance_runtime')
const expectedMaintenanceRelations: Record<string, string[]> = {
diff --git a/control-api/test/db.withTransaction.test.ts b/control-api/test/db.withTransaction.test.ts
new file mode 100644
index 000000000..2af1d82c4
--- /dev/null
+++ b/control-api/test/db.withTransaction.test.ts
@@ -0,0 +1,101 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const clientQuery = vi.fn()
+const clientRelease = vi.fn()
+const mockConnect = vi.fn()
+const mockPoolCtor = vi.fn(function MockPool() {
+ return {
+ connect: mockConnect,
+ query: vi.fn(),
+ }
+})
+
+vi.mock('pg', () => ({
+ Pool: mockPoolCtor,
+}))
+
+describe('db.withTransaction', () => {
+ beforeEach(() => {
+ vi.resetModules()
+ vi.clearAllMocks()
+ mockConnect.mockResolvedValue({
+ query: clientQuery,
+ release: clientRelease,
+ })
+ clientQuery.mockResolvedValue({ rows: [], rowCount: 0 })
+ })
+
+ it('commits successful work and releases the client for reuse', async () => {
+ const { withTransaction } = await import('../src/db.js')
+
+ await expect(withTransaction(async () => 'result')).resolves.toBe('result')
+
+ expect(clientQuery.mock.calls.map(([sql]) => sql)).toEqual(['BEGIN', 'COMMIT'])
+ expect(clientRelease).toHaveBeenCalledOnce()
+ expect(clientRelease).toHaveBeenCalledWith(undefined)
+ })
+
+ it('rolls back failed work, preserves its error, and releases the client for reuse', async () => {
+ const workError = new Error('work failed')
+ const { withTransaction } = await import('../src/db.js')
+
+ await expect(
+ withTransaction(async () => {
+ throw workError
+ })
+ ).rejects.toBe(workError)
+
+ expect(clientQuery.mock.calls.map(([sql]) => sql)).toEqual(['BEGIN', 'ROLLBACK'])
+ expect(clientRelease).toHaveBeenCalledOnce()
+ expect(clientRelease).toHaveBeenCalledWith(undefined)
+ })
+
+ it('destroys the client when BEGIN fails before work can run', async () => {
+ const beginError = new Error('begin failed')
+ const work = vi.fn()
+ clientQuery.mockRejectedValueOnce(beginError)
+ const { withTransaction } = await import('../src/db.js')
+
+ await expect(withTransaction(work)).rejects.toBe(beginError)
+
+ expect(work).not.toHaveBeenCalled()
+ expect(clientQuery.mock.calls.map(([sql]) => sql)).toEqual(['BEGIN'])
+ expect(clientRelease).toHaveBeenCalledOnce()
+ expect(clientRelease).toHaveBeenCalledWith(beginError)
+ })
+
+ it('destroys the client when rollback fails while preserving the work error', async () => {
+ const workError = new Error('work failed')
+ const rollbackError = new Error('rollback response failed')
+ clientQuery.mockImplementation(async (sql: string) => {
+ if (sql === 'ROLLBACK') throw rollbackError
+ return { rows: [], rowCount: 0 }
+ })
+ const { withTransaction } = await import('../src/db.js')
+
+ await expect(
+ withTransaction(async () => {
+ throw workError
+ })
+ ).rejects.toBe(workError)
+
+ expect(clientQuery.mock.calls.map(([sql]) => sql)).toEqual(['BEGIN', 'ROLLBACK'])
+ expect(clientRelease).toHaveBeenCalledOnce()
+ expect(clientRelease).toHaveBeenCalledWith(rollbackError)
+ })
+
+ it('destroys the client and does not roll back when the commit response fails', async () => {
+ const commitError = new Error('commit response failed')
+ clientQuery.mockImplementation(async (sql: string) => {
+ if (sql === 'COMMIT') throw commitError
+ return { rows: [], rowCount: 0 }
+ })
+ const { withTransaction } = await import('../src/db.js')
+
+ await expect(withTransaction(async () => 'result')).rejects.toBe(commitError)
+
+ expect(clientQuery.mock.calls.map(([sql]) => sql)).toEqual(['BEGIN', 'COMMIT'])
+ expect(clientRelease).toHaveBeenCalledOnce()
+ expect(clientRelease).toHaveBeenCalledWith(commitError)
+ })
+})
diff --git a/control-api/test/deploy.gfsProvisioning.test.ts b/control-api/test/deploy.gfsProvisioning.test.ts
index 748844875..ad629cbd9 100644
--- a/control-api/test/deploy.gfsProvisioning.test.ts
+++ b/control-api/test/deploy.gfsProvisioning.test.ts
@@ -1,5 +1,7 @@
import { describe, expect, it } from 'vitest'
import { readFileSync } from 'node:fs'
+import { spawnSync } from 'node:child_process'
+import { fileURLToPath } from 'node:url'
function read(relativeFromRepoRoot: string): string {
return readFileSync(new URL(relativeFromRepoRoot, import.meta.url), 'utf-8')
@@ -7,22 +9,162 @@ function read(relativeFromRepoRoot: string): string {
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 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 writer = script.slice(script.lastIndexOf('rotate-writer)'))
+ 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).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'))
+ })
+
+ it('adopts legacy writer state without rotating or restarting it', () => {
+ 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('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('[ "$(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('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('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')
+ 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()'))
+ 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(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": "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 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 --git a/control-api/test/gfs.seedResources.test.ts b/control-api/test/gfs.seedResources.test.ts
index bdfddd3bc..45bf57b17 100644
--- a/control-api/test/gfs.seedResources.test.ts
+++ b/control-api/test/gfs.seedResources.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest'
import {
DbSeedResourceStore,
+ InvalidRootDirectoriesError,
SeedDb,
SeedResourceStore,
seedRootDirectories,
@@ -15,8 +16,13 @@ interface Row {
class FakeStore implements SeedResourceStore {
rows = new Map<string, { id: string; row: Row }>()
+ lockedDrives: string[] = []
private seq = 0
+ async acquireStructureLock(drive: string): Promise<void> {
+ this.lockedDrives.push(drive)
+ }
+
private key(drive: string, parent: string | null, name: string): string {
return `${drive}|${parent ?? 'ROOT'}|${name}`
}
@@ -40,6 +46,7 @@ describe('seedRootDirectories (synthetic root model)', () => {
expect(roots[0].row.name).toBe('')
expect(roots[0].row.pathCache).toBe('/')
expect(roots[0].id).toBe(rootResourceId)
+ expect(store.lockedDrives).toEqual(['main'])
})
it('hangs a single-segment rootDirectory off the root with the right path_cache', async () => {
@@ -83,6 +90,24 @@ describe('seedRootDirectories (synthetic root model)', () => {
const orgs = [...store.rows.values()].filter(r => r.row.name === 'org')
expect(orgs).toHaveLength(1) // /org shared by both leaves
})
+
+ it.each([
+ 'relative',
+ '/org//x',
+ '/org/',
+ '/./x',
+ '/../x',
+ '/e\u0301',
+ '/bad\u0000name',
+ `/${'x'.repeat(256)}`,
+ ])('rejects non-canonical rootDirectory %j before locking or writing', async path => {
+ const store = new FakeStore()
+ await expect(seedRootDirectories(store, 'main', [path])).rejects.toBeInstanceOf(
+ InvalidRootDirectoriesError
+ )
+ expect(store.lockedDrives).toEqual([])
+ expect(store.rows.size).toBe(0)
+ })
})
class FakeDb implements SeedDb {
@@ -95,9 +120,27 @@ class FakeDb implements SeedDb {
}
describe('DbSeedResourceStore.ensureDirectory (idempotent upsert)', () => {
+ const root = {
+ resource_id: 'root-1',
+ drive: 'main',
+ parent_resource_id: null,
+ name: '',
+ kind: 'directory',
+ path_cache: '/',
+ deleted_at: null,
+ cycle: false,
+ }
+
+ it('uses the shared transaction-scoped drive lock key', async () => {
+ const db = new FakeDb()
+ await new DbSeedResourceStore(db).acquireStructureLock('main')
+ expect(db.queries[0].text).toContain("hashtext('gfs:structure:' || $1)")
+ expect(db.queries[0].values).toEqual(['main'])
+ })
+
it('inserts the synthetic root with the root conflict target and returns its id', async () => {
const db = new FakeDb()
- db.responses = [{ rows: [{ resource_id: 'root-1' }] }]
+ db.responses = [{ rows: [] }, { rows: [{ resource_id: 'root-1' }] }]
const id = await new DbSeedResourceStore(db).ensureDirectory({
drive: 'main',
parentResourceId: null,
@@ -105,13 +148,13 @@ describe('DbSeedResourceStore.ensureDirectory (idempotent upsert)', () => {
pathCache: '/',
})
expect(id).toBe('root-1')
- expect(db.queries[0].text).toContain('ON CONFLICT (drive) WHERE parent_resource_id IS NULL')
- expect(db.queries[0].text).toContain('DO NOTHING')
+ expect(db.queries[1].text).toContain('ON CONFLICT (drive) WHERE parent_resource_id IS NULL')
+ expect(db.queries[1].text).toContain('DO NOTHING')
})
- it('falls back to SELECT when the root already exists (insert returns no row)', async () => {
+ it('returns the canonical root after locking it', async () => {
const db = new FakeDb()
- db.responses = [{ rows: [] }, { rows: [{ resource_id: 'root-existing' }] }]
+ db.responses = [{ rows: [{ ...root, resource_id: 'root-existing' }] }]
const id = await new DbSeedResourceStore(db).ensureDirectory({
drive: 'main',
parentResourceId: null,
@@ -119,13 +162,18 @@ describe('DbSeedResourceStore.ensureDirectory (idempotent upsert)', () => {
pathCache: '/',
})
expect(id).toBe('root-existing')
- expect(db.queries).toHaveLength(2)
- expect(db.queries[1].text).toContain('SELECT resource_id')
+ expect(db.queries).toHaveLength(1)
+ expect(db.queries[0].text).toContain('ORDER BY resource_id FOR UPDATE')
})
it('inserts a sub-directory with the sibling conflict target', async () => {
const db = new FakeDb()
- db.responses = [{ rows: [{ resource_id: 'org-1' }] }]
+ db.responses = [
+ { rows: [root] },
+ { rows: [root] },
+ { rows: [root] },
+ { rows: [{ resource_id: 'org-1' }] },
+ ]
const id = await new DbSeedResourceStore(db).ensureDirectory({
drive: 'main',
parentResourceId: 'root-1',
@@ -133,13 +181,15 @@ describe('DbSeedResourceStore.ensureDirectory (idempotent upsert)', () => {
pathCache: '/org',
})
expect(id).toBe('org-1')
- expect(db.queries[0].text).toContain('ON CONFLICT (drive, parent_resource_id, name)')
- expect(db.queries[0].values).toEqual(['main', 'root-1', 'org', '/org'])
+ expect(db.queries[1].text).toContain('ORDER BY resource_id FOR UPDATE')
+ expect(db.queries[1].values?.[0]).toEqual(['root-1'])
+ expect(db.queries[3].text).toContain('ON CONFLICT (drive, parent_resource_id, name)')
+ expect(db.queries[3].values).toEqual(['main', 'root-1', 'org', '/org'])
})
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: [] }]
await expect(
new DbSeedResourceStore(db).ensureDirectory({
drive: 'main',
diff --git a/control-api/test/gfs.seedRoute.test.ts b/control-api/test/gfs.seedRoute.test.ts
index 282ee455a..5732c01bf 100644
--- a/control-api/test/gfs.seedRoute.test.ts
+++ b/control-api/test/gfs.seedRoute.test.ts
@@ -5,6 +5,7 @@ import { seedRootDirectoriesToHttp } from '../src/routes/gfs/seed.js'
class FakeStore implements SeedResourceStore {
calls: { drive: string; parentResourceId: string | null; name: string }[] = []
private seq = 0
+ async acquireStructureLock(): Promise<void> {}
async ensureDirectory(input: {
drive: string
parentResourceId: string | null
@@ -38,6 +39,16 @@ describe('seedRootDirectoriesToHttp', () => {
).toBe(400)
})
+ it.each(['relative', '/org//x', '/org/', '/./x', '/../x', '/e\u0301'])(
+ '400 invalid_rootDirectories for non-canonical path %j',
+ async path => {
+ const store = new FakeStore()
+ const out = await seedRootDirectoriesToHttp(store, { drive: 'main', rootDirectories: [path] })
+ expect(out).toEqual({ status: 400, body: { error: 'invalid_rootDirectories' } })
+ expect(store.calls).toEqual([])
+ }
+ )
+
it('200 + seeds the root and the requested directories', async () => {
const store = new FakeStore()
const out = await seedRootDirectoriesToHttp(store, {
diff --git a/control-api/test/gfs.seedRouteTransaction.test.ts b/control-api/test/gfs.seedRouteTransaction.test.ts
new file mode 100644
index 000000000..759f03668
--- /dev/null
+++ b/control-api/test/gfs.seedRouteTransaction.test.ts
@@ -0,0 +1,85 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+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 --git a/control-api/test/gfsAuditDecisionEvidence.realPostgres.integration.test.ts b/control-api/test/gfsAuditDecisionEvidence.realPostgres.integration.test.ts
new file mode 100644
index 000000000..0e5168b45
--- /dev/null
+++ b/control-api/test/gfsAuditDecisionEvidence.realPostgres.integration.test.ts
@@ -0,0 +1,187 @@
+import { randomBytes } from 'node:crypto'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+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',
+ ]]
+ )
+ 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 --git a/control-api/test/gfsBlobMigration.realPostgres.integration.test.ts b/control-api/test/gfsBlobMigration.realPostgres.integration.test.ts
new file mode 100644
index 000000000..1d9bea0e4
--- /dev/null
+++ b/control-api/test/gfsBlobMigration.realPostgres.integration.test.ts
@@ -0,0 +1,139 @@
+import { randomBytes, randomUUID } from 'node:crypto'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+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',
+ ])
+ 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',
+ ])
+ 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',
+ ])
+ 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,
+ })
+ })
+
+ 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 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
+ (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' })
+ })
+})
diff --git a/control-api/test/gfsCopy.realPostgres.integration.test.ts b/control-api/test/gfsCopy.realPostgres.integration.test.ts
new file mode 100644
index 000000000..55e0eff92
--- /dev/null
+++ b/control-api/test/gfsCopy.realPostgres.integration.test.ts
@@ -0,0 +1,295 @@
+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'
+
+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')!)
+ 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)
+ 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 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))))
+ )
+ 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 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 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 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]
+ )
+ expect(copied.rows[0]?.count).toBe(0)
+ expect(manifests.rows[0]?.count).toBe(0)
+ expect(outcome.rows).toEqual([{ mutation_outcome: 'failed' }])
+ })
+})
diff --git a/control-api/test/gfsGrants.test.ts b/control-api/test/gfsGrants.test.ts
index 728e658ad..93781d5fc 100644
--- a/control-api/test/gfsGrants.test.ts
+++ b/control-api/test/gfsGrants.test.ts
@@ -356,7 +356,7 @@ describe('assertMayGrantBatch — common grant authorization', () => {
const targets = [
{ type: 'user', id: USER_ID },
{ type: 'team', id: TEAM_ID },
- { type: 'host', id: '1st:mcp-host/standalone' },
+ { type: 'host', id: '1st:mcp-host/agent-a' },
] as const
await expect(
@@ -373,7 +373,7 @@ describe('assertMayGrantBatch — common grant authorization', () => {
expect(queries[0]?.values).toEqual(['main', R, ['user', 'team'], ['owner', 'owners']])
})
- it('keeps the existing operator host policy intact for bulk API grants', async () => {
+ it('keeps the existing operator host policy intact for bulk API grants to third-party hosts', async () => {
const db = mockDb({})
await expect(
assertMayGrantBatch(
@@ -382,13 +382,65 @@ describe('assertMayGrantBatch — common grant authorization', () => {
'main',
R,
perms('read', 'write', 'delete', 'manage_acl', 'share'),
+ [{ type: 'host', id: '3rd:sandbox-recipes/daily-report' }],
+ { isShare: false }
+ )
+ ).resolves.toBeUndefined()
+ })
+
+ it('rejects the retired fleet-wide standalone subject in bulk grants', async () => {
+ const db = mockDb({})
+ await expect(
+ assertMayGrantBatch(
+ db,
+ operator,
+ 'main',
+ R,
+ perms('read', 'write'),
[
+ { type: 'host', id: '1st:mcp-host/agent-a' },
{ type: 'host', id: '1st:mcp-host/standalone' },
- { type: 'host', id: '3rd:sandbox-recipes/daily-report' },
],
{ isShare: false }
)
- ).resolves.toBeUndefined()
+ ).rejects.toMatchObject({ status: 403, code: 'legacy_standalone_subject_reserved' })
+ })
+
+ it('caps managed first-party hosts to read/write in bulk grants', async () => {
+ const db = mockDb({})
+ await expect(
+ assertMayGrantBatch(
+ db,
+ operator,
+ 'main',
+ R,
+ perms('read', 'write', 'delete'),
+ [{ type: 'host', id: '1st:mcp-host/agent-a' }],
+ { isShare: false }
+ )
+ ).rejects.toMatchObject({ status: 403, code: 'managed_agent_permission_forbidden' })
+ })
+
+ it('rejects the entire plural bulk grant when one managed first-party host exceeds read/write', async () => {
+ const queries: QueryCall[] = []
+ const db = mockDb({ queries })
+ await expect(
+ assertMayGrantBatch(
+ db,
+ operator,
+ 'main',
+ R,
+ perms('read', 'write', 'share'),
+ [
+ { type: 'user', id: USER_ID },
+ { type: 'host', id: '1st:mcp-host/agent-a' },
+ ],
+ { isShare: false }
+ )
+ ).rejects.toMatchObject({ status: 403, code: 'managed_agent_permission_forbidden' })
+ // Target policy is fail-closed for the whole batch: no authority load, no
+ // grant written — not even for the otherwise-legitimate user target.
+ expect(queries).toHaveLength(0)
})
it('keeps the existing caller-dependent host restriction intact', async () => {
@@ -400,7 +452,7 @@ describe('assertMayGrantBatch — common grant authorization', () => {
'main',
R,
perms('manage_acl'),
- [{ type: 'host', id: '1st:mcp-host/standalone' }],
+ [{ type: 'host', id: '3rd:sandbox-recipes/daily-report' }],
{ isShare: false }
)
).rejects.toMatchObject({ status: 403, code: 'agent_manager_forbidden' })
@@ -601,7 +653,7 @@ describe('assertMayGrant — agent (host) restrictions', () => {
).rejects.toMatchObject({ status: 403, code: 'operator_grant_forbidden' })
})
- it('forbids a folder owner from making an agent a manager (manage_acl)', async () => {
+ it('forbids any caller from giving a managed first-party agent non-data-plane bits', async () => {
const db = mockDb({
ancestors: { [R]: [R] },
grants: [
@@ -614,17 +666,79 @@ describe('assertMayGrant — agent (host) restrictions', () => {
},
],
})
+ for (const permission of ['delete', 'manage_acl', 'share'] as const) {
+ await expect(
+ assertMayGrant(
+ db,
+ operator,
+ 'main',
+ R,
+ perms(permission),
+ { type: 'host', id: '1st:mcp-host/agent-a' },
+ { isShare: false }
+ )
+ ).rejects.toMatchObject({ status: 403, code: 'managed_agent_permission_forbidden' })
+ }
+ })
+
+ it('reserves the legacy fleet-wide subject while allowing explicit retirement', async () => {
+ const target = { type: 'host' as const, id: '1st:mcp-host/standalone' }
+
+ await expect(
+ assertMayGrant(mockDb({}), operator, 'main', R, perms('read', 'write'), target, {
+ isShare: false,
+ })
+ ).rejects.toMatchObject({ status: 403, code: 'legacy_standalone_subject_reserved' })
+
await expect(
assertMayGrant(
- db,
- user('owner'),
+ mockDb({}),
+ operator,
'main',
R,
- perms('manage_acl'),
- { type: 'host', id: '1st:mcp-host/standalone' },
+ perms('read', 'write', 'delete', 'manage_acl', 'share'),
+ target,
+ {
+ isShare: false,
+ allowLegacyRetirement: true,
+ }
+ )
+ ).resolves.toBeUndefined()
+ })
+
+ it('lets revocation remove an over-privileged individual host grant', async () => {
+ // Rows stored before the managed-agent envelope existed (e.g. delete on a
+ // 1st-party host) must stay deletable: the revoke path re-runs the policy
+ // with the stored permissions and allowLegacyRetirement, which exempts the
+ // envelope without reopening sentinel creation.
+ const target = { type: 'host' as const, id: '1st:mcp-host/agent-a' }
+
+ await expect(
+ assertMayGrant(mockDb({}), operator, 'main', R, perms('read', 'write', 'delete'), target, {
+ isShare: false,
+ allowLegacyRetirement: true,
+ })
+ ).resolves.toBeUndefined()
+
+ await expect(
+ assertMayGrant(mockDb({}), operator, 'main', R, perms('read', 'write', 'delete'), target, {
+ isShare: false,
+ })
+ ).rejects.toMatchObject({ status: 403, code: 'managed_agent_permission_forbidden' })
+ })
+
+ it('does not reserve an individual Host named standalone in another namespace', async () => {
+ await expect(
+ assertMayGrant(
+ mockDb({}),
+ operator,
+ 'main',
+ R,
+ perms('read', 'write'),
+ { type: 'host', id: '1st:custom-hosts/standalone' },
{ isShare: false }
)
- ).rejects.toMatchObject({ status: 403, code: 'agent_manager_forbidden' })
+ ).resolves.toBeUndefined()
})
it('lets the operator grant write to an agent (allowed)', async () => {
@@ -636,12 +750,51 @@ describe('assertMayGrant — agent (host) restrictions', () => {
'main',
R,
perms('read', 'write'),
- { type: 'host', id: '1st:mcp-host/standalone' },
+ { type: 'host', id: '1st:mcp-host/agent-a' },
{ isShare: false }
)
).resolves.toBeUndefined()
})
+ it('preserves operator grant compatibility for third-party hosts', async () => {
+ await expect(
+ assertMayGrant(
+ mockDb({}),
+ operator,
+ 'main',
+ R,
+ perms('delete', 'manage_acl', 'share'),
+ { type: 'host', id: '3rd:sandbox-recipes/plugin-a' },
+ { isShare: false }
+ )
+ ).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,
+ }],
+ })
+
+ 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] },
@@ -662,7 +815,7 @@ describe('assertMayGrant — agent (host) restrictions', () => {
'main',
R,
perms('read'),
- { type: 'host', id: '1st:mcp-host/standalone' },
+ { type: 'host', id: '1st:mcp-host/agent-a' },
{ isShare: true }
)
).rejects.toMatchObject({ status: 403, code: 'share_to_agent_forbidden' })
diff --git a/control-api/test/gfsHostSubject.test.ts b/control-api/test/gfsHostSubject.test.ts
index 2e7973c02..c73c4206e 100644
--- a/control-api/test/gfsHostSubject.test.ts
+++ b/control-api/test/gfsHostSubject.test.ts
@@ -1,7 +1,24 @@
+import { readFileSync } from 'node:fs'
import { describe, expect, it } from 'vitest'
import { makeHostSubjectId } from '../src/gfs/hostSubject.js'
import { parseSubject } from '../src/routes/gfs/grants.js'
+type HostSubjectVector = {
+ label: string
+ namespace: string
+ name: string
+ displayText: string
+ expectedSubjectId: string | null
+ expectedSubject: string | null
+}
+
+const vectors = JSON.parse(
+ readFileSync(
+ new URL('../../tests/contracts/gfs-host-subject-vectors.json', import.meta.url),
+ 'utf8'
+ )
+) as HostSubjectVector[]
+
describe('GFS host subjects', () => {
it('accepts only canonical first- and third-party host subjects', () => {
expect(parseSubject({ type: 'host', id: '1st:mcp-host/standalone' })).toEqual({
@@ -26,8 +43,17 @@ describe('GFS host subjects', () => {
}
})
- it('normalizes provisioner host subject ids through one helper', () => {
- expect(makeHostSubjectId('1st', 'mcp-host', 'standalone')).toBe('1st:mcp-host/standalone')
+ it.each(vectors)('derives the canonical durable identity: $label', vector => {
+ const actual = makeHostSubjectId('1st', vector.namespace, vector.name)
+
+ expect(actual).toBe(vector.expectedSubjectId)
+ if (actual) {
+ expect(`host:${actual}`).toBe(vector.expectedSubject)
+ expect(actual).not.toContain(vector.displayText)
+ }
+ })
+
+ it('supports third-party provisioner subjects through the same helper', () => {
expect(makeHostSubjectId('3rd', 'sandbox-recipes', 'daily-report')).toBe(
'3rd:sandbox-recipes/daily-report'
)
diff --git a/control-api/test/gfsLegacyStandaloneGrantMigration.test.ts b/control-api/test/gfsLegacyStandaloneGrantMigration.test.ts
new file mode 100644
index 000000000..7595abf12
--- /dev/null
+++ b/control-api/test/gfsLegacyStandaloneGrantMigration.test.ts
@@ -0,0 +1,234 @@
+import { readFile } from 'node:fs/promises'
+import { describe, expect, it, vi } from 'vitest'
+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
+ )
+
+ 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.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'],
+ }],
+ }
+ 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')
+ }
+ })
+
+ 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,
+ },
+ ] }))
+ 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')
+ 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 --git a/control-api/test/gfsProvisionerScopePolicy.test.ts b/control-api/test/gfsProvisionerScopePolicy.test.ts
index 88843e99b..802e0d52d 100644
--- a/control-api/test/gfsProvisionerScopePolicy.test.ts
+++ b/control-api/test/gfsProvisionerScopePolicy.test.ts
@@ -16,7 +16,10 @@ describe('provisionerScopesAllowed', () => {
expect(provisionerScopesAllowed('3rd', ['gfs.share'])).toBe(false)
})
- it('leaves first-party host provisioners governed by the existing subject-class gate', () => {
- expect(provisionerScopesAllowed('1st', ['gfs.read', 'gfs.write', 'gfs.delete'])).toBe(true)
+ it('limits first-party HCC provisioners to read and write', () => {
+ expect(provisionerScopesAllowed('1st', ['gfs.read', 'gfs.write'])).toBe(true)
+ expect(provisionerScopesAllowed('1st', ['gfs.delete'])).toBe(false)
+ expect(provisionerScopesAllowed('1st', ['gfs.manage_acl'])).toBe(false)
+ expect(provisionerScopesAllowed('1st', ['gfs.share'])).toBe(false)
})
})
diff --git a/control-api/test/gfsProvisionerToken.test.ts b/control-api/test/gfsProvisionerToken.test.ts
index b2a3df187..b8fa560ec 100644
--- a/control-api/test/gfsProvisionerToken.test.ts
+++ b/control-api/test/gfsProvisionerToken.test.ts
@@ -35,15 +35,41 @@ const NS = 'mcp-host'
describe('POST /api/v1/auth/gfs/:subject/tokens', () => {
it('hcc mints a 1st-party host token (read scope by default)', async () => {
const res = await request(await app())
- .post('/api/v1/auth/gfs/standalone/tokens')
+ .post('/api/v1/auth/gfs/chatllm/tokens')
.set('Authorization', `Bearer ${signInternalControlJwt('hcc')}`)
.send({ namespace: NS })
expect(res.status).toBe(200)
- expect(res.body.subject).toBe(`host:1st:${NS}/standalone`)
+ expect(res.body.subject).toBe(`host:1st:${NS}/chatllm`)
expect(typeof res.body.token).toBe('string')
expect(res.body.expiresInSeconds).toBeGreaterThan(0)
})
+ it('rejects the reserved legacy standalone subject for HCC issuance', async () => {
+ const res = await request(await app())
+ .post('/api/v1/auth/gfs/standalone/tokens')
+ .set('Authorization', `Bearer ${signInternalControlJwt('hcc')}`)
+ .send({ namespace: NS })
+ expect(res.status).toBe(409)
+ expect(res.body).toEqual({ error: 'subject_reserved' })
+ expect(res.body.token).toBeUndefined()
+ })
+
+ it('does not reserve other standalone subjects or the third-party subject class', async () => {
+ const hcc = await request(await app())
+ .post('/api/v1/auth/gfs/standalone/tokens')
+ .set('Authorization', `Bearer ${signInternalControlJwt('hcc')}`)
+ .send({ namespace: 'sandbox-recipes' })
+ expect(hcc.status).toBe(200)
+ expect(hcc.body.subject).toBe('host:1st:sandbox-recipes/standalone')
+
+ const wrc = await request(await app())
+ .post('/api/v1/auth/gfs/standalone/tokens')
+ .set('Authorization', `Bearer ${signInternalControlJwt('wrc')}`)
+ .send({ namespace: NS })
+ expect(wrc.status).toBe(200)
+ expect(wrc.body.subject).toBe('host:3rd:mcp-host/standalone')
+ })
+
it('wrc mints a 3rd-party host token', async () => {
const res = await request(await app())
.post('/api/v1/auth/gfs/my-recipe/tokens')
@@ -72,6 +98,17 @@ describe('POST /api/v1/auth/gfs/:subject/tokens', () => {
expect(res.body.error).toBe('scope_forbidden')
})
+ it('hcc cannot mint destructive or governance scopes for first-party agents', async () => {
+ for (const scope of ['gfs.delete', 'gfs.manage_acl', 'gfs.share']) {
+ const res = await request(await app())
+ .post('/api/v1/auth/gfs/chatllm/tokens')
+ .set('Authorization', `Bearer ${signInternalControlJwt('hcc')}`)
+ .send({ namespace: NS, scopes: ['gfs.read', scope] })
+ expect(res.status).toBe(403)
+ expect(res.body).toEqual({ error: 'scope_forbidden' })
+ }
+ })
+
it('rejects an unauthorized issuance namespace (400)', async () => {
const res = await request(await app())
.post('/api/v1/auth/gfs/standalone/tokens')
@@ -101,7 +138,7 @@ describe('POST /api/v1/auth/gfs/:subject/tokens', () => {
it('rejects an unknown scope (400 invalid_scope)', async () => {
const res = await request(await app())
- .post('/api/v1/auth/gfs/standalone/tokens')
+ .post('/api/v1/auth/gfs/chatllm/tokens')
.set('Authorization', `Bearer ${signInternalControlJwt('hcc')}`)
.send({ namespace: NS, scopes: ['gfs.bogus'] })
expect(res.status).toBe(400)
diff --git a/control-api/test/gfsReaderRole.realPostgres.integration.test.ts b/control-api/test/gfsReaderRole.realPostgres.integration.test.ts
new file mode 100644
index 000000000..245b7c028
--- /dev/null
+++ b/control-api/test/gfsReaderRole.realPostgres.integration.test.ts
@@ -0,0 +1,257 @@
+import { randomBytes } from 'node:crypto'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { Pool } from 'pg'
+import { CONTROL_API_MIGRATIONS, initDb } from '../src/db.js'
+import { createPermissionStoreProbe } from '../../gfs-controller/src/authz/storeProbe.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}'`)
+ 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(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'],
+ ])('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' })
+ })
+
+ 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('UPDATE gfs_blob_manifests SET updated_at = updated_at WHERE false')
+ ).resolves.toMatchObject({ rowCount: 0 })
+ })
+})
diff --git a/control-api/test/gfsReadiness.realPostgres.integration.test.ts b/control-api/test/gfsReadiness.realPostgres.integration.test.ts
new file mode 100644
index 000000000..1b676e21e
--- /dev/null
+++ b/control-api/test/gfsReadiness.realPostgres.integration.test.ts
@@ -0,0 +1,134 @@
+import { randomBytes } from 'node:crypto'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+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'
+
+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 --git a/control-api/test/gfsResources.routeTransaction.test.ts b/control-api/test/gfsResources.routeTransaction.test.ts
new file mode 100644
index 000000000..de4da6820
--- /dev/null
+++ b/control-api/test/gfsResources.routeTransaction.test.ts
@@ -0,0 +1,195 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const FILE = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'
+const SRC = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'
+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: [] }
+ }),
+ }
+ 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,
+ 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,
+ 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,
+ 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,
+ 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 --git a/control-api/test/gfsResources.test.ts b/control-api/test/gfsResources.test.ts
index 81ab79e51..520e71daf 100644
--- a/control-api/test/gfsResources.test.ts
+++ b/control-api/test/gfsResources.test.ts
@@ -5,22 +5,12 @@ 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'
const DEST_OTHER_DRIVE = 'dddddddd-dddd-dddd-dddd-dddddddddddd'
const DEST_FILE = 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee'
const DIR = 'ffffffff-ffff-ffff-ffff-ffffffffffff'
-
interface ResRow {
resource_id: string
drive: string
@@ -28,6 +18,7 @@ interface ResRow {
name: string
kind: string
version: number
+ deleted_at: string | null
}
interface GrantRow {
subject_type: string
@@ -45,6 +36,7 @@ const RESOURCES: Record<string, ResRow> = {
name: 'a.md',
kind: 'file',
version: 2,
+ deleted_at: null,
},
[SRC]: {
resource_id: SRC,
@@ -53,6 +45,7 @@ const RESOURCES: Record<string, ResRow> = {
name: 'src',
kind: 'directory',
version: 0,
+ deleted_at: null,
},
[DEST]: {
resource_id: DEST,
@@ -61,6 +54,7 @@ const RESOURCES: Record<string, ResRow> = {
name: 'dest',
kind: 'directory',
version: 0,
+ deleted_at: null,
},
[DEST_OTHER_DRIVE]: {
resource_id: DEST_OTHER_DRIVE,
@@ -69,6 +63,7 @@ const RESOURCES: Record<string, ResRow> = {
name: 'x',
kind: 'directory',
version: 0,
+ deleted_at: null,
},
[DEST_FILE]: {
resource_id: DEST_FILE,
@@ -77,6 +72,7 @@ const RESOURCES: Record<string, ResRow> = {
name: 'f.md',
kind: 'file',
version: 0,
+ deleted_at: null,
},
[DIR]: {
resource_id: DIR,
@@ -85,23 +81,61 @@ const RESOURCES: Record<string, ResRow> = {
name: 'd',
kind: 'directory',
version: 0,
+ deleted_at: null,
},
}
-function mockDb(opts?: { grants?: GrantRow[]; update?: 'ok' | 'empty' | 'conflict' }): GrantsDb {
+function mockDb(opts?: {
+ grants?: GrantRow[]
+ update?: 'ok' | 'empty' | 'conflict'
+ afterLock?: (resources: Record<string, ResRow>) => void
+}): GrantsDb & { queries: { text: string; values?: unknown[] }[] } {
const grants = opts?.grants ?? []
+ const resources = Object.fromEntries(
+ Object.entries(RESOURCES).map(([id, row]) => [id, { ...row }])
+ ) as Record<string, ResRow>
+ const queries: { text: string; values?: unknown[] }[] = []
return {
+ queries,
async query(text: string, values?: unknown[]) {
- // WITH RECURSIVE also contains "FROM gfs_resources"+"SELECT" — match it first.
+ queries.push({ text, values })
+ if (text.includes('pg_advisory_xact_lock')) return { rows: [] }
+ if (text.includes('resource_id = ANY($1::uuid[])')) {
+ opts?.afterLock?.(resources)
+ return { rows: [] }
+ }
if (text.includes('WITH RECURSIVE chain')) {
- const rid = String(values?.[1] ?? '')
- // self only — direct grants on the resource itself suffice for the tests.
- return { rows: [{ resource_id: rid }] }
+ const rows: Array<ResRow & { cycle: boolean }> = []
+ const visited = new Set<string>()
+ const idIndex = text.includes('0 AS depth') ? 1 : 0
+ let rid: string | null = String(values?.[idIndex] ?? '')
+ while (rid && resources[rid]) {
+ const row = resources[rid]
+ const cycle = visited.has(rid)
+ rows.push({ ...row, cycle })
+ if (cycle) break
+ visited.add(rid)
+ rid = row.parent_resource_id
+ }
+ return { rows }
+ }
+ if (text.includes('WITH RECURSIVE subtree') && text.includes('canonical_path')) {
+ return {
+ rows: [
+ {
+ expected_count: '1',
+ updated_count: '1',
+ canonical_count: '1',
+ distinct_path_count: '1',
+ has_cycle: false,
+ },
+ ],
+ }
}
if (text.includes('FROM gfs_resources') && text.includes('SELECT')) {
const rid = String(values?.[0] ?? '')
- const row = RESOURCES[rid]
- return { rows: row ? [row] : [] }
+ const row = resources[rid]
+ return { rows: row ? [{ ...row }] : [] }
}
if (text.includes('FROM gfs_grants')) return { rows: grants }
if (text.includes('FROM gfs_shares')) return { rows: [] }
@@ -114,7 +148,6 @@ function mockDb(opts?: { grants?: GrantRow[]; update?: 'ok' | 'empty' | 'conflic
},
}
}
-
const operator: GfsCaller = {
isOperator: true,
subjects: new Set(['operator:']),
@@ -130,7 +163,6 @@ const grant = (subjectId: string, resourceId: string, ...permissions: string[]):
permissions,
inherit: true,
})
-
async function patch(
db: GrantsDb,
caller: GfsCaller,
@@ -199,7 +231,6 @@ describe('applyResourcePatch — move', () => {
})
it('a user needs write+delete on src parent AND write on dest parent', async () => {
- // holds write+delete on SRC but NOT write on DEST → forbidden.
const db = mockDb({ grants: [grant('mover', SRC, 'write', 'delete')] })
await expect(patch(db, user('mover'), FILE, { newParentId: DEST })).rejects.toMatchObject({
status: 403,
@@ -231,14 +262,24 @@ describe('applyResourcePatch — concurrency + guards', () => {
expect(out.version).toBe(3)
})
- it('a concurrent version bump (no rows updated) is precondition_failed', async () => {
- await expect(
- patch(mockDb({ update: 'empty' }), operator, FILE, { newName: 'b.md' })
- ).rejects.toMatchObject({
+ it('rejects a source version change observed while acquiring row locks', async () => {
+ const db = mockDb({ afterLock: resources => (resources[FILE].version += 1) })
+ await expect(patch(db, operator, FILE, { newName: 'b.md' })).rejects.toMatchObject({
status: 412,
+ code: 'precondition_failed',
})
})
+ 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')]
+ for (const afterLock of mutations) {
+ 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 @@ describe('applyResourcePatch — concurrency + guards', () => {
})
})
+ 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'))
+ 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)
})
@@ -261,7 +330,6 @@ describe('applyResourcePatch — concurrency + guards', () => {
describe('applyResourcePatch — security guards (review findings)', () => {
it('forbids moving a directory into itself (cycle guard)', async () => {
- // DIR is a directory; moving it into itself must be rejected, not a no-op.
await expect(patch(mockDb(), operator, DIR, { newParentId: DIR })).rejects.toMatchObject({
status: 400,
code: 'path_invalid',
@@ -269,7 +337,7 @@ describe('applyResourcePatch — security guards (review findings)', () => {
})
it('audits the denial when a non-operator is forbidden', async () => {
- const db = mockDb({ grants: [grant('owner', FILE, 'read')] }) // no write
+ const db = mockDb({ grants: [grant('owner', FILE, 'read')] })
const audited: Array<{ outcome?: string }> = []
await expect(
applyResourcePatch(db, user('owner'), 'main', FILE, { newName: 'b.md' }, async p => {
diff --git a/control-api/test/gfsStructuralIntegrity.realPostgres.integration.test.ts b/control-api/test/gfsStructuralIntegrity.realPostgres.integration.test.ts
new file mode 100644
index 000000000..09a5fb963
--- /dev/null
+++ b/control-api/test/gfsStructuralIntegrity.realPostgres.integration.test.ts
@@ -0,0 +1,349 @@
+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,
+ type Transactor,
+} from '../../gfs-controller/src/db/writeStore.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 })
+ 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 })
+ 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 })
+ 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
+ (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])
+ 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' })
+ } 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 }])
+ })
+
+ 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
+ )
+ 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',
+ ])
+ 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]])
+ 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,
+ }])
+ } 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 --git a/control-api/test/routes.externalGfs.test.ts b/control-api/test/routes.externalGfs.test.ts
index 76a8b29fe..d2f4683b2 100644
--- a/control-api/test/routes.externalGfs.test.ts
+++ b/control-api/test/routes.externalGfs.test.ts
@@ -53,7 +53,7 @@ const U1 = '11111111-aaaa-4aaa-8aaa-111111111111'
const U2 = '22222222-bbbb-4bbb-8bbb-222222222222'
const T1 = '33333333-cccc-4ccc-8ccc-333333333333'
const T2 = '44444444-dddd-4ddd-8ddd-444444444444'
-const H1 = '1st:mcp-host/standalone'
+const H1 = '1st:mcp-host/agent-a'
const CORRELATION_ID = '55555555-eeee-4eee-8eee-555555555555'
const SESSION = {
userId: U1,
@@ -814,6 +814,33 @@ describe('authenticated bulk grant/share transport', () => {
])
})
+ it('denies an entire plural grant batch when a managed first-party host exceeds read/write', async () => {
+ auth()
+ // The caller holds every requested bit, so the only thing standing between
+ // this batch and a mutation is the managed first-party host permission cap.
+ authority(['manage_acl', 'read', 'delete'])
+ const app = await buildApp()
+
+ const res = await request(app)
+ .put('/external/gfs/grants')
+ .set('x-user-session-token', 'sess')
+ .set('x-correlation-id', CORRELATION_ID)
+ .send({
+ resourceId: R,
+ subjects: [
+ { type: 'user', id: U2 },
+ { type: 'host', id: H1 },
+ ],
+ permissions: ['read', 'delete'],
+ })
+
+ expect(res.status).toBe(403)
+ expect(res.body.error).toBe('managed_agent_permission_forbidden')
+ expect(
+ mockQuery.mock.calls.some(call => String(call[0]).includes('INSERT INTO gfs_grants'))
+ ).toBe(false)
+ })
+
it('does not publish staged mutation or audit effects when event persistence fails', async () => {
auth()
authority(['manage_acl', 'read'])
diff --git a/control-api/test/routes.overview.test.ts b/control-api/test/routes.overview.test.ts
index 538f0edb9..797dff7fc 100644
--- a/control-api/test/routes.overview.test.ts
+++ b/control-api/test/routes.overview.test.ts
@@ -25,9 +25,57 @@ describe("routes/admin.hostsOverview", () => {
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",
+ active: true,
+ 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");
+ });
+
+ 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: "deleted",
+ namespace: "mcp-host",
+ deletionTimestamp: "2026-07-17T12:00:00Z",
+ },
+ 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 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",
+ active: true,
+ gfsSubject: { type: "host", id: "1st:mcp-host/visible" },
+ },
+ ]);
});
it("returns 500 when host overview fails", async () => {
@@ -64,6 +112,7 @@ describe("routes/admin.hostsOverview", () => {
.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")
diff --git a/control-api/test/routes.profile.test.ts b/control-api/test/routes.profile.test.ts
index 56c07aa45..78f13e2ef 100644
--- a/control-api/test/routes.profile.test.ts
+++ b/control-api/test/routes.profile.test.ts
@@ -123,6 +123,10 @@ describe('routes/profile', () => {
}
function accessCatalogGateway() {
+ const hosts = [
+ { metadata: { name: 'agent-a', namespace: 'mcp-host' }, spec: { enabled: true } },
+ { metadata: { name: 'agent-b', namespace: 'mcp-host' }, spec: { enabled: true } },
+ ]
return {
listResource: vi.fn(async (plural: string) => {
if (plural === 'contexts') {
@@ -132,13 +136,18 @@ describe('routes/profile', () => {
]
}
if (plural === 'hosts') {
- return [
- { metadata: { name: 'agent-a' }, spec: { enabled: true } },
- { metadata: { name: 'agent-b' }, spec: { enabled: true } },
- ]
+ return hosts
}
return []
}),
+ getResource: vi.fn(async (plural: string, name: string) => {
+ if (plural !== 'hosts') {
+ throw Object.assign(new Error('not-found'), { statusCode: 404 })
+ }
+ const host = hosts.find(candidate => candidate.metadata.name === name)
+ if (!host) throw Object.assign(new Error('not-found'), { statusCode: 404 })
+ return host
+ }),
}
}
@@ -510,7 +519,17 @@ describe('routes/profile', () => {
.expect({
userId: 'u1',
agentNames: ['agent-a'],
- agents: [{ name: 'agent-a', contextRef: null, mcpServers: [] }],
+ agents: [
+ {
+ name: 'agent-a',
+ namespace: 'mcp-host',
+ displayName: 'agent-a',
+ active: true,
+ gfsSubject: { type: 'host', id: '1st:mcp-host/agent-a' },
+ contextRef: null,
+ mcpServers: [],
+ },
+ ],
})
await withInternalServiceAuthAndUserSession(request(app).get('/external/teams/t1/contexts'))
@@ -523,12 +542,70 @@ describe('routes/profile', () => {
teamId: 't1',
agentNames: ['agent-a', 'agent-b'],
agents: [
- { name: 'agent-a', contextRef: null, mcpServers: [] },
- { name: 'agent-b', contextRef: null, mcpServers: [] },
+ {
+ name: 'agent-a',
+ namespace: 'mcp-host',
+ displayName: 'agent-a',
+ active: true,
+ gfsSubject: { type: 'host', id: '1st:mcp-host/agent-a' },
+ contextRef: null,
+ mcpServers: [],
+ },
+ {
+ name: 'agent-b',
+ namespace: 'mcp-host',
+ displayName: 'agent-b',
+ active: true,
+ gfsSubject: { type: 'host', id: '1st:mcp-host/agent-b' },
+ contextRef: null,
+ mcpServers: [],
+ },
],
})
})
+ it('preserves user and team names-only access when Host enrichment has a transient failure', async () => {
+ svc.getUserAgents.mockResolvedValue({
+ userId: 'u1',
+ agentNames: ['agent-a', 'agent-stale'],
+ })
+ svc.getTeamAgents.mockResolvedValue({
+ teamId: 't1',
+ agentNames: ['agent-b'],
+ })
+ const transientError = Object.assign(new Error('Kubernetes API unavailable'), {
+ statusCode: 503,
+ })
+ const gateway = accessCatalogGateway()
+ gateway.getResource.mockRejectedValue(transientError)
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+
+ const app = express()
+ app.use(express.json())
+ mountInternalRoutes(app, gateway)
+
+ await withInternalServiceAuthAndUserSession(request(app).get('/external/users/u1/agents'))
+ .expect(200)
+ .expect({
+ userId: 'u1',
+ agentNames: ['agent-a', 'agent-stale'],
+ agents: [],
+ })
+
+ await withInternalServiceAuthAndUserSession(request(app).get('/external/teams/t1/agents'))
+ .expect(200)
+ .expect({ teamId: 't1', agentNames: ['agent-b'], agents: [] })
+
+ expect(gateway.listResource).not.toHaveBeenCalledWith('hosts', 'mcp-host')
+ expect(gateway.getResource.mock.calls.map(call => call[1])).toEqual([
+ 'agent-a',
+ 'agent-stale',
+ 'agent-b',
+ ])
+ expect(warn).toHaveBeenCalledTimes(2)
+ warn.mockRestore()
+ })
+
it('verifies session token server-side for rpc token issuance', async () => {
rpcMock.issueRpcAccessToken.mockReturnValue({
token: 'rpc-token',
diff --git a/control-api/test/routes.profileAdmin.test.ts b/control-api/test/routes.profileAdmin.test.ts
index 046af7f57..483b6a66e 100644
--- a/control-api/test/routes.profileAdmin.test.ts
+++ b/control-api/test/routes.profileAdmin.test.ts
@@ -200,7 +200,7 @@ describe('routes/profileAdmin', () => {
return [{ metadata: { name: 'ctx-live' }, spec: { contextId: 'ctx-alias' } }]
}
if (plural === 'hosts') {
- return [{ metadata: { name: 'agent-live' }, spec: { enabled: false } }]
+ return [{ metadata: { name: 'agent-live', namespace: 'mcp-host' }, spec: { enabled: true } }]
}
return []
})
@@ -243,7 +243,7 @@ describe('routes/profileAdmin', () => {
return [{ metadata: { name: 'ctx-live' }, spec: { contextId: 'ctx-alias' } }]
}
if (plural === 'hosts') {
- return [{ metadata: { name: 'agent-live' }, spec: { enabled: false } }]
+ return [{ metadata: { name: 'agent-live', namespace: 'mcp-host' }, spec: { enabled: true } }]
}
return []
})
diff --git a/control-api/test/services.access.mcpInvocable.test.ts b/control-api/test/services.access.mcpInvocable.test.ts
index c70a0e675..fc299a301 100644
--- a/control-api/test/services.access.mcpInvocable.test.ts
+++ b/control-api/test/services.access.mcpInvocable.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it, vi } from 'vitest'
import type { K8sGateway } from '../src/k8s.js'
import {
+ isK8sResourceNotFound,
resolveInvocableMcpServersForContexts,
resolveMcpServersForAgents,
} from '../src/services/access/mcpInvocable.js'
@@ -18,13 +19,24 @@ function gateway(resources: {
if (plural === 'hosts') return resources.hosts ?? []
return []
})
+ const getResource = vi.fn(async (plural: string, name: string) => {
+ if (plural !== 'hosts') return undefined
+ const found = resources.hosts?.find(
+ resource => (resource.metadata as { name?: string } | undefined)?.name === name
+ )
+ if (!found) throw Object.assign(new Error('not-found'), { statusCode: 404 })
+ return found
+ })
return {
listResource,
- getResource: vi.fn(),
+ getResource,
createResource: vi.fn(),
updateResource: vi.fn(),
deleteResource: vi.fn(),
- } as unknown as K8sGateway & { listResource: typeof listResource }
+ } as unknown as K8sGateway & {
+ listResource: typeof listResource
+ getResource: typeof getResource
+ }
}
const okServer = (name: string, url?: string) => ({
@@ -41,10 +53,18 @@ const ctx = (contextId: string, servers: string[]) => ({
})
const host = (name: string, contextRef: string | null) => ({
- metadata: { name },
+ metadata: { name, namespace: 'mcp-host' },
spec: contextRef ? { contextRef } : {},
})
+const directoryFields = (name: string) => ({
+ name,
+ namespace: 'mcp-host',
+ displayName: name,
+ active: true,
+ gfsSubject: { type: 'host', id: `1st:mcp-host/${name}` },
+})
+
describe('resolveInvocableMcpServersForContexts', () => {
it('returns invocable {name, url} for servers in allowed contexts', async () => {
const g = gateway({
@@ -167,12 +187,16 @@ describe('resolveMcpServersForAgents', () => {
agentNames: ['trader', 'ops'],
})
expect(out).toEqual([
- { name: 'trader', contextRef: 'trading', mcpServers: [{ name: 'mcp-a' }, { name: 'mcp-b' }] },
- { name: 'ops', contextRef: 'business', mcpServers: [{ name: 'mcp-c' }] },
+ {
+ ...directoryFields('trader'),
+ contextRef: 'trading',
+ mcpServers: [{ name: 'mcp-a' }, { name: 'mcp-b' }],
+ },
+ { ...directoryFields('ops'), contextRef: 'business', mcpServers: [{ name: 'mcp-c' }] },
])
})
- it('returns null contextRef for agents whose Host CR is missing', async () => {
+ it('omits agents whose Host CR is missing', async () => {
const g = gateway({
contexts: [ctx('trading', ['mcp-a'])],
mcpservers: [okServer('mcp-a')],
@@ -183,7 +207,28 @@ describe('resolveMcpServersForAgents', () => {
hostsNamespace: 'mcp-host',
agentNames: ['trader', 'ghost'],
})
- expect(out[1]).toEqual({ name: 'ghost', contextRef: null, mcpServers: [] })
+ expect(out).toEqual([
+ { ...directoryFields('trader'), contextRef: 'trading', mcpServers: [{ name: 'mcp-a' }] },
+ ])
+ expect(g.getResource.mock.calls.map(call => call[1])).toEqual(['trader', 'ghost'])
+ })
+
+ it('propagates RBAC and transport failures instead of treating an authorized Host as missing', async () => {
+ for (const error of [
+ Object.assign(new Error('forbidden'), { statusCode: 403 }),
+ Object.assign(new Error('socket closed'), { code: 'ECONNRESET' }),
+ ]) {
+ const g = gateway({ hosts: [host('trader', null)] })
+ g.getResource.mockRejectedValueOnce(error)
+
+ await expect(
+ resolveMcpServersForAgents(g, {
+ mcpServersNamespace: 'mcp-server',
+ hostsNamespace: 'mcp-host',
+ agentNames: ['trader'],
+ })
+ ).rejects.toBe(error)
+ }
})
it('preserves the input order of agentNames', async () => {
@@ -200,6 +245,21 @@ describe('resolveMcpServersForAgents', () => {
expect(out.map(e => e.name)).toEqual(['c1', 'a1', 'b1'])
})
+ it('fetches only authorized names and preserves their order when hidden Hosts exist', async () => {
+ const g = gateway({
+ hosts: [host('visible-b', null), host('hidden', null), host('visible-a', null)],
+ })
+ const out = await resolveMcpServersForAgents(g, {
+ mcpServersNamespace: 'mcp-server',
+ hostsNamespace: 'mcp-host',
+ agentNames: ['visible-a', 'visible-b'],
+ })
+
+ expect(out.map(agent => agent.name)).toEqual(['visible-a', 'visible-b'])
+ expect(g.getResource.mock.calls.map(call => call[1])).toEqual(['visible-a', 'visible-b'])
+ expect(g.listResource).not.toHaveBeenCalledWith('hosts', expect.anything())
+ })
+
it('applies the same invocability filter as the RPC helper', async () => {
const g = gateway({
contexts: [ctx('trading', ['a', 'b'])],
@@ -249,7 +309,24 @@ describe('resolveMcpServersForAgents', () => {
hostsNamespace: 'mcp-host',
agentNames: ['trader'],
})
- expect(out).toEqual([{ name: 'trader', contextRef: null, mcpServers: [] }])
+ expect(out).toEqual([])
+ })
+})
+
+describe('isK8sResourceNotFound', () => {
+ it('accepts Kubernetes and gateway 404 shapes', () => {
+ expect(isK8sResourceNotFound({ name: 'K8sNotFoundError' })).toBe(true)
+ expect(isK8sResourceNotFound({ statusCode: 404 })).toBe(true)
+ expect(isK8sResourceNotFound({ code: 404 })).toBe(true)
+ expect(isK8sResourceNotFound({ body: { code: 404 } })).toBe(true)
+ expect(isK8sResourceNotFound({ response: { status: 404 } })).toBe(true)
+ expect(isK8sResourceNotFound({ response: { body: { code: 404 } } })).toBe(true)
+ })
+
+ it('rejects RBAC, transport, and misleading text-only errors', () => {
+ expect(isK8sResourceNotFound({ statusCode: 403 })).toBe(false)
+ expect(isK8sResourceNotFound({ code: 'ECONNRESET' })).toBe(false)
+ expect(isK8sResourceNotFound(new Error('not found'))).toBe(false)
})
})
diff --git a/gfs-controller/src/api/copy.test.ts b/gfs-controller/src/api/copy.test.ts
new file mode 100644
index 000000000..175b80adb
--- /dev/null
+++ b/gfs-controller/src/api/copy.test.ts
@@ -0,0 +1,257 @@
+import { describe, expect, it } from "vitest";
+import { GfsError } from "./errors";
+import { CopyDestinationSnapshot, CopyPreflightInput, CopySnapshotNode, preflightCopy } from "./copy";
+
+const SOURCE = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
+const FILE = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb";
+const DEST = "cccccccc-cccc-cccc-cccc-cccccccccccc";
+const ROOT = "dddddddd-dddd-dddd-dddd-dddddddddddd";
+const OTHER = "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee";
+
+function node(over: Partial<CopySnapshotNode> = {}): CopySnapshotNode {
+ return {
+ resourceId: SOURCE,
+ drive: "main",
+ parentResourceId: ROOT,
+ name: "source",
+ kind: "directory",
+ pathCache: "/source",
+ version: 7,
+ bytes: 0n,
+ blobKey: null,
+ contentSha256: null,
+ deletedAt: null,
+ depth: 0,
+ cycle: false,
+ underTombstone: false,
+ ...over,
+ };
+}
+
+function destination(over: Partial<CopyDestinationSnapshot> = {}): CopyDestinationSnapshot {
+ return {
+ ancestors: [
+ node({ resourceId: DEST, parentResourceId: ROOT, name: "archive", pathCache: "/archive", version: 2, depth: 0 }),
+ node({ resourceId: ROOT, parentResourceId: null, name: "", pathCache: "/", version: 1, depth: 1 }),
+ ],
+ liveChildren: [],
+ ...over,
+ };
+}
+
+function input(over: Partial<CopyPreflightInput> = {}): CopyPreflightInput {
+ return {
+ drive: "main",
+ sourceResourceId: SOURCE,
+ destinationParentId: DEST,
+ ifMatch: 7,
+ snapshot: [
+ node(),
+ node({
+ resourceId: FILE,
+ parentResourceId: SOURCE,
+ name: "résumé.txt",
+ pathCache: "/source/résumé.txt",
+ kind: "file",
+ version: 3,
+ bytes: 12n,
+ blobKey: `${FILE.replaceAll("-", "")}/generation`,
+ contentSha256: "a".repeat(64),
+ depth: 1,
+ }),
+ ],
+ destination: destination(),
+ maxObjects: 1000,
+ maxBytes: 1024 * 1024 * 1024,
+ deadlineAtMs: 31_000,
+ nowMs: 1_000,
+ ...over,
+ };
+}
+
+function expectCode(fn: () => unknown, code: GfsError["code"]): void {
+ expect(fn).toThrowError(expect.objectContaining({ code }));
+}
+
+describe("preflightCopy", () => {
+ it("returns deterministic totals and an old-id parent map without allocating identities", () => {
+ const request = input({ snapshot: [...input().snapshot].reverse() });
+ const plan = preflightCopy(request);
+
+ expect(plan.nodes.map(item => item.resourceId)).toEqual([SOURCE, FILE]);
+ expect(plan).toMatchObject({ rootName: "source", objectCount: 2, fileCount: 1, folderCount: 1, totalBytes: 12n });
+ expect([...plan.parentByResourceId.entries()]).toEqual([
+ [SOURCE.replaceAll("-", ""), null],
+ [FILE.replaceAll("-", ""), SOURCE.replaceAll("-", "")],
+ ]);
+ });
+
+ it("NFC-normalizes an explicit destination name", () => {
+ expect(preflightCopy(input({ newName: "re\u0301sume\u0301" })).rootName).toBe("résumé");
+ });
+
+ it("accepts a newly-created source root at version 0 with If-Match 0", () => {
+ expect(preflightCopy(input({ ifMatch: 0, snapshot: [node({ version: 0 })] })).objectCount).toBe(1);
+ });
+
+ it("copies the observed live folder when historical tombstoned children are absent from the snapshot", () => {
+ const plan = preflightCopy(input({ snapshot: [node()] }));
+ expect(plan).toMatchObject({ objectCount: 1, folderCount: 1, fileCount: 0, totalBytes: 0n });
+ });
+
+ it("rejects an empty drive without inventing a drive-name grammar", () => {
+ expectCode(() => preflightCopy(input({ drive: "" })), "path_invalid");
+ });
+
+ it("admits object and byte totals exactly at their configured limits", () => {
+ expect(preflightCopy(input({ maxObjects: 2, maxBytes: 12 })).totalBytes).toBe(12n);
+ });
+
+ it("admits the documented 1000-object default and rejects object 1001", () => {
+ const descendants = Array.from({ length: 999 }, (_, index) => {
+ const suffix = (index + 1).toString(16).padStart(12, "0");
+ return node({
+ resourceId: `00000000-0000-4000-8000-${suffix}`,
+ parentResourceId: SOURCE,
+ name: `file-${index + 1}`,
+ pathCache: `/source/file-${index + 1}`,
+ kind: "file",
+ version: 0,
+ bytes: 1n,
+ blobKey: `00000000000040008000${suffix}/generation`,
+ contentSha256: "a".repeat(64),
+ depth: 1,
+ });
+ });
+ const atDefault = [node(), ...descendants];
+
+ expect(preflightCopy(input({ snapshot: atDefault }))).toMatchObject({
+ objectCount: 1000,
+ fileCount: 999,
+ folderCount: 1,
+ totalBytes: 999n,
+ });
+
+ expectCode(
+ () => preflightCopy(input({ snapshot: [
+ ...atDefault,
+ node({
+ resourceId: "00000000-0000-4000-8000-000000001000",
+ parentResourceId: SOURCE,
+ name: "file-1000",
+ pathCache: "/source/file-1000",
+ kind: "file",
+ version: 0,
+ bytes: 1n,
+ blobKey: "00000000000040008000000000001000/generation",
+ contentSha256: "b".repeat(64),
+ depth: 1,
+ }),
+ ] })),
+ "payload_too_large"
+ );
+ });
+
+ it.each([
+ ["objects", { maxObjects: 1 }],
+ ["bytes", { maxBytes: 11 }],
+ ])("rejects one over the configured %s limit before publication", (_label, over) => {
+ expectCode(() => preflightCopy(input(over)), "payload_too_large");
+ });
+
+ it("rejects a byte sum that cannot be represented safely", () => {
+ expectCode(
+ () => preflightCopy(input({ snapshot: [node({ kind: "file", bytes: BigInt(Number.MAX_SAFE_INTEGER) + 1n })], maxBytes: Number.MAX_SAFE_INTEGER })),
+ "payload_too_large"
+ );
+ });
+
+ it.each([0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY, Number.MAX_SAFE_INTEGER + 1])(
+ "rejects invalid operational limit %s",
+ invalid => expectCode(() => preflightCopy(input({ maxObjects: invalid })), "path_invalid")
+ );
+
+ it("requires the root If-Match and rejects a stale value", () => {
+ expectCode(() => preflightCopy(input({ ifMatch: undefined })), "precondition_failed");
+ expectCode(() => preflightCopy(input({ ifMatch: 6 })), "precondition_failed");
+ });
+
+ it("rejects at the deadline boundary", () => {
+ expectCode(() => preflightCopy(input({ nowMs: 31_000 })), "precondition_failed");
+ expect(preflightCopy(input({ nowMs: 30_999 })).objectCount).toBe(2);
+ });
+
+ it("rejects an absent source or destination", () => {
+ expectCode(() => preflightCopy(input({ snapshot: [] })), "not_found");
+ expectCode(() => preflightCopy(input({ destination: { ancestors: [], liveChildren: [] } })), "not_found");
+ });
+
+ it("rejects a destination equal to or below the frozen source", () => {
+ expectCode(
+ () => preflightCopy(input({ destinationParentId: SOURCE, destination: destination({ ancestors: [node(), node({ resourceId: ROOT, parentResourceId: null, name: "", pathCache: "/", depth: 1 })] }) })),
+ "path_invalid"
+ );
+ expectCode(
+ () => preflightCopy(input({
+ destinationParentId: FILE,
+ snapshot: [node(), node({ resourceId: FILE, parentResourceId: SOURCE, name: "nested", pathCache: "/source/nested", depth: 1 })],
+ destination: destination({ ancestors: [
+ node({ resourceId: FILE, parentResourceId: SOURCE, name: "nested", pathCache: "/source/nested", depth: 0 }),
+ node({ parentResourceId: ROOT, pathCache: "/source", depth: 1 }),
+ node({ resourceId: ROOT, parentResourceId: null, name: "", pathCache: "/", depth: 2 }),
+ ] }),
+ })),
+ "path_invalid"
+ );
+ });
+
+ it("rejects a live root-name collision but accepts an explicit conflict-free name", () => {
+ const withCollision = destination({ liveChildren: [{ resourceId: OTHER, name: "source" }] });
+ expectCode(() => preflightCopy(input({ destination: withCollision })), "already_exists");
+ expect(preflightCopy(input({ destination: withCollision, newName: "source-copy" })).rootName).toBe("source-copy");
+ });
+
+ it.each([
+ ["source cycle flag", { snapshot: [node({ cycle: true })] }],
+ ["live node below tombstone", { snapshot: [node({ underTombstone: true })] }],
+ ["duplicate source id", { snapshot: [node(), node({ depth: 1, parentResourceId: SOURCE })] }],
+ ["disconnected descendant", { snapshot: [node(), node({ resourceId: FILE, parentResourceId: OTHER, depth: 1 })] }],
+ ["parent is a file", { snapshot: [node({ kind: "file" }), node({ resourceId: FILE, parentResourceId: SOURCE, depth: 1 })] }],
+ ["tombstone", { snapshot: [node({ deletedAt: "2026-07-17T00:00:00.000Z" })] }],
+ ["invalid depth", { snapshot: [node({ depth: -1 })] }],
+ ["nonzero directory bytes", { snapshot: [node({ bytes: 1n })] }],
+ ["negative file bytes", { snapshot: [node({ kind: "file", bytes: -1n })] }],
+ ["non-NFC source name", { snapshot: [node({ name: "re\u0301sume\u0301" })] }],
+ ])("rejects structurally invalid snapshot: %s", (_label, over) => {
+ expectCode(() => preflightCopy(input(over as Partial<CopyPreflightInput>)), "precondition_failed");
+ });
+
+ it("rejects cross-drive source and destination ancestry", () => {
+ expectCode(() => preflightCopy(input({ snapshot: [node({ drive: "other" })] })), "cross_boundary");
+ expectCode(
+ () => preflightCopy(input({ destination: destination({ ancestors: [node({ resourceId: DEST, drive: "other" })] }) })),
+ "cross_boundary"
+ );
+ });
+
+ it("rejects an invalid destination parent, broken ancestry, cycle, or noncanonical drive root", () => {
+ expectCode(() => preflightCopy(input({ destination: destination({ ancestors: [node({ resourceId: DEST, kind: "file" })] }) })), "not_a_directory");
+ expectCode(() => preflightCopy(input({ destination: destination({ ancestors: [node({ resourceId: DEST, parentResourceId: OTHER }), node({ resourceId: ROOT, parentResourceId: null, name: "", depth: 1 })] }) })), "precondition_failed");
+ expectCode(() => preflightCopy(input({ destination: destination({ ancestors: [node({ resourceId: DEST, cycle: true })] }) })), "precondition_failed");
+ expectCode(() => preflightCopy(input({ destination: destination({ ancestors: [node({ resourceId: DEST, parentResourceId: ROOT }), node({ resourceId: ROOT, parentResourceId: null, name: "root", depth: 1 })] }) })), "precondition_failed");
+ });
+
+ it("rejects invalid names and duplicate destination child ids", () => {
+ expectCode(() => preflightCopy(input({ newName: "../bad" })), "path_invalid");
+ expectCode(
+ () => preflightCopy(input({ destination: destination({ liveChildren: [{ resourceId: OTHER, name: "one" }, { resourceId: OTHER, name: "two" }] }) })),
+ "precondition_failed"
+ );
+ });
+
+ it("rejects stale and non-canonical source or destination path caches", () => {
+ expectCode(() => preflightCopy(input({ snapshot: [node(), node({ resourceId: FILE, parentResourceId: SOURCE, name: "file", kind: "file", pathCache: "/stale/file", bytes: 1n, depth: 1 })] })), "precondition_failed");
+ expectCode(() => preflightCopy(input({ snapshot: [node({ pathCache: "/source/" })] })), "precondition_failed");
+ expectCode(() => preflightCopy(input({ destination: destination({ ancestors: [node({ resourceId: DEST, parentResourceId: ROOT, name: "archive", pathCache: "/stale/archive", depth: 0 }), node({ resourceId: ROOT, parentResourceId: null, name: "", pathCache: "/", depth: 1 })] }) })), "precondition_failed");
+ });
+});
diff --git a/gfs-controller/src/api/copy.ts b/gfs-controller/src/api/copy.ts
new file mode 100644
index 000000000..71b38f299
--- /dev/null
+++ b/gfs-controller/src/api/copy.ts
@@ -0,0 +1,269 @@
+import { GfsError } from "./errors";
+import { normalizeResourceName, ResourceNameError } from "./resourceName";
+import { normalizeResourceId, PathError } from "../storage/paths";
+
+/** One immutable metadata observation returned by the recursive snapshot query. */
+export interface CopySnapshotNode {
+ resourceId: string;
+ drive: string;
+ parentResourceId: string | null;
+ name: string;
+ kind: "file" | "directory";
+ pathCache: string | null;
+ version: number;
+ bytes: bigint;
+ blobKey: string | null;
+ contentSha256: string | null;
+ deletedAt: string | null;
+ depth: number;
+ /** True when the recursive CTE encountered an id already on its traversal path. */
+ cycle: boolean;
+ /** Integrity sentinel: a live row was reached through a tombstoned ancestor. */
+ underTombstone: boolean;
+}
+
+/** Destination parent plus its complete upward ancestry and current live children. */
+export interface CopyDestinationSnapshot {
+ ancestors: CopySnapshotNode[];
+ liveChildren: Array<{ resourceId: string; name: string }>;
+}
+
+export interface CopyPreflightInput {
+ drive: string;
+ sourceResourceId: string;
+ destinationParentId: string;
+ newName?: string;
+ ifMatch?: number;
+ snapshot: CopySnapshotNode[];
+ destination: CopyDestinationSnapshot;
+ maxObjects: number;
+ maxBytes: number;
+ deadlineAtMs: number;
+ nowMs: number;
+}
+
+export interface CopyPreflightPlan {
+ nodes: CopySnapshotNode[];
+ rootName: string;
+ objectCount: number;
+ fileCount: number;
+ folderCount: number;
+ totalBytes: bigint;
+ /** Frozen old-id parent relation; the source root is represented by null. */
+ parentByResourceId: ReadonlyMap<string, string | null>;
+}
+
+const MAX_SAFE_BIGINT = BigInt(Number.MAX_SAFE_INTEGER);
+
+function rid(value: string): string {
+ try {
+ return normalizeResourceId(value);
+ } catch (error) {
+ if (error instanceof PathError) throw new GfsError("path_invalid", error.message);
+ throw error;
+ }
+}
+
+function validName(raw: string): string {
+ try {
+ return normalizeResourceName(raw);
+ } catch (error) {
+ if (error instanceof ResourceNameError) throw new GfsError("path_invalid", error.message);
+ throw error;
+ }
+}
+
+function failStructure(message: string): never {
+ throw new GfsError("precondition_failed", message);
+}
+
+function assertDeadline(input: CopyPreflightInput): void {
+ if (!Number.isFinite(input.deadlineAtMs) || !Number.isFinite(input.nowMs)) {
+ throw new GfsError("path_invalid", "copy deadline must be finite");
+ }
+ if (input.nowMs >= input.deadlineAtMs) {
+ throw new GfsError("precondition_failed", "synchronous copy deadline exceeded");
+ }
+}
+
+function assertLimit(name: string, value: number): void {
+ if (!Number.isSafeInteger(value) || value <= 0) {
+ throw new GfsError("path_invalid", `${name} must be a positive safe integer`);
+ }
+}
+
+function canonicalAbsolutePath(path: string): string {
+ if (!path.startsWith("/") || (path.length > 1 && path.endsWith("/")) || path.includes("//")) {
+ failStructure("copy snapshot contains a non-canonical path");
+ }
+ if (path === "/") return path;
+ const segments = path.slice(1).split("/").map(validName);
+ const canonical = `/${segments.join("/")}`;
+ if (canonical !== path) failStructure("copy snapshot contains a non-canonical path");
+ return canonical;
+}
+
+function childPath(parentPath: string, name: string): string {
+ return parentPath === "/" ? `/${name}` : `${parentPath}/${name}`;
+}
+
+/**
+ * Validate a frozen recursive copy snapshot without allocating identities or
+ * touching blob storage. All comparisons use canonical rids while the returned
+ * nodes retain the database values needed for the later transactional recheck.
+ */
+export function preflightCopy(input: CopyPreflightInput): CopyPreflightPlan {
+ if (typeof input.drive !== "string" || input.drive.length === 0) {
+ throw new GfsError("path_invalid", "copy drive must be a non-empty string");
+ }
+ assertDeadline(input);
+ assertLimit("maxObjects", input.maxObjects);
+ assertLimit("maxBytes", input.maxBytes);
+
+ const sourceId = rid(input.sourceResourceId);
+ const destinationId = rid(input.destinationParentId);
+ if (input.snapshot.length === 0) {
+ throw new GfsError("not_found", "copy source not found");
+ }
+ if (input.snapshot.length > input.maxObjects) {
+ throw new GfsError("payload_too_large", "copy exceeds the configured synchronous limits");
+ }
+ if (input.destination.ancestors.length === 0) {
+ throw new GfsError("not_found", "copy destination not found");
+ }
+
+ const nodes = [...input.snapshot].sort((a, b) => a.depth - b.depth || rid(a.resourceId).localeCompare(rid(b.resourceId)));
+ const byId = new Map<string, CopySnapshotNode>();
+ const parentByResourceId = new Map<string, string | null>();
+ let totalBytes = 0n;
+ let fileCount = 0;
+ let folderCount = 0;
+
+ for (const node of nodes) {
+ const nodeId = rid(node.resourceId);
+ if (byId.has(nodeId)) failStructure("copy snapshot contains a duplicate resource id or cycle");
+ byId.set(nodeId, node);
+ if (node.cycle) failStructure("copy source contains a parent cycle");
+ if (node.underTombstone) failStructure("copy source contains a live node below a tombstone");
+ if (node.drive !== input.drive) throw new GfsError("cross_boundary", "copy source crosses drive boundary");
+ if (node.deletedAt !== null) failStructure("copy source changed or contains a tombstone");
+ if (!Number.isSafeInteger(node.version) || node.version < 0) failStructure("copy source has an invalid version");
+ if (!Number.isSafeInteger(node.depth) || node.depth < 0) failStructure("copy snapshot has an invalid depth");
+ if (node.kind !== "file" && node.kind !== "directory") failStructure("copy source has an invalid kind");
+ if (node.name !== node.name.normalize("NFC")) failStructure("copy source contains a non-canonical name");
+ if (nodeId !== sourceId || node.depth !== 0) validName(node.name);
+
+ if (node.kind === "file") {
+ if (node.bytes < 0n) failStructure("copy source has a negative file size");
+ totalBytes += node.bytes;
+ if (totalBytes > MAX_SAFE_BIGINT) {
+ throw new GfsError("payload_too_large", "copy byte total exceeds safe integer precision");
+ }
+ fileCount += 1;
+ } else {
+ if (node.bytes !== 0n) failStructure("copy source directory has physical bytes");
+ folderCount += 1;
+ }
+ }
+
+ const root = byId.get(sourceId);
+ if (!root || root.depth !== 0) failStructure("copy snapshot root does not match the requested source");
+ if (nodes.filter(node => node.depth === 0).length !== 1) failStructure("copy snapshot has multiple roots");
+ if (input.ifMatch === undefined || input.ifMatch !== root.version) {
+ throw new GfsError("precondition_failed", "copy source If-Match is required and must match the root version");
+ }
+
+ if (root.pathCache === null) failStructure("copy source has no canonical path");
+ const rootPath = canonicalAbsolutePath(root.pathCache);
+ if (root.parentResourceId === null) {
+ if (root.name !== "" || rootPath !== "/") failStructure("copy source drive root is non-canonical");
+ } else if (rootPath.split("/").at(-1) !== root.name) {
+ failStructure("copy source root path does not match its name");
+ }
+
+ for (const node of nodes) {
+ const nodeId = rid(node.resourceId);
+ if (nodeId === sourceId) {
+ parentByResourceId.set(nodeId, null);
+ continue;
+ }
+ if (node.parentResourceId === null) failStructure("copy snapshot contains a disconnected root");
+ const parentId = rid(node.parentResourceId);
+ const parent = byId.get(parentId);
+ if (!parent || parent.kind !== "directory" || parent.depth + 1 !== node.depth) {
+ failStructure("copy snapshot contains an invalid parent map");
+ }
+ if (node.pathCache === null || parent.pathCache === null || node.pathCache !== childPath(parent.pathCache, node.name)) {
+ failStructure("copy source path cache is stale");
+ }
+ parentByResourceId.set(nodeId, parentId);
+ }
+
+ const ancestorIds = new Set<string>();
+ const ancestors = [...input.destination.ancestors].sort((a, b) => a.depth - b.depth);
+ for (const ancestor of ancestors) {
+ const ancestorId = rid(ancestor.resourceId);
+ if (ancestorIds.has(ancestorId) || ancestor.cycle) failStructure("copy destination contains a parent cycle");
+ ancestorIds.add(ancestorId);
+ if (ancestor.drive !== input.drive) throw new GfsError("cross_boundary", "copy destination crosses drive boundary");
+ if (ancestor.deletedAt !== null) failStructure("copy destination changed or contains a tombstone");
+ if (!Number.isSafeInteger(ancestor.version) || ancestor.version < 0) failStructure("copy destination has an invalid version");
+ if (ancestor.kind !== "directory") throw new GfsError("not_a_directory", "copy destination is not a directory");
+ if (ancestor.name !== ancestor.name.normalize("NFC")) failStructure("copy destination contains a non-canonical name");
+ }
+ const destination = ancestors.find(node => rid(node.resourceId) === destinationId && node.depth === 0);
+ if (!destination) failStructure("copy destination snapshot does not match the requested parent");
+ for (let index = 0; index < ancestors.length; index += 1) {
+ const node = ancestors[index];
+ if (index === ancestors.length - 1) {
+ if (node.parentResourceId !== null || node.name !== "" || node.pathCache !== "/") failStructure("copy destination has no canonical drive root");
+ } else {
+ const next = ancestors[index + 1];
+ if (node.parentResourceId === null || rid(node.parentResourceId) !== rid(next.resourceId) || next.depth !== node.depth + 1) {
+ failStructure("copy destination ancestry is incomplete");
+ }
+ validName(node.name);
+ if (node.pathCache === null || next.pathCache === null || node.pathCache !== childPath(next.pathCache, node.name)) {
+ failStructure("copy destination path cache is stale");
+ }
+ }
+ }
+
+ if (byId.has(destinationId)) {
+ throw new GfsError("path_invalid", "copy destination cannot be the source or its descendant");
+ }
+
+ const rootName = validName(input.newName ?? root.name);
+ const childIds = new Set<string>();
+ for (const child of input.destination.liveChildren) {
+ const childId = rid(child.resourceId);
+ if (childIds.has(childId)) failStructure("copy destination children contain duplicate resource ids");
+ childIds.add(childId);
+ if (child.name !== child.name.normalize("NFC")) failStructure("copy destination contains a non-canonical child name");
+ validName(child.name);
+ if (child.name === rootName) {
+ // Accepted trade-off (adversarial review, issue #797): returning
+ // `already_exists` confirms to a caller holding write-but-not-read on the
+ // destination that one attacker-chosen name exists here — the classic
+ // POSIX EEXIST create oracle. The leaked bit is low value (the caller
+ // already holds write on the destination and supplies the name), so copy
+ // intentionally does not additionally require read on the destination
+ // parent, keeping the capability gate (read source + write dest) simple.
+ throw new GfsError("already_exists", `a resource named '${rootName}' already exists here`);
+ }
+ }
+
+ if (totalBytes > BigInt(input.maxBytes)) {
+ throw new GfsError("payload_too_large", "copy exceeds the configured synchronous limits");
+ }
+
+ return {
+ nodes,
+ rootName,
+ objectCount: nodes.length,
+ fileCount,
+ folderCount,
+ totalBytes,
+ parentByResourceId,
+ };
+}
diff --git a/gfs-controller/src/api/copyArchitecture.test.ts b/gfs-controller/src/api/copyArchitecture.test.ts
new file mode 100644
index 000000000..e2161364d
--- /dev/null
+++ b/gfs-controller/src/api/copyArchitecture.test.ts
@@ -0,0 +1,15 @@
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+
+const source = (name: string): string => readFileSync(join(process.cwd(), "src/api", name), "utf8");
+
+describe("Copy architecture boundary", () => {
+ it("does not depend on Move or request delete authority", () => {
+ const copySources = [source("./copy.ts"), source("./copyRoute.ts")].join("\n");
+
+ expect(copySources).not.toMatch(/from\s+["']\.\/move["']/);
+ expect(copySources).not.toMatch(/MoveError|planMove|requiredChecks/);
+ expect(copySources).not.toMatch(/op:\s*["']delete["']|authorizeDelete|\.delete\s*\(/);
+ });
+});
diff --git a/gfs-controller/src/api/copyRoute.ts b/gfs-controller/src/api/copyRoute.ts
new file mode 100644
index 000000000..e6a382487
--- /dev/null
+++ b/gfs-controller/src/api/copyRoute.ts
@@ -0,0 +1,199 @@
+import type { GfsVerifiedClaims } from "../auth/verify";
+import type { AuditSink } from "../authz/audit";
+import type { AuthzContext, AuthzQueryBudget, PermissionEpoch } from "../authz/permissionClient";
+import type { GfsPermission } from "../authz/resolve";
+import { checkTokenCeiling } from "../authz/tokenCeiling";
+import type { DeadlineBudget } from "../db/deadlineQuery";
+import type { CopyQueryBudget, PgResourceStore } from "../db/resourceStore";
+import type { GfsWriteService } from "../db/writeStore";
+import { normalizeResourceId, PathError } from "../storage/paths";
+import { preflightCopy } from "./copy";
+import { GfsError } from "./errors";
+import { normalizeResourceName, ResourceNameError } from "./resourceName";
+
+export interface CopyRouteDeps {
+ authorizeMany: (ctx: AuthzContext, requests: ReadonlyArray<{ resourceId: string; op: GfsPermission }>, budget?: AuthzQueryBudget) => Promise<Array<{ allowed: boolean }>>;
+ /** Snapshot the live permission-invalidation epoch (revocation generation + LISTEN health). */
+ permissionEpoch: () => PermissionEpoch;
+ resources: Pick<PgResourceStore, "loadCopyAdmission" | "loadCopySnapshot" | "loadCopyDestination">;
+ writes: Pick<GfsWriteService, "copy">;
+ audit: AuditSink;
+ maxObjects: number;
+ maxBytes: number;
+ timeoutMs: number;
+}
+
+export interface CopyRouteInput {
+ body: Record<string, unknown>;
+ claims: GfsVerifiedClaims;
+ context: AuthzContext;
+ requestId: string;
+ admittedAtMs: number;
+ signal: AbortSignal;
+ now: () => number;
+ deps: CopyRouteDeps;
+}
+
+const POST_FAILURE_AUDIT_MS = 2_000;
+
+function postFailureAuditBudget(): DeadlineBudget {
+ return { deadlineAtMs: Date.now() + POST_FAILURE_AUDIT_MS };
+}
+
+function rid(body: Record<string, unknown>, key: string): string {
+ const value = body[key];
+ if (typeof value !== "string") throw new GfsError("path_invalid", `'${key}' must be a resource id`);
+ try { return normalizeResourceId(value); }
+ catch (error) {
+ if (error instanceof PathError) throw new GfsError("path_invalid", error.message);
+ throw error;
+ }
+}
+
+function optionalName(body: Record<string, unknown>): string | undefined {
+ const value = body.newName;
+ if (value === undefined || value === null) return undefined;
+ if (typeof value !== "string") throw new GfsError("path_invalid", "'newName' must be a string");
+ try { return normalizeResourceName(value); }
+ catch (error) {
+ if (error instanceof ResourceNameError) throw new GfsError("path_invalid", error.message);
+ throw error;
+ }
+}
+
+function ifMatch(body: Record<string, unknown>): number | undefined {
+ const value = body.ifMatch;
+ if (value === undefined || value === null) return undefined;
+ if (!Number.isSafeInteger(value) || Number(value) < 0) throw new GfsError("path_invalid", "'ifMatch' must be a non-negative safe integer");
+ return Number(value);
+}
+
+function ceilingAllowed(claims: GfsVerifiedClaims, op: GfsPermission, path: string | null): boolean {
+ return checkTokenCeiling({ scopes: claims.scopes, pathBindings: claims.pathBindings, op, resourcePath: path }).allowed;
+}
+
+function checkDeadline(input: CopyRouteInput, deadlineAtMs: number, now: () => number): number {
+ input.signal.throwIfAborted();
+ const elapsedMs = now();
+ if (elapsedMs >= deadlineAtMs) throw new GfsError("precondition_failed", "synchronous copy deadline exceeded");
+ return elapsedMs;
+}
+
+async function failedAudit(input: CopyRouteInput, sourceResourceId: string, error: unknown): Promise<void> {
+ await input.deps.audit.record({
+ recordType: "mutation_outcome", subject: input.context.primarySubject, op: "copy",
+ resourceId: sourceResourceId, drive: input.claims.drive, outcome: "error",
+ reason: error instanceof GfsError ? error.code : "internal_error", requestId: input.requestId,
+ matchedSubject: null, authorizationSource: null, cachedAuthorizationSource: null,
+ mutationOutcome: "failed",
+ }, undefined, postFailureAuditBudget());
+}
+
+export async function executeCopyRoute(input: CopyRouteInput): Promise<Record<string, unknown>> {
+ const requestedDrive = input.body.drive;
+ if (typeof requestedDrive !== "string" || requestedDrive.length === 0) {
+ throw new GfsError("path_invalid", "'drive' must be a non-empty string");
+ }
+ if (requestedDrive !== input.claims.drive) {
+ throw new GfsError("cross_boundary", "copy drive does not match the authorized drive");
+ }
+ const sourceResourceId = rid(input.body, "sourceResourceId");
+ const destinationParentId = rid(input.body, "destinationParentId");
+ const newName = optionalName(input.body);
+ const version = ifMatch(input.body);
+ let publicationCalled = false;
+ let authorized = false;
+ try {
+ const relativeNow = () => Math.max(0, input.now() - input.admittedAtMs);
+ const deadlineAtMs = input.deps.timeoutMs;
+ const budget: CopyQueryBudget = { deadlineAtMs, signal: input.signal, now: relativeNow };
+ checkDeadline(input, deadlineAtMs, relativeNow);
+ const admission = await input.deps.resources.loadCopyAdmission(
+ input.claims.drive, sourceResourceId, destinationParentId, budget
+ );
+ checkDeadline(input, deadlineAtMs, relativeNow);
+ const cheapRequests: Array<{ resourceId: string; op: GfsPermission }> = [
+ { resourceId: sourceResourceId, op: "read" },
+ { resourceId: destinationParentId, op: "write" },
+ ];
+ const cheapCeiling = ceilingAllowed(input.claims, "read", admission.sourceRoot?.pathCache ?? null)
+ && ceilingAllowed(input.claims, "write", admission.destinationParent?.pathCache ?? null);
+ const cheapDecisions = await input.deps.authorizeMany(input.context, cheapRequests, budget);
+ checkDeadline(input, deadlineAtMs, relativeNow);
+ if (!cheapCeiling || cheapDecisions.length !== cheapRequests.length || cheapDecisions.some(decision => !decision.allowed)) {
+ throw new GfsError("forbidden", "copy is not authorized");
+ }
+
+ const snapshot = await input.deps.resources.loadCopySnapshot(
+ input.claims.drive, sourceResourceId, BigInt(input.deps.maxObjects) + 1n, budget
+ );
+ checkDeadline(input, deadlineAtMs, relativeNow);
+ const observedRoot = snapshot.find(node => normalizeResourceId(node.resourceId) === sourceResourceId && node.depth === 0);
+ const collisionName = newName ?? admission.sourceRoot?.name ?? observedRoot?.name ?? "";
+ const destination = await input.deps.resources.loadCopyDestination(
+ input.claims.drive, destinationParentId, collisionName, budget
+ );
+ checkDeadline(input, deadlineAtMs, relativeNow);
+ const sourcePaths = new Map(snapshot.map(node => [normalizeResourceId(node.resourceId), node.pathCache]));
+ const destinationPath = destination.ancestors.find(node =>
+ normalizeResourceId(node.resourceId) === destinationParentId && node.depth === 0
+ )?.pathCache ?? null;
+ const requests: Array<{ resourceId: string; op: GfsPermission }> = snapshot.map(node => ({
+ resourceId: normalizeResourceId(node.resourceId), op: "read",
+ }));
+ if (!sourcePaths.has(sourceResourceId)) requests.push({ resourceId: sourceResourceId, op: "read" });
+ requests.push({ resourceId: destinationParentId, op: "write" });
+
+ const ceiling = requests.every(request => ceilingAllowed(
+ input.claims,
+ request.op,
+ request.op === "write" ? destinationPath : sourcePaths.get(request.resourceId) ?? null
+ ));
+ // Capture the invalidation epoch immediately BEFORE the snapshot is
+ // authorized. The writer transaction re-reads it under the advisory lock so a
+ // grant revoked between here and the INSERT is caught (TOCTOU close).
+ const authzEpochCaptured = input.deps.permissionEpoch();
+ const decisions = await input.deps.authorizeMany(input.context, requests, budget);
+ if (!ceiling || decisions.length !== requests.length || decisions.some(decision => !decision.allowed)) {
+ throw new GfsError("forbidden", "copy is not authorized");
+ }
+ authorized = true;
+
+ const nowMs = checkDeadline(input, deadlineAtMs, relativeNow);
+ const plan = preflightCopy({
+ drive: input.claims.drive, sourceResourceId, destinationParentId, newName, ifMatch: version,
+ snapshot, destination, maxObjects: input.deps.maxObjects, maxBytes: input.deps.maxBytes,
+ deadlineAtMs, nowMs,
+ });
+ publicationCalled = true;
+ const published = await input.deps.writes.copy({
+ requestId: input.requestId, subject: input.context.primarySubject, audit: input.deps.audit,
+ drive: input.claims.drive, destinationParentId, plan, destination, deadlineAtMs,
+ signal: input.signal, now: relativeNow,
+ authzEpoch: { captured: authzEpochCaptured, current: input.deps.permissionEpoch },
+ });
+ const rootRid = normalizeResourceId(published.root.resourceId);
+ return {
+ requestId: published.requestId,
+ resourceId: published.root.resourceId, rid: rootRid,
+ gfsUri: `gfs://${published.root.drive}/${rootRid}`,
+ name: published.root.name, kind: published.root.kind, version: published.root.version,
+ objects: published.objectCount, files: published.fileCount,
+ folders: published.folderCount, bytes: Number(published.totalBytes),
+ };
+ } catch (error) {
+ if (authorized && !publicationCalled) {
+ // The audit write is best-effort here; its own failure must never
+ // replace the original copy error surfaced to the caller.
+ try { await failedAudit(input, sourceResourceId, error); }
+ catch (auditError) {
+ console.error(`[gfsc] copy post-failure audit write failed: ${
+ auditError instanceof Error ? auditError.message : String(auditError)}`);
+ }
+ }
+ if ((error as NodeJS.ErrnoException).code === "ENOSPC") {
+ throw new GfsError("payload_too_large", "copy cannot fit in the available destination capacity");
+ }
+ throw error;
+ }
+}
diff --git a/gfs-controller/src/api/envelope.ts b/gfs-controller/src/api/envelope.ts
index 9d90cd173..fd7fd4021 100644
--- a/gfs-controller/src/api/envelope.ts
+++ b/gfs-controller/src/api/envelope.ts
@@ -60,5 +60,8 @@ export function toResponse(error: unknown): { status: number; body: ErrEnvelope
if (code === "path_invalid") {
return { status: 400, body: { ok: false, error: { code: "path_invalid", message } } };
}
- return { status: 500, body: { ok: false, error: { code: "internal", message } } };
+ return {
+ status: 500,
+ body: { ok: false, error: { code: "internal", message: "internal server error" } },
+ };
}
diff --git a/gfs-controller/src/api/move.test.ts b/gfs-controller/src/api/move.test.ts
deleted file mode 100644
index 8a1d5fca6..000000000
--- a/gfs-controller/src/api/move.test.ts
+++ /dev/null
@@ -1,187 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { assertIfMatch, MoveError, normalizeName, planMove } from "./move.js";
-
-/**
- * P2-S05 — move/rename validation (spec §Move, rename, delete). rename → write
- * on the resource; move → write+delete on source parent + write on dest parent;
- * never crosses drive; stale If-Match → precondition_failed.
- */
-
-const R = "res-1";
-const SRC_PARENT = "src-parent";
-const DEST_PARENT = "dest-parent";
-
-describe("normalizeName", () => {
- it("accepts a normal name and NFC-normalizes it", () => {
- expect(normalizeName("Report.md")).toBe("Report.md");
- expect(normalizeName("My Report.md")).toBe("My Report.md"); // spaces valid
- // é as decomposed e + combining accent → composed form
- expect(normalizeName("café")).toBe("café");
- });
-
- it("rejects empty, dot, dotdot, slash and over-long names", () => {
- const notThrown: string[] = [];
- for (const bad of ["", ".", "..", "a/b", "x".repeat(256)]) {
- try {
- normalizeName(bad);
- notThrown.push(JSON.stringify(bad.length > 20 ? `len${bad.length}` : bad));
- } catch {
- /* expected */
- }
- }
- expect(notThrown).toEqual([]);
- });
-});
-
-describe("assertIfMatch", () => {
- it("passes when no If-Match is given or it matches", () => {
- expect(() => assertIfMatch(3)).not.toThrow();
- expect(() => assertIfMatch(3, 3)).not.toThrow();
- });
- it("throws precondition_failed on a stale If-Match", () => {
- expect(() => assertIfMatch(4, 3)).toThrow(MoveError);
- try {
- assertIfMatch(4, 3);
- } catch (e) {
- expect((e as MoveError).code).toBe("precondition_failed");
- }
- });
-});
-
-describe("planMove — rename", () => {
- it("requires write on the resource and bumps version", () => {
- const plan = planMove({
- resourceId: R,
- sourceDrive: "main",
- sourceParentId: SRC_PARENT,
- currentVersion: 2,
- newName: "renamed.md",
- });
- expect(plan.kind).toBe("rename");
- expect(plan.name).toBe("renamed.md");
- expect(plan.checks).toEqual([{ resourceId: R, op: "write" }]);
- expect(plan.nextVersion).toBe(3);
- });
-});
-
-describe("planMove — move", () => {
- it("requires write+delete on source parent and write on dest parent", () => {
- const plan = planMove({
- resourceId: R,
- sourceDrive: "main",
- sourceParentId: SRC_PARENT,
- currentVersion: 0,
- newParentId: DEST_PARENT,
- destDrive: "main",
- });
- expect(plan.kind).toBe("move");
- expect(plan.newParentId).toBe(DEST_PARENT);
- expect(plan.checks).toEqual([
- { resourceId: SRC_PARENT, op: "write" },
- { resourceId: SRC_PARENT, op: "delete" },
- { resourceId: DEST_PARENT, op: "write" },
- ]);
- });
-
- it("forbids a cross-drive move (cross_boundary)", () => {
- expect(() =>
- planMove({
- resourceId: R,
- sourceDrive: "main",
- sourceParentId: SRC_PARENT,
- currentVersion: 0,
- newParentId: DEST_PARENT,
- destDrive: "other",
- })
- ).toThrow(/cross/i);
- });
-
- it("forbids moving the drive root", () => {
- expect(() =>
- planMove({
- resourceId: R,
- sourceDrive: "main",
- sourceParentId: null,
- currentVersion: 0,
- newParentId: DEST_PARENT,
- destDrive: "main",
- })
- ).toThrow(MoveError);
- });
-
- it("requires destDrive for a move (fail-closed, no cross-drive slip-through)", () => {
- expect(() =>
- planMove({
- resourceId: R,
- sourceDrive: "main",
- sourceParentId: SRC_PARENT,
- currentVersion: 0,
- newParentId: DEST_PARENT,
- // destDrive omitted
- })
- ).toThrow(MoveError);
- });
-
- it("forbids moving a resource into itself (cycle)", () => {
- expect(() =>
- planMove({
- resourceId: R,
- sourceDrive: "main",
- sourceParentId: SRC_PARENT,
- currentVersion: 0,
- newParentId: R,
- destDrive: "main",
- })
- ).toThrow(/subtree/i);
- });
-
- it("forbids moving a resource into its own descendant (cycle)", () => {
- expect(() =>
- planMove({
- resourceId: R,
- sourceDrive: "main",
- sourceParentId: SRC_PARENT,
- currentVersion: 0,
- newParentId: DEST_PARENT,
- destDrive: "main",
- destAncestors: [DEST_PARENT, R], // R is an ancestor of the destination
- })
- ).toThrow(/subtree/i);
- });
-});
-
-describe("planMove — combined + guards", () => {
- it("supports rename+move with all checks", () => {
- const plan = planMove({
- resourceId: R,
- sourceDrive: "main",
- sourceParentId: SRC_PARENT,
- currentVersion: 1,
- newName: "x.md",
- newParentId: DEST_PARENT,
- destDrive: "main",
- });
- expect(plan.kind).toBe("rename+move");
- expect(plan.checks).toContainEqual({ resourceId: R, op: "write" });
- expect(plan.checks).toContainEqual({ resourceId: DEST_PARENT, op: "write" });
- });
-
- it("rejects a no-op request (neither rename nor move)", () => {
- expect(() =>
- planMove({ resourceId: R, sourceDrive: "main", sourceParentId: SRC_PARENT, currentVersion: 0 })
- ).toThrow(MoveError);
- });
-
- it("rejects a stale If-Match before doing anything", () => {
- expect(() =>
- planMove({
- resourceId: R,
- sourceDrive: "main",
- sourceParentId: SRC_PARENT,
- currentVersion: 5,
- newName: "x.md",
- ifMatch: 4,
- })
- ).toThrow(MoveError);
- });
-});
diff --git a/gfs-controller/src/api/move.ts b/gfs-controller/src/api/move.ts
deleted file mode 100644
index 020c55d91..000000000
--- a/gfs-controller/src/api/move.ts
+++ /dev/null
@@ -1,167 +0,0 @@
-/**
- * Move / rename validation (spec community.md §Move, rename, delete).
- *
- * A move is a pure DB reparent — bytes live flat by resourceId, so nothing is
- * renamed or relocated on disk. This module is the writer-routed, side-effect-
- * free core that the gfs write path uses to decide whether a rename/move is
- * legal and which permission checks it requires:
- *
- * - rename (name) → `write` on the resource.
- * - move (reparent)→ `write` + `delete` on the source parent, `write` on the
- * destination parent. Never crosses `drive` (cross_boundary).
- * - concurrency → monotonic `version`; `etag = version`; a stale `If-Match`
- * is `precondition_failed` (writer-routed, never checked
- * against a possibly-stale reader replica).
- *
- * Pure — no I/O. The caller loads the rows, runs requiredChecks() against the
- * permission store, applies the DB reparent, and bumps `version`.
- */
-
-export type GfsPermission = "read" | "write" | "delete" | "manage_acl" | "share";
-
-export type MoveErrorCode =
- | "path_invalid"
- | "cross_boundary"
- | "precondition_failed"
- | "not_found";
-
-export class MoveError extends Error {
- constructor(
- readonly code: MoveErrorCode,
- message?: string,
- ) {
- super(message ?? code);
- this.name = "MoveError";
- }
-}
-
-/** A single (resourceId, op) authorization the caller must hold for the change. */
-export interface PermissionCheck {
- resourceId: string;
- op: GfsPermission;
-}
-
-export interface MoveRequest {
- /** The resource being changed. */
- resourceId: string;
- sourceDrive: string;
- /** Current parent (null for a drive root, which cannot be moved/renamed away). */
- sourceParentId: string | null;
- /** Its current monotonic version (= etag). */
- currentVersion: number;
- /** New name (rename) — NFC-normalized + validated. */
- newName?: string;
- /** New parent + its drive (move). */
- newParentId?: string;
- destDrive?: string;
- /** R + the destination's ancestor ids — supplied for the descendant cycle check. */
- destAncestors?: string[];
- /** Optional optimistic-concurrency guard. */
- ifMatch?: number;
-}
-
-export interface MovePlan {
- kind: "rename" | "move" | "rename+move";
- /** Final name to write (validated). */
- name?: string;
- newParentId?: string;
- /** Permission checks the caller must satisfy (spec §Move). */
- checks: PermissionCheck[];
- /** version to write (currentVersion + 1). */
- nextVersion: number;
-}
-
-const NAME_MAX = 255;
-/** Control characters (incl. NUL) are never valid in a name; spaces ARE valid. */
-const CONTROL_CHARS = /[\x00-\x1f\x7f]/; // eslint-disable-line no-control-regex
-
-/**
- * NFC-normalize and validate a path segment. Rejects empty, `.`/`..`, any
- * slash, control chars (incl. NUL), and over-length names. Spaces ARE allowed
- * ("My Report.md") — the blob is keyed by resourceId, not name.
- */
-export function normalizeName(raw: string): string {
- if (typeof raw !== "string") throw new MoveError("path_invalid", "name must be a string");
- const name = raw.normalize("NFC");
- if (
- name.length === 0 ||
- name.length > NAME_MAX ||
- name === "." ||
- name === ".." ||
- name.includes("/") ||
- CONTROL_CHARS.test(name)
- ) {
- throw new MoveError("path_invalid", `invalid name: ${JSON.stringify(raw)}`);
- }
- return name;
-}
-
-/** Throw precondition_failed when a provided If-Match does not match the version. */
-export function assertIfMatch(currentVersion: number, ifMatch?: number): void {
- if (ifMatch !== undefined && ifMatch !== currentVersion) {
- throw new MoveError("precondition_failed", `If-Match ${ifMatch} != version ${currentVersion}`);
- }
-}
-
-/**
- * Build the validated plan for a rename and/or move. Throws MoveError on a bad
- * name, a stale If-Match, a cross-drive move, or a no-op request. The returned
- * `checks` are exactly the spec's required permissions:
- * rename → write on the resource;
- * move → write+delete on the source parent, write on the destination parent.
- */
-export function planMove(req: MoveRequest): MovePlan {
- assertIfMatch(req.currentVersion, req.ifMatch);
-
- const wantsRename = req.newName !== undefined;
- const wantsMove = req.newParentId !== undefined;
- if (!wantsRename && !wantsMove) {
- throw new MoveError("path_invalid", "no rename or move requested");
- }
-
- const checks: PermissionCheck[] = [];
- let name: string | undefined;
-
- if (wantsRename) {
- name = normalizeName(req.newName as string);
- // rename authority is `write` on the resource itself.
- checks.push({ resourceId: req.resourceId, op: "write" });
- }
-
- if (wantsMove) {
- // Fail-closed: a move MUST state its destination drive — never assume the
- // source drive, or a cross-drive move with an omitted destDrive slips through.
- if (req.destDrive === undefined) {
- throw new MoveError("path_invalid", "destDrive is required for a move");
- }
- if (req.destDrive !== req.sourceDrive) {
- throw new MoveError("cross_boundary", "cross-drive move is forbidden");
- }
- if (req.sourceParentId === null) {
- throw new MoveError("path_invalid", "the drive root cannot be moved");
- }
- const dest = req.newParentId as string;
- // Cycle guard: a resource may never move into itself or its own descendants
- // (that would orphan the subtree and loop ancestor traversal). The trivial
- // self-move is checkable purely; the full descendant check uses destAncestors
- // (R + the destination's ancestors) when the caller supplies it.
- if (dest === req.resourceId || (req.destAncestors !== undefined && req.destAncestors.includes(req.resourceId))) {
- throw new MoveError("path_invalid", "cannot move a resource into its own subtree");
- }
- // move authority: write+delete on the source parent, write on the dest parent.
- checks.push({ resourceId: req.sourceParentId, op: "write" });
- checks.push({ resourceId: req.sourceParentId, op: "delete" });
- checks.push({ resourceId: dest, op: "write" });
- }
-
- const kind: MovePlan["kind"] =
- wantsRename && wantsMove ? "rename+move" : wantsRename ? "rename" : "move";
-
- return {
- kind,
- name,
- newParentId: wantsMove ? (req.newParentId as string) : undefined,
- checks,
- nextVersion: req.currentVersion + 1,
- };
-}
diff --git a/gfs-controller/src/api/read.test.ts b/gfs-controller/src/api/read.test.ts
index 15951d99a..7dde488bc 100644
--- a/gfs-controller/src/api/read.test.ts
+++ b/gfs-controller/src/api/read.test.ts
@@ -1,5 +1,10 @@
import { describe, expect, it } from "vitest";
+import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
import { Readable } from "node:stream";
+import { BlobStore } from "../storage/blobStore";
+import { GENERATION_STORAGE_DIRECTORY } from "../storage/paths";
import { GfsError } from "./errors";
import {
BlobReader,
@@ -27,6 +32,8 @@ function resource(partial: Partial<GfsResource> & { resourceId: string; name: st
pathCache: null,
version: 0,
bytes: 0,
+ blobKey: null,
+ contentSha256: null,
deletedAt: null,
...partial,
};
@@ -69,6 +76,22 @@ const blobs: BlobReader = {
read: async (id) => Readable.from([Buffer.from(`bytes:${id}`)]),
};
+function deferred(): { promise: Promise<void>; resolve: () => void } {
+ let resolve!: () => void;
+ const promise = new Promise<void>(done => {
+ resolve = done;
+ });
+ return { promise, resolve };
+}
+
+async function collect(stream: Readable): Promise<Buffer> {
+ const chunks: Buffer[] = [];
+ for await (const chunk of stream) {
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
+ }
+ return Buffer.concat(chunks);
+}
+
function dirStore(): FakeStore {
return new FakeStore().add(resource({ resourceId: PARENT, name: "root", kind: "directory" }));
}
@@ -180,6 +203,119 @@ describe("downloadResource", () => {
expect(view.kind).toBe("file");
});
+ it("reads exactly the generation selected by metadata while legacy rows use the flat key", async () => {
+ const calls: Array<{ resourceId: string; blobKey?: string | null }> = [];
+ const keyedBlobs: BlobReader = {
+ read: async (resourceId, blobKey) => {
+ calls.push({ resourceId, blobKey });
+ return Readable.from([Buffer.from(blobKey ?? "legacy")]);
+ },
+ };
+ const key = `${rid(10)}/11111111-1111-4111-8111-111111111111`;
+ const store = dirStore()
+ .add(resource({ resourceId: rid(10), name: "new", blobKey: key, contentSha256: "a".repeat(64) }))
+ .add(resource({ resourceId: rid(11), name: "legacy" }));
+
+ await downloadResource(store, keyedBlobs, "main", rid(10));
+ await downloadResource(store, keyedBlobs, "main", rid(11));
+ expect(calls).toEqual([
+ { resourceId: rid(10), blobKey: key },
+ { resourceId: rid(11), blobKey: null },
+ ]);
+ });
+
+ it("an opened reader returns one complete generation while a replacement is staged", async () => {
+ const directory = mkdtempSync(join(tmpdir(), "gfs-read-snapshot-"));
+ const resourceId = rid(12);
+ const oldGeneration = "11111111-1111-4111-8111-111111111111";
+ const newGeneration = "22222222-2222-4222-8222-222222222222";
+ const oldBytes = Buffer.alloc(256 * 1024, "o");
+ const newBytes = Buffer.alloc(256 * 1024, "n");
+ const candidateDurable = deferred();
+ const releaseCandidate = deferred();
+
+ try {
+ const initialWriter = new BlobStore(directory, "writer");
+ const oldBlob = await initialWriter.writeImmutable(resourceId, oldGeneration, oldBytes);
+ expect(oldBlob.blobKey).toBe(`${resourceId}/${oldGeneration}`);
+ expect(
+ existsSync(join(directory, GENERATION_STORAGE_DIRECTORY, resourceId, oldGeneration))
+ ).toBe(true);
+
+ const metadata = dirStore().add(
+ resource({
+ resourceId,
+ name: "snapshot.bin",
+ bytes: oldBytes.length,
+ blobKey: oldBlob.blobKey,
+ contentSha256: oldBlob.contentSha256,
+ })
+ );
+ const reader = new BlobStore(directory, "reader");
+ const openedOld = await downloadResource(metadata, reader, "main", resourceId);
+
+ let firstSync = true;
+ const stagingWriter = new BlobStore(directory, "writer", async () => {
+ if (!firstSync) return;
+ firstSync = false;
+ candidateDurable.resolve();
+ await releaseCandidate.promise;
+ });
+ const stagedWrite = stagingWriter.writeImmutable(resourceId, newGeneration, newBytes);
+ await candidateDurable.promise;
+
+ expect(await collect(openedOld.stream)).toEqual(oldBytes);
+ expect((await metadata.getResource("main", resourceId))?.blobKey).toBe(oldBlob.blobKey);
+
+ releaseCandidate.resolve();
+ const newBlob = await stagedWrite;
+ metadata.add(
+ resource({
+ resourceId,
+ name: "snapshot.bin",
+ version: 1,
+ bytes: newBytes.length,
+ blobKey: newBlob.blobKey,
+ contentSha256: newBlob.contentSha256,
+ })
+ );
+
+ const openedNew = await downloadResource(metadata, reader, "main", resourceId);
+ expect(newBlob.blobKey).toBe(`${resourceId}/${newGeneration}`);
+ expect(await collect(openedNew.stream)).toEqual(newBytes);
+ } finally {
+ releaseCandidate.resolve();
+ rmSync(directory, { recursive: true, force: true });
+ }
+ });
+
+ it("reads a legacy flat blob when metadata has no generation pointer", async () => {
+ const directory = mkdtempSync(join(tmpdir(), "gfs-legacy-read-"));
+ const resourceId = rid(13);
+ const legacyBytes = Buffer.from("complete legacy bytes");
+ try {
+ writeFileSync(join(directory, resourceId), legacyBytes);
+ const metadata = dirStore().add(
+ resource({
+ resourceId,
+ name: "legacy.txt",
+ bytes: legacyBytes.length,
+ blobKey: null,
+ contentSha256: null,
+ })
+ );
+ const download = await downloadResource(
+ metadata,
+ new BlobStore(directory, "reader"),
+ "main",
+ resourceId
+ );
+ expect(await collect(download.stream)).toEqual(legacyBytes);
+ } finally {
+ rmSync(directory, { recursive: true, force: true });
+ }
+ });
+
it("is_a_directory when targeting a folder", async () => {
const store = dirStore().add(resource({ resourceId: rid(6), name: "d", kind: "directory" }));
await expect(downloadResource(store, blobs, "main", rid(6))).rejects.toMatchObject({
diff --git a/gfs-controller/src/api/read.ts b/gfs-controller/src/api/read.ts
index e1fd8705f..61af5f4cb 100644
--- a/gfs-controller/src/api/read.ts
+++ b/gfs-controller/src/api/read.ts
@@ -12,6 +12,10 @@ export interface GfsResource {
pathCache: string | null;
version: number;
bytes: number;
+ /** Internal committed physical generation. Never exposed in GfsResourceView. */
+ blobKey: string | null;
+ /** Digest of the committed generation. Never exposed in GfsResourceView. */
+ contentSha256: string | null;
deletedAt: string | null;
}
@@ -45,7 +49,7 @@ export interface ResourceStore {
}
export interface BlobReader {
- read(resourceId: string): Promise<Readable>;
+ read(resourceId: string, blobKey?: string | null): Promise<Readable>;
}
export const DEFAULT_LIMIT = 100;
@@ -182,7 +186,7 @@ export async function downloadResource(
throw new GfsError("is_a_directory", `resource is a directory: ${resourceId}`);
}
try {
- const stream = await blobs.read(normalized);
+ const stream = await blobs.read(normalized, resource.blobKey);
return { resource: toView(resource), stream };
} catch (err) {
if ((err as { code?: string }).code === "not_found") {
diff --git a/gfs-controller/src/api/renameRoute.ts b/gfs-controller/src/api/renameRoute.ts
new file mode 100644
index 000000000..07ce41364
--- /dev/null
+++ b/gfs-controller/src/api/renameRoute.ts
@@ -0,0 +1,53 @@
+import type { GfsVerifiedClaims } from "../auth/verify";
+import type { AuditSink } from "../authz/audit";
+import type { AuthzContext } from "../authz/permissionClient";
+import type { GfsWriteService } from "../db/writeStore";
+import { GfsError } from "./errors";
+import { toView } from "./read";
+import { normalizeResourceName, ResourceNameError } from "./resourceName";
+
+export interface RenameRouteInput {
+ body: Record<string, unknown>;
+ claims: GfsVerifiedClaims;
+ context: AuthzContext;
+ resourceId: string;
+ requestId: string;
+ audit: AuditSink;
+ authorizeWrite: () => Promise<void>;
+ writes: Pick<GfsWriteService, "rename">;
+ limits: { maxObjects: number; timeoutMs: number };
+}
+
+export async function executeRenameRoute(input: RenameRouteInput): Promise<ReturnType<typeof toView>> {
+ if (Object.keys(input.body).sort().join(",") !== "drive,ifMatch,newName") {
+ throw new GfsError("path_invalid", "rename body must contain exactly drive, newName and ifMatch");
+ }
+ const drive = input.body.drive;
+ if (typeof drive !== "string" || drive.length === 0) throw new GfsError("path_invalid", "rename drive must be a non-empty string");
+ if (drive !== input.claims.drive) throw new GfsError("cross_boundary", "rename drive does not match the authorized drive");
+ const rawName = input.body.newName;
+ if (typeof rawName !== "string") throw new GfsError("path_invalid", "rename newName must be a string");
+ let newName: string;
+ try { newName = normalizeResourceName(rawName); }
+ catch (error) {
+ if (error instanceof ResourceNameError) throw new GfsError("path_invalid", error.message);
+ throw error;
+ }
+ const ifMatch = input.body.ifMatch;
+ if (!Number.isSafeInteger(ifMatch) || Number(ifMatch) < 0) {
+ throw new GfsError("path_invalid", "rename ifMatch must be a non-negative safe integer");
+ }
+ try { await input.authorizeWrite(); }
+ catch (error) {
+ if (error instanceof GfsError && error.code === "forbidden") {
+ throw new GfsError("forbidden", "rename is not authorized");
+ }
+ throw error;
+ }
+ const updated = await input.writes.rename({
+ requestId: input.requestId, subject: input.context.primarySubject, audit: input.audit,
+ drive, resourceId: input.resourceId, newName, ifMatch: Number(ifMatch),
+ maxObjects: input.limits.maxObjects, deadlineAtMs: Date.now() + input.limits.timeoutMs,
+ });
+ return toView(updated);
+}
diff --git a/gfs-controller/src/api/resourceName.ts b/gfs-controller/src/api/resourceName.ts
new file mode 100644
index 000000000..0408f966c
--- /dev/null
+++ b/gfs-controller/src/api/resourceName.ts
@@ -0,0 +1,31 @@
+const NAME_MAX = 255;
+/** Control characters (including NUL) are never valid in a resource name. */
+const CONTROL_CHARS = /[\x00-\x1f\x7f]/; // eslint-disable-line no-control-regex
+
+export class ResourceNameError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "ResourceNameError";
+ }
+}
+
+/**
+ * Normalize and validate one GFS resource-name segment. This primitive is
+ * deliberately operation-neutral: resource operations may share the name
+ * contract without sharing authorization or mutation semantics.
+ */
+export function normalizeResourceName(raw: string): string {
+ if (typeof raw !== "string") throw new ResourceNameError("name must be a string");
+ const name = raw.normalize("NFC");
+ if (
+ name.length === 0
+ || name.length > NAME_MAX
+ || name === "."
+ || name === ".."
+ || name.includes("/")
+ || CONTROL_CHARS.test(name)
+ ) {
+ throw new ResourceNameError(`invalid name: ${JSON.stringify(raw)}`);
+ }
+ return name;
+}
diff --git a/gfs-controller/src/api/serve.copy.test.ts b/gfs-controller/src/api/serve.copy.test.ts
new file mode 100644
index 000000000..c2ea14e9c
--- /dev/null
+++ b/gfs-controller/src/api/serve.copy.test.ts
@@ -0,0 +1,330 @@
+import { EventEmitter } from "node:events";
+import type { IncomingMessage } from "node:http";
+import { PassThrough, Readable } from "node:stream";
+import { describe, expect, it, vi } from "vitest";
+import type { GfsVerifiedClaims } from "../auth/verify";
+import type { AuditEvent } from "../authz/audit";
+import type { AuthzContext } from "../authz/permissionClient";
+import type { CopyDestinationSnapshot, CopySnapshotNode } from "./copy";
+import { GfsServingHandler, type ServingDeps } from "./serve";
+
+const ROOT = "00000000-0000-4000-8000-000000000001";
+const DEST = "00000000-0000-4000-8000-000000000002";
+const SOURCE = "00000000-0000-4000-8000-000000000003";
+const CHILD = "00000000-0000-4000-8000-000000000004";
+const REQUEST = "00000000-0000-4000-8000-000000000005";
+const claims: GfsVerifiedClaims = {
+ sub: "host:test", drive: "main", scopes: ["gfs.read", "gfs.write"], pathBindings: [], iat: 1, exp: 2,
+};
+const context: AuthzContext = {
+ primarySubject: "agent:test", subjects: ["agent:test"], drive: "main", isOperator: false, requestId: REQUEST,
+};
+
+function node(over: Partial<CopySnapshotNode> = {}): CopySnapshotNode {
+ return { resourceId: SOURCE, drive: "main", parentResourceId: ROOT, name: "source", kind: "directory",
+ pathCache: "/source", version: 2, bytes: 0n, blobKey: null, contentSha256: null,
+ deletedAt: null, depth: 0, cycle: false, underTombstone: false, ...over };
+}
+
+class Response extends EventEmitter {
+ statusCode = 0; headersSent = false; body = "";
+ writeHead(status: number): this { this.statusCode = status; this.headersSent = true; return this; }
+ end(value?: string): this { if (value) this.body += value; this.emit("close"); return this; }
+ json(): unknown { return JSON.parse(this.body); }
+}
+
+function request(body: Record<string, unknown>) {
+ const stream = Readable.from([Buffer.from(JSON.stringify(body))]) as Readable & { method: string; url: string; headers: Record<string, string> };
+ stream.method = "POST"; stream.url = "/v1/copy";
+ stream.headers = { authorization: "Bearer local", "content-type": "application/json", "x-request-id": REQUEST };
+ return stream as unknown as IncomingMessage;
+}
+
+function fixture(options: { child?: boolean; snapshotCount?: number; omitLastParent?: boolean; denyChild?: boolean; copyError?: unknown; scopes?: GfsVerifiedClaims["scopes"]; times?: number[] } = {}) {
+ const snapshot = [node()];
+ if (options.child) snapshot.push(node({ resourceId: CHILD, parentResourceId: SOURCE, name: "child", pathCache: "/source/child", depth: 1 }));
+ for (let index = snapshot.length; index < (options.snapshotCount ?? snapshot.length); index += 1) {
+ const resourceId = `20000000-0000-4000-8000-${String(index).padStart(12, "0")}`;
+ snapshot.push(node({ resourceId, parentResourceId: SOURCE, name: `child-${index}`, pathCache: `/source/child-${index}`, depth: 1 }));
+ }
+ if (options.omitLastParent && snapshot.length > 1) snapshot[snapshot.length - 1].parentResourceId = ROOT;
+ const destination: CopyDestinationSnapshot = { ancestors: [
+ node({ resourceId: DEST, parentResourceId: ROOT, name: "archive", pathCache: "/archive", version: 1 }),
+ node({ resourceId: ROOT, parentResourceId: null, name: "", pathCache: "/", version: 0, depth: 1 }),
+ ], liveChildren: [] };
+ const batch: Array<Array<{ resourceId: string; op: string }>> = [];
+ const audits: AuditEvent[] = [];
+ let loads = 0;
+ const copy = vi.fn(async (input: { requestId: string }) => {
+ if (options.copyError) throw options.copyError;
+ return { root: {
+ resourceId: "10000000-0000-4000-8000-000000000001", drive: "main", parentResourceId: DEST,
+ name: "source-copy", kind: "directory" as const, pathCache: "/archive/source-copy", version: 0,
+ bytes: 0, blobKey: null, contentSha256: null, deletedAt: null,
+ }, requestId: input.requestId, objectCount: snapshot.length, fileCount: 0,
+ folderCount: snapshot.length, totalBytes: 0n };
+ });
+ const deps: ServingDeps = {
+ verifyToken: () => ({ ...claims, scopes: options.scopes ?? claims.scopes }),
+ resolveContext: async (_claims, requestId) => ({ ...context, requestId }),
+ authorize: async () => ({ allowed: true }),
+ store: { getResource: async () => null, listChildren: async () => [] },
+ blobs: { read: async () => Readable.from([]) },
+ writeService: { copy } as unknown as ServingDeps["writeService"],
+ copy: {
+ authorizeMany: async (_ctx, requests) => {
+ batch.push(requests.map(item => ({ ...item })));
+ return requests.map(item => ({ allowed: !(options.denyChild && item.resourceId === CHILD.replaceAll("-", "")) }));
+ },
+ permissionEpoch: () => ({ generation: 0, bypassed: false }),
+ resources: {
+ loadCopyAdmission: async () => ({ sourceRoot: snapshot[0] ?? null, destinationParent: destination.ancestors[0] ?? null }),
+ loadCopySnapshot: async () => { loads += 1; return snapshot; },
+ loadCopyDestination: async () => { loads += 1; return destination; },
+ },
+ audit: { record: async event => { audits.push(event); } },
+ maxObjects: 1000, maxBytes: 1024 * 1024, timeoutMs: 30_000,
+ },
+ now: () => options.times?.shift() ?? 10,
+ };
+ return { deps, destination, handler: new GfsServingHandler(deps), batch, audits, copy, get loads() { return loads; } };
+}
+
+describe("POST /v1/copy", () => {
+ it("aborts a stalled request body from the HTTP admission timer before metadata loads", async () => {
+ vi.useFakeTimers();
+ try {
+ const f = fixture();
+ f.deps.copy!.timeoutMs = 25;
+ const stalled = new PassThrough() as PassThrough & { method: string; url: string; headers: Record<string, string> };
+ stalled.method = "POST"; stalled.url = "/v1/copy";
+ stalled.headers = { authorization: "Bearer local", "content-type": "application/json", "x-request-id": REQUEST };
+ const res = new Response();
+ const handling = f.handler.tryHandle(stalled as unknown as IncomingMessage, res as never);
+ await vi.advanceTimersByTimeAsync(25);
+ await handling;
+ expect(res.statusCode).toBe(412);
+ expect(f.loads).toBe(0);
+ expect(f.batch).toEqual([]);
+ expect(f.copy).not.toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("re-arms timeouts above the Node timer maximum instead of overflowing to 1 ms", async () => {
+ vi.useFakeTimers();
+ try {
+ const f = fixture();
+ f.deps.copy!.timeoutMs = 2_147_483_648;
+ const stalled = new PassThrough() as PassThrough & { method: string; url: string; headers: Record<string, string> };
+ stalled.method = "POST"; stalled.url = "/v1/copy";
+ stalled.headers = { authorization: "Bearer local", "content-type": "application/json", "x-request-id": REQUEST };
+ const res = new Response();
+ const handling = f.handler.tryHandle(stalled as unknown as IncomingMessage, res as never);
+
+ await vi.advanceTimersByTimeAsync(1);
+ expect(res.statusCode).toBe(0);
+ await vi.advanceTimersByTimeAsync(2_147_483_646);
+ expect(res.statusCode).toBe(0);
+ await vi.advanceTimersByTimeAsync(1);
+ await handling;
+
+ expect(res.statusCode).toBe(412);
+ expect(f.loads).toBe(0);
+ expect(f.copy).not.toHaveBeenCalled();
+ expect(vi.getTimerCount()).toBe(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("does not extend a long deadline when its first timer callback is delayed", async () => {
+ vi.useFakeTimers();
+ let monotonicNowNs = 0n;
+ const monotonicClock = vi.spyOn(process.hrtime, "bigint").mockImplementation(() => monotonicNowNs);
+ try {
+ const f = fixture();
+ f.deps.copy!.timeoutMs = 2_147_484_647;
+ const stalled = new PassThrough() as PassThrough & { method: string; url: string; headers: Record<string, string> };
+ stalled.method = "POST"; stalled.url = "/v1/copy";
+ stalled.headers = { authorization: "Bearer local", "content-type": "application/json", "x-request-id": REQUEST };
+ const res = new Response();
+ const handling = f.handler.tryHandle(stalled as unknown as IncomingMessage, res as never);
+
+ // Model an event-loop stall or machine suspension: the first bounded
+ // timer fires, but the monotonic clock has already crossed the real
+ // request deadline. Nominal chunk subtraction would incorrectly re-arm.
+ monotonicNowNs = 2_147_484_648n * 1_000_000n;
+ await vi.advanceTimersByTimeAsync(2_147_483_647);
+ await handling;
+
+ expect(res.statusCode).toBe(412);
+ expect(f.loads).toBe(0);
+ expect(f.copy).not.toHaveBeenCalled();
+ expect(vi.getTimerCount()).toBe(0);
+ } finally {
+ monotonicClock.mockRestore();
+ vi.useRealTimers();
+ }
+ });
+
+ it("clears a long copy timer when the request completes", async () => {
+ vi.useFakeTimers();
+ try {
+ const f = fixture();
+ f.deps.copy!.timeoutMs = Number.MAX_SAFE_INTEGER;
+ const res = new Response();
+
+ await f.handler.tryHandle(request({ drive: "main", sourceResourceId: SOURCE, destinationParentId: DEST, ifMatch: 2 }), res as never);
+
+ expect(res.statusCode).toBe(201);
+ expect(vi.getTimerCount()).toBe(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("keeps the maximum safe timeout exact with a relative deadline budget", async () => {
+ const admittedAtMs = 1_700_000_000_000;
+ const f = fixture({ times: [
+ admittedAtMs,
+ admittedAtMs + 1,
+ admittedAtMs + 2,
+ admittedAtMs + 3,
+ admittedAtMs + 4,
+ admittedAtMs + 5,
+ admittedAtMs + 6,
+ admittedAtMs + 7,
+ ] });
+ f.deps.copy!.timeoutMs = Number.MAX_SAFE_INTEGER;
+ const res = new Response();
+
+ await f.handler.tryHandle(request({ drive: "main", sourceResourceId: SOURCE, destinationParentId: DEST, ifMatch: 2 }), res as never);
+
+ expect(res.statusCode).toBe(201);
+ const publication = f.copy.mock.calls[0][0] as { deadlineAtMs: number; now: () => number };
+ expect(publication.deadlineAtMs).toBe(Number.MAX_SAFE_INTEGER);
+ expect(publication.now()).toBe(7);
+ });
+
+ it("adopts one request id, batch-authorizes the frozen tree and returns a minimal DTO", async () => {
+ const f = fixture({ child: true }); const res = new Response();
+ await f.handler.tryHandle(request({ drive: "main", sourceResourceId: SOURCE, destinationParentId: DEST, newName: "source-copy", ifMatch: 2 }), res as never);
+ expect(res.statusCode).toBe(201);
+ expect(f.batch).toEqual([
+ [
+ { resourceId: SOURCE.replaceAll("-", ""), op: "read" },
+ { resourceId: DEST.replaceAll("-", ""), op: "write" },
+ ],
+ [
+ { resourceId: SOURCE.replaceAll("-", ""), op: "read" },
+ { resourceId: CHILD.replaceAll("-", ""), op: "read" },
+ { resourceId: DEST.replaceAll("-", ""), op: "write" },
+ ],
+ ]);
+ expect(f.copy).toHaveBeenCalledOnce();
+ expect(f.copy.mock.calls[0][0]).toMatchObject({
+ requestId: REQUEST, subject: "agent:test", destinationParentId: DEST.replaceAll("-", ""),
+ });
+ expect(res.json()).toEqual({ ok: true, data: {
+ requestId: REQUEST,
+ resourceId: "10000000-0000-4000-8000-000000000001",
+ rid: "10000000000040008000000000000001",
+ gfsUri: "gfs://main/10000000000040008000000000000001",
+ name: "source-copy", kind: "directory", version: 0,
+ objects: 2, files: 0, folders: 2, bytes: 0,
+ } });
+ expect(res.body).not.toContain("blobKey");
+ });
+
+ it("returns one generic denial when a descendant is denied", async () => {
+ const f = fixture({ child: true, denyChild: true }); const res = new Response();
+ await f.handler.tryHandle(request({ drive: "main", sourceResourceId: SOURCE, destinationParentId: DEST, ifMatch: 2 }), res as never);
+ expect(res.statusCode).toBe(403);
+ expect(res.body).toContain("copy is not authorized");
+ expect(res.body).not.toContain(CHILD);
+ expect(f.copy).not.toHaveBeenCalled();
+ expect(f.audits).toEqual([]);
+ });
+
+ it("is absent on readers and maps ENOSPC without leaking storage details", async () => {
+ const reader = fixture();
+ delete reader.deps.writeService; delete reader.deps.copy;
+ const absent = new Response();
+ await reader.handler.tryHandle(request({ drive: "main", sourceResourceId: SOURCE, destinationParentId: DEST, ifMatch: 2 }), absent as never);
+ expect(absent.statusCode).toBe(404);
+
+ const writer = fixture({ copyError: Object.assign(new Error("private filesystem path"), { code: "ENOSPC" }) });
+ const full = new Response();
+ await writer.handler.tryHandle(request({ drive: "main", sourceResourceId: SOURCE, destinationParentId: DEST, ifMatch: 2 }), full as never);
+ expect(full.statusCode).toBe(413);
+ expect(full.body).not.toContain("private filesystem path");
+ });
+
+ it("rejects a body-drive mismatch before loading either tree", async () => {
+ const f = fixture(); const res = new Response();
+ await f.handler.tryHandle(request({ drive: "other", sourceResourceId: SOURCE, destinationParentId: DEST, ifMatch: 2 }), res as never);
+ expect(res.statusCode).toBe(409);
+ expect(f.loads).toBe(0);
+ expect(f.batch).toEqual([]);
+ expect(f.copy).not.toHaveBeenCalled();
+ expect(f.audits).toEqual([]);
+ });
+
+ it("uses the admission timestamp for timeout and audits only after batch authorization", async () => {
+ const timed = fixture({ times: [0, 0, 0, 30_000] }); const timedRes = new Response();
+ await timed.handler.tryHandle(request({ drive: "main", sourceResourceId: SOURCE, destinationParentId: DEST, ifMatch: 2 }), timedRes as never);
+ expect(timedRes.statusCode).toBe(412);
+ expect(timed.copy).not.toHaveBeenCalled();
+ expect(timed.audits).toHaveLength(0);
+
+ const ceiling = fixture({ scopes: ["gfs.read"] }); const denied = new Response();
+ await ceiling.handler.tryHandle(request({ drive: "main", sourceResourceId: SOURCE, destinationParentId: DEST, ifMatch: 2 }), denied as never);
+ expect(denied.statusCode).toBe(403);
+ expect(ceiling.copy).not.toHaveBeenCalled();
+ expect(ceiling.audits).toEqual([]);
+ });
+
+ it("enforces If-Match, collision and object limits after authorization", async () => {
+ const stale = fixture(); const staleRes = new Response();
+ const staleAudit = vi.spyOn(stale.deps.copy!.audit, "record");
+ await stale.handler.tryHandle(request({ drive: "main", sourceResourceId: SOURCE, destinationParentId: DEST }), staleRes as never);
+ expect(staleRes.statusCode).toBe(412);
+ expect(stale.audits).toHaveLength(1);
+ expect(staleAudit.mock.calls[0][2]).toMatchObject({ deadlineAtMs: expect.any(Number) });
+
+ const collision = fixture();
+ collision.destination.liveChildren.push({ resourceId: CHILD, name: "source" });
+ const collisionRes = new Response();
+ await collision.handler.tryHandle(request({ drive: "main", sourceResourceId: SOURCE, destinationParentId: DEST, ifMatch: 2 }), collisionRes as never);
+ expect(collisionRes.statusCode).toBe(409);
+
+ const limited = fixture({ child: true }); limited.deps.copy!.maxObjects = 1;
+ const limitedRes = new Response();
+ await limited.handler.tryHandle(request({ drive: "main", sourceResourceId: SOURCE, destinationParentId: DEST, ifMatch: 2 }), limitedRes as never);
+ expect(limitedRes.statusCode).toBe(413);
+
+ const exact = fixture(); exact.deps.copy!.maxObjects = 1;
+ const exactRes = new Response();
+ await exact.handler.tryHandle(request({ drive: "main", sourceResourceId: SOURCE, destinationParentId: DEST, ifMatch: 2 }), exactRes as never);
+ expect(exactRes.statusCode).toBe(201);
+ });
+
+ it("rejects the bounded one-over snapshot without publishing", async () => {
+ const fixture1001 = fixture({ snapshotCount: 1001 }); const res = new Response();
+ await fixture1001.handler.tryHandle(request({ drive: "main", sourceResourceId: SOURCE, destinationParentId: DEST, ifMatch: 2 }), res as never);
+ expect(res.statusCode).toBe(413);
+ expect(fixture1001.batch[1]).toHaveLength(1002);
+ expect(fixture1001.copy).not.toHaveBeenCalled();
+ expect(fixture1001.audits).toHaveLength(1);
+ });
+
+ it("rejects an unordered one-over sentinel before validating its omitted parent or publishing", async () => {
+ const fixture1001 = fixture({ snapshotCount: 1001, omitLastParent: true }); const res = new Response();
+ await fixture1001.handler.tryHandle(request({ drive: "main", sourceResourceId: SOURCE, destinationParentId: DEST, ifMatch: 2 }), res as never);
+ expect(res.statusCode).toBe(413);
+ expect(fixture1001.copy).not.toHaveBeenCalled();
+ expect(fixture1001.audits).toHaveLength(1);
+ });
+});
diff --git a/gfs-controller/src/api/serve.rename.test.ts b/gfs-controller/src/api/serve.rename.test.ts
new file mode 100644
index 000000000..f97faadb7
--- /dev/null
+++ b/gfs-controller/src/api/serve.rename.test.ts
@@ -0,0 +1,99 @@
+import { EventEmitter } from "node:events";
+import type { IncomingMessage } from "node:http";
+import { Readable } from "node:stream";
+import { describe, expect, it, vi } from "vitest";
+import type { GfsVerifiedClaims } from "../auth/verify";
+import type { AuthzContext } from "../authz/permissionClient";
+import { GfsServingHandler, type ServingDeps } from "./serve";
+
+const RID = "00000000-0000-4000-8000-000000000011";
+const PARENT = "00000000-0000-4000-8000-000000000012";
+const REQUEST = "00000000-0000-4000-8000-000000000013";
+const claims: GfsVerifiedClaims = {
+ sub: "host:test", drive: "main", scopes: ["gfs.write"], pathBindings: [], iat: 1, exp: 2,
+};
+const context: AuthzContext = {
+ primarySubject: "agent:test", subjects: ["agent:test"], drive: "main", isOperator: false, requestId: REQUEST,
+};
+
+class Response extends EventEmitter {
+ statusCode = 0; headersSent = false; body = "";
+ writeHead(status: number): this { this.statusCode = status; this.headersSent = true; return this; }
+ end(value?: string): this { if (value) this.body += value; this.emit("close"); return this; }
+}
+
+function request(body: Record<string, unknown>): IncomingMessage {
+ const stream = Readable.from([Buffer.from(JSON.stringify(body))]) as Readable & {
+ method: string; url: string; headers: Record<string, string>;
+ };
+ stream.method = "PATCH"; stream.url = `/v1/resources/${RID}`;
+ stream.headers = { authorization: "Bearer local", "x-request-id": REQUEST };
+ return stream as unknown as IncomingMessage;
+}
+
+function fixture(options: { allowed?: boolean } = {}) {
+ const operations: string[] = [];
+ const rename = vi.fn(async (_input: unknown) => ({
+ resourceId: RID, drive: "main", parentResourceId: PARENT, name: "renamed", kind: "directory" as const,
+ pathCache: "/docs/renamed", version: 5, bytes: 0, blobKey: null, contentSha256: null, deletedAt: null,
+ }));
+ const deps: ServingDeps = {
+ verifyToken: () => claims,
+ resolveContext: async (_claims, requestId) => ({ ...context, requestId }),
+ authorize: async (_ctx, _rid, op) => { operations.push(op); return { allowed: options.allowed !== false }; },
+ store: { getResource: async () => null, listChildren: async () => [] },
+ blobs: { read: async () => Readable.from([]) },
+ writeService: { rename } as unknown as ServingDeps["writeService"],
+ audit: { record: async () => undefined },
+ rename: { maxObjects: 1000, timeoutMs: 30_000 },
+ };
+ return { deps, handler: new GfsServingHandler(deps), rename, operations };
+}
+
+describe("PATCH resource rename", () => {
+ it("authorizes write only and preserves stable identity", async () => {
+ const f = fixture(); const res = new Response();
+ await f.handler.tryHandle(request({ drive: "main", newName: "renamed", ifMatch: 4 }), res as never);
+ expect(res.statusCode).toBe(200);
+ expect(f.operations).toEqual(["write"]);
+ expect(f.rename).toHaveBeenCalledOnce();
+ expect(f.rename.mock.calls[0][0]).toMatchObject({
+ requestId: REQUEST, subject: "agent:test", drive: "main",
+ resourceId: RID.replaceAll("-", ""), newName: "renamed", ifMatch: 4,
+ maxObjects: 1000, deadlineAtMs: expect.any(Number),
+ });
+ expect(res.body).toContain(RID.replaceAll("-", ""));
+ expect(res.body).not.toContain("blobKey");
+ });
+
+ it("rejects drive mismatch and non-exact bodies before authorization", async () => {
+ const mismatch = fixture(); const mismatchRes = new Response();
+ await mismatch.handler.tryHandle(request({ drive: "other", newName: "renamed", ifMatch: 4 }), mismatchRes as never);
+ expect(mismatchRes.statusCode).toBe(409); expect(mismatch.operations).toEqual([]);
+ const extra = fixture(); const extraRes = new Response();
+ await extra.handler.tryHandle(request({ drive: "main", newName: "renamed", ifMatch: 4, extra: false }), extraRes as never);
+ expect(extraRes.statusCode).toBe(400); expect(extra.operations).toEqual([]);
+ });
+
+ it("returns generic deny and never calls rename", async () => {
+ const f = fixture({ allowed: false }); const res = new Response();
+ await f.handler.tryHandle(request({ drive: "main", newName: "renamed", ifMatch: 4 }), res as never);
+ expect(res.statusCode).toBe(403); expect(res.body).toContain("rename is not authorized");
+ expect(f.rename).not.toHaveBeenCalled();
+ });
+
+ it("does not expose PATCH on a reader", async () => {
+ const f = fixture(); delete f.deps.writeService; delete f.deps.audit;
+ const res = new Response();
+ await f.handler.tryHandle(request({ drive: "main", newName: "renamed", ifMatch: 4 }), res as never);
+ expect(res.statusCode).toBe(404); expect(f.operations).toEqual([]);
+ });
+
+ it("does not expose PATCH without configured rename admission limits", async () => {
+ const f = fixture(); delete f.deps.rename;
+ const res = new Response();
+ await f.handler.tryHandle(request({ drive: "main", newName: "renamed", ifMatch: 4 }), res as never);
+ expect(res.statusCode).toBe(404); expect(f.operations).toEqual([]);
+ expect(f.rename).not.toHaveBeenCalled();
+ });
+});
diff --git a/gfs-controller/src/api/serve.test.ts b/gfs-controller/src/api/serve.test.ts
index 4a3a34d45..c1579b0be 100644
--- a/gfs-controller/src/api/serve.test.ts
+++ b/gfs-controller/src/api/serve.test.ts
@@ -76,6 +76,8 @@ const FILE: GfsResource = {
pathCache: "/docs/report.pdf",
version: 2,
bytes: 11,
+ blobKey: null,
+ contentSha256: null,
deletedAt: null,
};
const DIR: GfsResource = {
@@ -93,6 +95,7 @@ function deps(over: Partial<ServingDeps> = {}): ServingDeps {
verifyToken: () => CLAIMS,
resolveContext: async () => CTX,
authorize: async () => ({ allowed: true }),
+ audit: { record: async () => undefined },
store: {
getResource: async () => FILE,
listChildren: async () => [FILE],
@@ -235,6 +238,20 @@ describe("GfsReadServer.tryHandle — served reads", () => {
expect(res.body).toBe("hello world");
});
+ it("destroys the blob stream when the client disconnects mid-download", async () => {
+ // fd-leak regression: pipe() does not propagate destination close to the
+ // source, so a client abort must destroy the blob stream explicitly.
+ const res = new FakeRes();
+ const source = new Readable({ read() {} });
+ source.push("partial");
+ const d = deps({ blobs: { read: async () => source } });
+ const handled = run(d, req(`/v1/resources/${RID}/content`, { auth: "Bearer t" }), res);
+ await new Promise(resolve => setTimeout(resolve, 0));
+ res.emit("close");
+ await handled;
+ expect(source.destroyed).toBe(true);
+ });
+
it("200 resolve maps a gfs:// uri (same drive) to its view", async () => {
const res = new FakeRes();
await run(deps(),
@@ -353,6 +370,35 @@ function writeDeps(over: Partial<ServingDeps> = {}): { d: ServingDeps; calls: Ar
}
describe("GfsServingHandler — write routes (governed mutation)", () => {
+ it("does not expose internal blob keys or physical paths in a failure response", async () => {
+ const res = new FakeRes();
+ const { d } = writeDeps({
+ writeService: {
+ create: async () => {
+ throw new Error(
+ "immutable blob failed: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/11111111-1111-4111-8111-111111111111 at /data/gfs/private"
+ );
+ },
+ } as unknown as ServingDeps["writeService"],
+ });
+ await run(
+ d,
+ reqBody(`/v1/resources/${RID}/children`, {
+ method: "POST",
+ auth: "Bearer t",
+ body: { name: "n.txt", content: "hi" },
+ }),
+ res
+ );
+ expect(res.statusCode).toBe(500);
+ expect(res.json).toEqual({
+ ok: false,
+ error: { code: "internal", message: "internal server error" },
+ });
+ expect(res.body).not.toContain("11111111-1111-4111-8111-111111111111");
+ expect(res.body).not.toContain("/data/gfs/private");
+ });
+
it("201 create (POST children) authorizes WRITE on the parent and calls the write service", async () => {
const res = new FakeRes();
const { d, calls, authzOps } = writeDeps();
diff --git a/gfs-controller/src/api/serve.ts b/gfs-controller/src/api/serve.ts
index ed262461f..cadae859b 100644
--- a/gfs-controller/src/api/serve.ts
+++ b/gfs-controller/src/api/serve.ts
@@ -1,6 +1,8 @@
+import { randomUUID } from "node:crypto";
import type { IncomingMessage, ServerResponse } from "node:http";
import type { GfsMetrics } from "../metrics";
import type { AuthzContext } from "../authz/permissionClient";
+import type { AuditSink } from "../authz/audit";
import type { AccessibleResourcePage } from "../authz/accessibleStore";
import type { GfsPermission } from "../authz/resolve";
import { checkTokenCeiling } from "../authz/tokenCeiling";
@@ -16,8 +18,10 @@ import {
toView,
} from "./read";
import { ok, toResponse } from "./envelope";
+import { executeCopyRoute, type CopyRouteDeps } from "./copyRoute";
+import { executeRenameRoute } from "./renameRoute";
import { GfsError } from "./errors";
-import { MoveError, normalizeName } from "./move";
+import { normalizeResourceName, ResourceNameError } from "./resourceName";
import { planWrite, WriteError } from "./write";
/**
@@ -58,6 +62,10 @@ export interface ServingDeps {
/** The transactional write data plane. Absent on a read-only replica — write
* routes then respond 404 (the verb is not served), never a silent no-op. */
writeService?: GfsWriteService;
+ audit?: AuditSink;
+ copy?: Omit<CopyRouteDeps, "writes">;
+ /** Admission limits for the synchronous rename mutation; PATCH is not served without them. */
+ rename?: { maxObjects: number; timeoutMs: number };
metrics?: GfsMetrics;
/** Injectable clock for deterministic latency tests; defaults to Date.now. */
now?: () => number;
@@ -65,6 +73,46 @@ export interface ServingDeps {
/** Largest mutation body gfsc accepts before failing loud with payload_too_large. */
const MAX_WRITE_BODY_BYTES = 16 * 1024 * 1024;
+const MAX_NODE_TIMER_DELAY_MS = 2_147_483_647;
+const NANOSECONDS_PER_MILLISECOND = 1_000_000n;
+
+/**
+ * Node clamps larger timer delays to 1 ms. Re-arm the copy deadline in bounded
+ * chunks so the full positive safe-integer ENV contract remains meaningful.
+ * Each callback recomputes its remaining budget against an absolute monotonic
+ * deadline: event-loop stalls and machine suspension must not extend the copy.
+ */
+function armCopyAbortTimer(controller: AbortController, timeoutMs: number): () => void {
+ const deadlineNs = process.hrtime.bigint() + BigInt(timeoutMs) * NANOSECONDS_PER_MILLISECOND;
+ let timer: NodeJS.Timeout | undefined;
+ let cancelled = false;
+
+ const armNextChunk = (): void => {
+ const remainingNs = deadlineNs - process.hrtime.bigint();
+ if (remainingNs <= 0n) {
+ controller.abort(new GfsError("precondition_failed", "synchronous copy deadline exceeded"));
+ return;
+ }
+ // Round up so an early timer callback cannot expire the request before its
+ // monotonic deadline. The next callback recomputes rather than subtracting
+ // this nominal delay, which also handles delayed callbacks correctly.
+ const remainingMs = Number(
+ (remainingNs + NANOSECONDS_PER_MILLISECOND - 1n) / NANOSECONDS_PER_MILLISECOND
+ );
+ const delayMs = Math.min(remainingMs, MAX_NODE_TIMER_DELAY_MS);
+ timer = setTimeout(() => {
+ if (cancelled) return;
+ armNextChunk();
+ }, delayMs);
+ timer.unref();
+ };
+
+ armNextChunk();
+ return () => {
+ cancelled = true;
+ if (timer) clearTimeout(timer);
+ };
+}
/** A host principal (`sub` starts with `host:`) is an AGENT — write invariants
* (mandatory If-Match on replace/delete) apply only to agents. */
@@ -75,6 +123,7 @@ function isAgentSub(sub: string): boolean {
const RESOURCE_RE = /^\/v1\/resources\/([^/]+)(?:\/(children|content))?$/;
const RESOLVE_RE = /^\/v1\/resolve$/;
const ACCESSIBLE_RE = /^\/v1\/accessible$/;
+const COPY_RE = /^\/v1\/copy$/;
const GFS_URI_RE = /^gfs:\/\/([^/]+)\/([^/?#]+)$/;
function bearerToken(req: IncomingMessage): string {
@@ -121,31 +170,50 @@ export class GfsServingHandler {
const resourceMatch = RESOURCE_RE.exec(url.pathname);
const resolveMatch = RESOLVE_RE.exec(url.pathname);
const accessibleMatch = ACCESSIBLE_RE.exec(url.pathname);
- if (!resourceMatch && !resolveMatch && !accessibleMatch) return false;
+ const copyMatch = COPY_RE.exec(url.pathname);
+ if (!resourceMatch && !resolveMatch && !accessibleMatch && !copyMatch) return false;
const method = req.method ?? "GET";
- const isWrite = method === "POST" || method === "PUT" || method === "DELETE";
- if (method !== "GET" && !(isWrite && this.deps.writeService && resourceMatch)) {
+ const isWrite = method === "POST" || method === "PUT" || method === "PATCH" || method === "DELETE";
+ const copyWrite = method === "POST" && copyMatch && this.deps.writeService && this.deps.copy;
+ const renameWrite = method === "PATCH" && resourceMatch?.[2] === undefined
+ && this.deps.writeService && this.deps.audit && this.deps.rename;
+ const resourceWrite = isWrite && this.deps.writeService && resourceMatch
+ && (method === "DELETE" || Boolean(this.deps.audit));
+ if ((copyMatch && !copyWrite) || (method === "PATCH" && !renameWrite) || (method !== "GET" && !resourceWrite && !copyWrite)) {
sendJson(res, 404, { ok: false, error: { code: "not_found", message: "not found" } });
return true;
}
const started = this.clock();
+ const copyAbort = copyWrite ? new AbortController() : undefined;
+ const cancelCopyTimer = copyAbort
+ ? armCopyAbortTimer(copyAbort, this.deps.copy!.timeoutMs)
+ : undefined;
try {
const claims = this.deps.verifyToken(bearerToken(req));
- const ctx = await this.authContext(claims, req);
+ const needsMutationRequestId = Boolean(copyMatch) || Boolean(renameWrite)
+ || Boolean(resourceMatch && ((method === "POST" && resourceMatch[2] === "children") || (method === "PUT" && resourceMatch[2] === "content")));
+ const requestId = needsMutationRequestId ? requireRequestId(req) : undefined;
+ const ctx = await this.authContext(claims, req, requestId);
+ copyAbort?.signal.throwIfAborted();
if (method === "GET") {
await this.handleRead(res, claims, ctx, url, resourceMatch, resolveMatch, accessibleMatch);
this.deps.metrics?.recordRead(this.clock() - started);
+ } else if (copyMatch) {
+ await this.serveCopy(req, res, claims, ctx, requestId!, started, copyAbort!.signal);
+ this.deps.metrics?.recordWrite(this.clock() - started);
} else {
- await this.handleWrite(req, res, claims, ctx, method, resourceMatch!);
+ await this.handleWrite(req, res, claims, ctx, method, resourceMatch!, requestId);
this.deps.metrics?.recordWrite(this.clock() - started);
}
} catch (err) {
const { status, body } = toResponse(err);
if (!res.headersSent) sendJson(res, status, body);
else res.end(); // a content stream already started; just terminate
+ } finally {
+ cancelCopyTimer?.();
}
return true;
}
@@ -193,14 +261,17 @@ export class GfsServingHandler {
claims: GfsVerifiedClaims,
ctx: AuthzContext,
method: string,
- resourceMatch: RegExpExecArray
+ resourceMatch: RegExpExecArray,
+ requestId?: string
): Promise<void> {
const rid = requireRid(resourceMatch[1]);
const sub = resourceMatch[2]; // undefined | "children" | "content"
if (method === "POST" && sub === "children") {
- await this.serveCreate(req, res, claims, ctx, rid);
+ await this.serveCreate(req, res, claims, ctx, rid, requestId!);
} else if (method === "PUT" && sub === "content") {
- await this.serveReplace(req, res, claims, ctx, rid);
+ await this.serveReplace(req, res, claims, ctx, rid, requestId!);
+ } else if (method === "PATCH" && sub === undefined) {
+ await this.serveRename(req, res, claims, ctx, rid, requestId!);
} else if (method === "DELETE" && sub === undefined) {
await this.serveDelete(req, res, claims, ctx, rid);
} else {
@@ -209,8 +280,8 @@ export class GfsServingHandler {
}
/** Resolve the principal to its subject set; a store failure is fail-closed 503. */
- private async authContext(claims: GfsVerifiedClaims, req: IncomingMessage): Promise<AuthzContext> {
- const requestId = headerValue(req, "x-request-id");
+ private async authContext(claims: GfsVerifiedClaims, req: IncomingMessage, admittedRequestId?: string): Promise<AuthzContext> {
+ const requestId = admittedRequestId ?? headerValue(req, "x-request-id");
try {
return await this.deps.resolveContext({ sub: claims.sub, drive: claims.drive }, requestId);
} catch (err) {
@@ -322,10 +393,15 @@ export class GfsServingHandler {
});
stream.pipe(res);
// Surface a mid-stream read error instead of silently truncating the body.
+ // pipe() does not propagate destination close back to the source, so a
+ // client abort must destroy the blob stream or its fd stays open.
await new Promise<void>((resolve, reject) => {
stream.on("end", resolve);
stream.on("error", reject);
- res.on("close", resolve);
+ res.on("close", () => {
+ stream.destroy();
+ resolve();
+ });
});
}
@@ -353,12 +429,30 @@ export class GfsServingHandler {
// ── Write routes ────────────────────────────────────────────────────────────
+ private async serveCopy(
+ req: IncomingMessage,
+ res: ServerResponse,
+ claims: GfsVerifiedClaims,
+ ctx: AuthzContext,
+ requestId: string,
+ admittedAtMs: number,
+ signal: AbortSignal
+ ): Promise<void> {
+ const body = await readJsonBody(req, { signal });
+ const data = await executeCopyRoute({
+ body, claims, context: ctx, requestId, admittedAtMs, signal, now: () => this.clock(),
+ deps: { ...this.deps.copy!, writes: this.deps.writeService! },
+ });
+ sendJson(res, 201, ok(data));
+ }
+
private async serveCreate(
req: IncomingMessage,
res: ServerResponse,
claims: GfsVerifiedClaims,
ctx: AuthzContext,
- parentId: string
+ parentId: string,
+ requestId: string
): Promise<void> {
const body = await readJsonBody(req);
const name = requireName(body, "name");
@@ -372,7 +466,10 @@ export class GfsServingHandler {
);
await this.authorizeChecks(claims, ctx, plan.checks);
- const created = await this.deps.writeService!.create({ drive: claims.drive, parentId, name, kind, content });
+ const created = await this.deps.writeService!.create({
+ drive: claims.drive, parentId, name, kind, content,
+ mutation: { subject: ctx.primarySubject, requestId, audit: this.deps.audit! },
+ });
sendJson(res, 201, ok(toView(created)));
}
@@ -381,7 +478,8 @@ export class GfsServingHandler {
res: ServerResponse,
claims: GfsVerifiedClaims,
ctx: AuthzContext,
- resourceId: string
+ resourceId: string,
+ requestId: string
): Promise<void> {
const body = await readJsonBody(req);
const content = readContentBuffer(body);
@@ -392,10 +490,27 @@ export class GfsServingHandler {
);
await this.authorizeChecks(claims, ctx, plan.checks);
- const updated = await this.deps.writeService!.replace({ drive: claims.drive, resourceId, ifMatch, content });
+ const updated = await this.deps.writeService!.replace({
+ drive: claims.drive, resourceId, ifMatch, content,
+ mutation: { subject: ctx.primarySubject, requestId, audit: this.deps.audit! },
+ });
sendJson(res, 200, ok(toView(updated)));
}
+ private async serveRename(
+ req: IncomingMessage, res: ServerResponse, claims: GfsVerifiedClaims,
+ ctx: AuthzContext, resourceId: string, requestId: string
+ ): Promise<void> {
+ const body = await readJsonBody(req);
+ const data = await executeRenameRoute({
+ body, claims, context: ctx, resourceId, requestId, audit: this.deps.audit!,
+ authorizeWrite: () => this.authorizeOp(claims, ctx, resourceId, "write"),
+ writes: this.deps.writeService!,
+ limits: this.deps.rename!,
+ });
+ sendJson(res, 200, ok(data));
+ }
+
private async serveDelete(
req: IncomingMessage,
res: ServerResponse,
@@ -428,6 +543,13 @@ export class GfsServingHandler {
}
}
+function requireRequestId(req: IncomingMessage): string {
+ const supplied = headerValue(req, "x-request-id");
+ if (supplied === undefined) return randomUUID();
+ const normalized = requireRid(supplied);
+ return [normalized.slice(0, 8), normalized.slice(8, 12), normalized.slice(12, 16), normalized.slice(16, 20), normalized.slice(20)].join("-");
+}
+
function headerValue(req: IncomingMessage, name: string): string | undefined {
const v = req.headers[name];
return typeof v === "string" ? v : undefined;
@@ -479,9 +601,9 @@ function decodeBase64Content(encoded: string): Buffer {
function requireName(body: Record<string, unknown>, key: string): string {
try {
- return normalizeName(requireString(body, key));
+ return normalizeResourceName(requireString(body, key));
} catch (err) {
- if (err instanceof MoveError) throw new GfsError("path_invalid", err.message);
+ if (err instanceof ResourceNameError) throw new GfsError("path_invalid", err.message);
throw err;
}
}
@@ -502,18 +624,31 @@ function optionalNumber(body: Record<string, unknown>, key: string): number | un
*/
async function readJsonBody(
req: IncomingMessage,
- opts: { allowEmpty?: boolean } = {}
+ opts: { allowEmpty?: boolean; signal?: AbortSignal } = {}
): Promise<Record<string, unknown>> {
const chunks: Buffer[] = [];
let total = 0;
- for await (const chunk of req) {
- const buf = chunk as Buffer;
- total += buf.length;
- if (total > MAX_WRITE_BODY_BYTES) {
- throw new GfsError("payload_too_large", `request body exceeds ${MAX_WRITE_BODY_BYTES} bytes`);
+ const abort = (): void => {
+ req.destroy(opts.signal?.reason instanceof Error
+ ? opts.signal.reason
+ : new GfsError("precondition_failed", "synchronous copy deadline exceeded"));
+ };
+ opts.signal?.throwIfAborted();
+ opts.signal?.addEventListener("abort", abort, { once: true });
+ try {
+ for await (const chunk of req) {
+ opts.signal?.throwIfAborted();
+ const buf = chunk as Buffer;
+ total += buf.length;
+ if (total > MAX_WRITE_BODY_BYTES) {
+ throw new GfsError("payload_too_large", `request body exceeds ${MAX_WRITE_BODY_BYTES} bytes`);
+ }
+ chunks.push(buf);
}
- chunks.push(buf);
+ } finally {
+ opts.signal?.removeEventListener("abort", abort);
}
+ opts.signal?.throwIfAborted();
const raw = Buffer.concat(chunks).toString("utf8").trim();
if (raw === "") {
if (opts.allowEmpty) return {};
diff --git a/gfs-controller/src/authz/audit.ts b/gfs-controller/src/authz/audit.ts
new file mode 100644
index 000000000..3681cfcce
--- /dev/null
+++ b/gfs-controller/src/authz/audit.ts
@@ -0,0 +1,120 @@
+import { createHash } from "node:crypto";
+import {
+ withDeadlineTransaction,
+ type DeadlineBudget,
+ type DeadlinePool,
+} from "../db/deadlineQuery";
+
+/** Minimal query surface — a pg Pool satisfies this; tests inject a fake. */
+export interface Queryable {
+ query(text: string, values?: unknown[]): Promise<{ rows: Record<string, unknown>[] }>;
+}
+
+export type PersistedAuthorizationSource =
+ | "direct_grant"
+ | "inherited_grant"
+ | "direct_share"
+ | "inherited_share"
+ | "operator";
+
+export type AuthorizationEvidence =
+ | {
+ authorizationSource: "cache";
+ cachedAuthorizationSource: PersistedAuthorizationSource;
+ }
+ | {
+ authorizationSource: PersistedAuthorizationSource | null;
+ cachedAuthorizationSource: null;
+ };
+
+interface AuditEventBase {
+ subject: string;
+ op: string;
+ resourceId: string;
+ drive: string;
+ outcome: "allow" | "deny" | "error";
+ reason?: string;
+ requestId?: string;
+}
+
+export type AuditEvent =
+ | (AuditEventBase &
+ AuthorizationEvidence & {
+ recordType: "authorization_decision";
+ matchedSubject: string | null;
+ mutationOutcome: null;
+ })
+ | (AuditEventBase &
+ AuthorizationEvidence & {
+ recordType: "mutation_outcome";
+ matchedSubject: string | null;
+ mutationOutcome: "succeeded" | "failed";
+ })
+ | (AuditEventBase & {
+ recordType: "legacy";
+ matchedSubject: null;
+ authorizationSource: null;
+ cachedAuthorizationSource: null;
+ mutationOutcome: null;
+ });
+
+export interface AuditSink {
+ record(event: AuditEvent, queryable?: Queryable, budget?: DeadlineBudget): Promise<void>;
+}
+
+/** PostgreSQL-backed, INSERT-only sink for typed GFS audit evidence. */
+export class DbAuditSink implements AuditSink {
+ constructor(private readonly db: Queryable & DeadlinePool) {}
+
+ async record(event: AuditEvent, queryable?: Queryable, budget?: DeadlineBudget): Promise<void> {
+ const gfsUri = `gfs://${event.drive}/${event.resourceId}`;
+ const rowHash = createHash("sha256")
+ .update(
+ JSON.stringify([
+ event.subject,
+ event.op,
+ gfsUri,
+ event.outcome,
+ event.reason ?? null,
+ event.requestId ?? null,
+ event.recordType,
+ event.matchedSubject,
+ event.authorizationSource,
+ event.cachedAuthorizationSource,
+ event.mutationOutcome,
+ ])
+ )
+ .digest("hex");
+
+ const append = (target: Queryable) => target.query(
+ `INSERT INTO gfs_audit
+ (subject, op, gfs_uri, outcome, request_id, row_hash, record_type,
+ matched_subject, authorization_source, cached_authorization_source,
+ mutation_outcome)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,
+ [
+ event.subject,
+ event.op,
+ gfsUri,
+ event.outcome,
+ event.requestId ?? null,
+ rowHash,
+ event.recordType,
+ event.matchedSubject,
+ event.authorizationSource,
+ event.cachedAuthorizationSource,
+ event.mutationOutcome,
+ ]
+ );
+
+ if (queryable) {
+ await append(queryable);
+ return;
+ }
+ if (budget) {
+ await withDeadlineTransaction(this.db, budget, false, append);
+ return;
+ }
+ await append(this.db);
+ }
+}
diff --git a/gfs-controller/src/authz/cache.test.ts b/gfs-controller/src/authz/cache.test.ts
index e5c2315e7..95f1e195a 100644
--- a/gfs-controller/src/authz/cache.test.ts
+++ b/gfs-controller/src/authz/cache.test.ts
@@ -15,49 +15,89 @@ import {
*/
const KEY = { subjectsKey: "user:u1", resourceId: "r1", op: "read" };
+const ALLOW_DECISION = {
+ allowed: true,
+ via: "grant" as const,
+ matchedSubject: "user:u1",
+ authorizationSource: "direct_grant" as const,
+};
+const DENY_DECISION = {
+ allowed: false,
+ via: null,
+ matchedSubject: null,
+ authorizationSource: null,
+};
describe("DecisionCache", () => {
it("returns a cached decision within the TTL and misses after it", () => {
let t = 1000;
const cache = new DecisionCache({ ttlMs: 100, now: () => t });
- cache.set(KEY, true);
- expect(cache.get(KEY)).toBe(true);
+ cache.set(KEY, ALLOW_DECISION);
+ expect(cache.get(KEY)).toEqual(ALLOW_DECISION);
t += 99;
- expect(cache.get(KEY)).toBe(true);
+ expect(cache.get(KEY)).toEqual(ALLOW_DECISION);
t += 1; // now at +100 = expiry boundary
expect(cache.get(KEY)).toBeUndefined();
});
it("flushAll drops entries so the next op re-checks (immediate revocation)", () => {
const cache = new DecisionCache({ ttlMs: 10_000 });
- cache.set(KEY, true);
- expect(cache.get(KEY)).toBe(true);
+ cache.set(KEY, ALLOW_DECISION);
+ expect(cache.get(KEY)).toEqual(ALLOW_DECISION);
cache.flushAll();
expect(cache.get(KEY)).toBeUndefined();
});
+ it("bumps generation on every flushAll and holds it stable otherwise", () => {
+ let t = 1000;
+ const cache = new DecisionCache({ ttlMs: 100, now: () => t });
+ expect(cache.generation).toBe(0);
+ // Ordinary reads/writes/expiry never move the revocation counter.
+ cache.set(KEY, ALLOW_DECISION);
+ expect(cache.get(KEY)).toEqual(ALLOW_DECISION);
+ t += 1000; // force expiry on the next get
+ expect(cache.get(KEY)).toBeUndefined();
+ expect(cache.generation).toBe(0);
+ // Each revocation NOTIFY (flushAll) advances it by exactly one.
+ cache.flushAll();
+ expect(cache.generation).toBe(1);
+ cache.flushAll();
+ expect(cache.generation).toBe(2);
+ });
+
+ it("keeps attribution isolated from caller mutation", () => {
+ const cache = new DecisionCache({ ttlMs: 10_000 });
+ cache.set(KEY, ALLOW_DECISION);
+ const first = cache.get(KEY)!;
+ first.matchedSubject = "user:changed";
+ expect(cache.get(KEY)).toMatchObject({
+ matchedSubject: "user:u1",
+ authorizationSource: "direct_grant",
+ });
+ });
+
it("serves and stores NOTHING while bypassed (fail-closed)", () => {
const cache = new DecisionCache({ ttlMs: 10_000 });
- cache.set(KEY, true);
+ cache.set(KEY, ALLOW_DECISION);
cache.setBypassed(true);
expect(cache.isBypassed).toBe(true);
expect(cache.get(KEY)).toBeUndefined(); // existing entry not served
- cache.set(KEY, true); // ignored while bypassed
+ cache.set(KEY, ALLOW_DECISION); // ignored while bypassed
expect(cache.size).toBe(0);
cache.setBypassed(false);
expect(cache.get(KEY)).toBeUndefined(); // was never stored
- cache.set(KEY, false);
- expect(cache.get(KEY)).toBe(false); // caching works again
+ cache.set(KEY, DENY_DECISION);
+ expect(cache.get(KEY)).toEqual(DENY_DECISION); // caching works again
});
it("evicts the oldest entry past maxEntries", () => {
const cache = new DecisionCache({ ttlMs: 10_000, maxEntries: 2 });
- cache.set({ ...KEY, resourceId: "a" }, true);
- cache.set({ ...KEY, resourceId: "b" }, true);
- cache.set({ ...KEY, resourceId: "c" }, true); // evicts "a"
+ cache.set({ ...KEY, resourceId: "a" }, ALLOW_DECISION);
+ cache.set({ ...KEY, resourceId: "b" }, ALLOW_DECISION);
+ cache.set({ ...KEY, resourceId: "c" }, ALLOW_DECISION); // evicts "a"
expect(cache.size).toBe(2);
expect(cache.get({ ...KEY, resourceId: "a" })).toBeUndefined();
- expect(cache.get({ ...KEY, resourceId: "c" })).toBe(true);
+ expect(cache.get({ ...KEY, resourceId: "c" })).toEqual(ALLOW_DECISION);
});
it("rejects a non-positive ttl", () => {
diff --git a/gfs-controller/src/authz/cache.ts b/gfs-controller/src/authz/cache.ts
index 13912f035..d715e5ae3 100644
Binary files a/gfs-controller/src/authz/cache.ts and b/gfs-controller/src/authz/cache.ts differ
diff --git a/gfs-controller/src/authz/dbAuditSink.test.ts b/gfs-controller/src/authz/dbAuditSink.test.ts
new file mode 100644
index 000000000..238dd6159
--- /dev/null
+++ b/gfs-controller/src/authz/dbAuditSink.test.ts
@@ -0,0 +1,181 @@
+import { describe, expect, it, vi } from "vitest";
+import { AuditEvent, DbAuditSink, Queryable } from "./audit";
+
+class AuditDb implements Queryable {
+ text = "";
+ values: unknown[] = [];
+
+ async query(text: string, values?: unknown[]): Promise<{ rows: Record<string, unknown>[] }> {
+ this.text = text;
+ this.values = values ?? [];
+ return { rows: [] };
+ }
+}
+
+class AuditPool extends AuditDb {
+ queries: string[] = [];
+ releases = 0;
+ connectCalls = 0;
+
+ async connect() {
+ this.connectCalls += 1;
+ return {
+ query: async (text: string, values?: unknown[]) => {
+ this.queries.push(text);
+ return this.query(text, values);
+ },
+ release: () => { this.releases += 1; },
+ };
+ }
+}
+
+const directDecision: AuditEvent = {
+ subject: "agent:reader-1",
+ op: "read",
+ resourceId: "resource-id",
+ drive: "main",
+ outcome: "allow",
+ requestId: "req-7",
+ recordType: "authorization_decision",
+ matchedSubject: "agent:reader-1",
+ authorizationSource: "direct_grant",
+ cachedAuthorizationSource: null,
+ mutationOutcome: null,
+};
+
+describe("DbAuditSink", () => {
+ it("persists typed authorization attribution in the hashed INSERT-only row", async () => {
+ const db = new AuditDb();
+ await new DbAuditSink(db).record(directDecision);
+
+ expect(db.text).toContain(
+ "record_type,\n matched_subject, authorization_source, cached_authorization_source"
+ );
+ expect(db.values).toEqual([
+ "agent:reader-1",
+ "read",
+ "gfs://main/resource-id",
+ "allow",
+ "req-7",
+ expect.stringMatching(/^[0-9a-f]{64}$/),
+ "authorization_decision",
+ "agent:reader-1",
+ "direct_grant",
+ null,
+ null,
+ ]);
+ expect(db.text).not.toMatch(/\b(path|name|blob_key)\b/);
+ expect(String(db.values[5])).toMatch(/^[0-9a-f]{64}$/);
+ });
+
+ it("persists cache attribution and includes it in the deterministic hash", async () => {
+ const first = new AuditDb();
+ const repeated = new AuditDb();
+ const direct = new AuditDb();
+ const cachedDecision: AuditEvent = {
+ ...directDecision,
+ authorizationSource: "cache",
+ cachedAuthorizationSource: "direct_grant",
+ };
+
+ await new DbAuditSink(first).record(cachedDecision);
+ await new DbAuditSink(repeated).record(cachedDecision);
+ await new DbAuditSink(direct).record(directDecision);
+
+ expect(first.values.slice(6, 11)).toEqual([
+ "authorization_decision",
+ "agent:reader-1",
+ "cache",
+ "direct_grant",
+ null,
+ ]);
+ expect(first.values[5]).toBe(repeated.values[5]);
+ expect(first.values[5]).not.toBe(direct.values[5]);
+ });
+
+ it("uses a supplied transaction client instead of the default pool", async () => {
+ const pool = new AuditDb();
+ const transaction = new AuditDb();
+
+ await new DbAuditSink(pool).record(directDecision, transaction);
+
+ expect(pool.text).toBe("");
+ expect(pool.values).toEqual([]);
+ expect(transaction.text).toContain("INSERT INTO gfs_audit");
+ expect(transaction.values.slice(0, 4)).toEqual([
+ "agent:reader-1",
+ "read",
+ "gfs://main/resource-id",
+ "allow",
+ ]);
+ });
+
+ it("supports a separate typed mutation outcome record", async () => {
+ const db = new AuditDb();
+ await new DbAuditSink(db).record({
+ ...directDecision,
+ op: "write",
+ outcome: "error",
+ recordType: "mutation_outcome",
+ mutationOutcome: "failed",
+ });
+
+ expect(db.values.slice(6, 11)).toEqual([
+ "mutation_outcome",
+ "agent:reader-1",
+ "direct_grant",
+ null,
+ "failed",
+ ]);
+ });
+
+ it("uses a checked-out client and statement timeout for a bounded standalone audit", async () => {
+ const pool = new AuditPool();
+
+ await new DbAuditSink(pool).record(directDecision, undefined, {
+ deadlineAtMs: Date.now() + 1_000,
+ });
+
+ expect(pool.connectCalls).toBe(1);
+ expect(pool.queries).toEqual([
+ "BEGIN",
+ expect.stringContaining("set_config('statement_timeout'"),
+ expect.stringContaining("INSERT INTO gfs_audit"),
+ "COMMIT",
+ ]);
+ expect(pool.releases).toBe(1);
+ });
+
+ it("releases a late audit client without issuing SQL after its acquisition deadline", async () => {
+ vi.useFakeTimers();
+ try {
+ let resolveClient!: (client: {
+ query(text: string, values?: unknown[]): Promise<{ rows: Record<string, unknown>[] }>;
+ release(): void;
+ }) => void;
+ const queries: string[] = [];
+ let releases = 0;
+ const pool = Object.assign(new AuditDb(), {
+ connect: () => new Promise<Parameters<typeof resolveClient>[0]>(resolve => { resolveClient = resolve; }),
+ });
+ const sink = new DbAuditSink(pool);
+ const recording = sink.record(directDecision, undefined, {
+ deadlineAtMs: Date.now() + 10,
+ });
+ const rejected = expect(recording).rejects.toMatchObject({ code: "precondition_failed" });
+
+ await vi.advanceTimersByTimeAsync(10);
+ await rejected;
+ resolveClient({
+ query: async text => { queries.push(text); return { rows: [] }; },
+ release: () => { releases += 1; },
+ });
+ await Promise.resolve();
+
+ expect(queries).toEqual([]);
+ expect(releases).toBe(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/gfs-controller/src/authz/permissionClient.auditEvidence.test.ts b/gfs-controller/src/authz/permissionClient.auditEvidence.test.ts
new file mode 100644
index 000000000..095fb10b1
--- /dev/null
+++ b/gfs-controller/src/authz/permissionClient.auditEvidence.test.ts
@@ -0,0 +1,100 @@
+import { describe, expect, it } from "vitest";
+import { DecisionCache } from "./cache";
+import {
+ AuditEvent,
+ AuditSink,
+ AuthzContext,
+ PermissionClient,
+ Queryable,
+} from "./permissionClient";
+
+class EvidenceDb implements Queryable {
+ constructor(private readonly allowed: boolean) {}
+
+ async query(text: string, values?: unknown[]): Promise<{ rows: Record<string, unknown>[] }> {
+ if (text.includes("WITH RECURSIVE")) {
+ const resourceId = String((values?.[1] as string[])[0]);
+ return {
+ rows: [{ requested_resource_id: resourceId, resource_id: resourceId }],
+ };
+ }
+ if (text.includes("FROM gfs_grants")) {
+ return {
+ rows: this.allowed
+ ? [{
+ resource_id: "R",
+ subject_type: "user",
+ subject_id: "user-1",
+ permissions: ["read"],
+ inherit: false,
+ }]
+ : [],
+ };
+ }
+ return { rows: [] };
+ }
+}
+
+class EvidenceSink implements AuditSink {
+ events: AuditEvent[] = [];
+
+ async record(event: AuditEvent, _queryable?: Queryable): Promise<void> {
+ this.events.push(event);
+ }
+}
+
+const context: AuthzContext = {
+ drive: "main",
+ subjects: ["user:user-1"],
+ isOperator: false,
+ primarySubject: "agent:reader-1",
+ requestId: "req-cache",
+};
+
+async function recordCacheHit(allowed: boolean): Promise<AuditEvent> {
+ const sink = new EvidenceSink();
+ const client = new PermissionClient(
+ new EvidenceDb(allowed),
+ sink,
+ new DecisionCache({ ttlMs: 30_000 })
+ );
+ await client.authorize(context, "R", "read");
+ await client.authorize(context, "R", "read");
+ return sink.events[1];
+}
+
+describe("PermissionClient typed audit evidence", () => {
+ it("records cache as the source while retaining an allowed decision's underlying source", async () => {
+ await expect(recordCacheHit(true)).resolves.toMatchObject({
+ subject: "agent:reader-1",
+ op: "read",
+ resourceId: "R",
+ outcome: "allow",
+ requestId: "req-cache",
+ recordType: "authorization_decision",
+ matchedSubject: "user:user-1",
+ authorizationSource: "cache",
+ cachedAuthorizationSource: "direct_grant",
+ mutationOutcome: null,
+ });
+ });
+
+ it("keeps cached-deny attribution null without leaking resource metadata", async () => {
+ const event = await recordCacheHit(false);
+ expect(event).toMatchObject({
+ subject: "agent:reader-1",
+ op: "read",
+ resourceId: "R",
+ outcome: "deny",
+ requestId: "req-cache",
+ recordType: "authorization_decision",
+ matchedSubject: null,
+ authorizationSource: null,
+ cachedAuthorizationSource: null,
+ mutationOutcome: null,
+ });
+ expect(event).not.toHaveProperty("path");
+ expect(event).not.toHaveProperty("name");
+ expect(event).not.toHaveProperty("blobKey");
+ });
+});
diff --git a/gfs-controller/src/authz/permissionClient.batch.test.ts b/gfs-controller/src/authz/permissionClient.batch.test.ts
new file mode 100644
index 000000000..82ff000fa
--- /dev/null
+++ b/gfs-controller/src/authz/permissionClient.batch.test.ts
@@ -0,0 +1,233 @@
+import { describe, expect, it } from "vitest";
+import { DecisionCache } from "./cache";
+import { AuditEvent, AuditSink, AuthzContext, PermissionClient, Queryable } from "./permissionClient";
+
+class BatchDb implements Queryable {
+ ancestorChains: Record<string, string[]> = {};
+ grants: Record<string, unknown>[] = [];
+ shares: Record<string, unknown>[] = [];
+ requestedRowIds: Record<string, string> = {};
+ counts = { ancestors: 0, grants: 0, shares: 0 };
+ calls: Array<{ text: string; values: unknown[] }> = [];
+ failAncestors = false;
+
+ async query(text: string, values?: unknown[]): Promise<{ rows: Record<string, unknown>[] }> {
+ this.calls.push({ text, values: values ?? [] });
+ if (text.includes("WITH RECURSIVE")) {
+ this.counts.ancestors++;
+ if (this.failAncestors) throw new Error("store unavailable");
+ const requested = (values?.[1] as string[]) ?? [];
+ return { rows: requested.flatMap((resourceId) =>
+ (this.ancestorChains[resourceId] ?? []).map((ancestorId) => ({
+ requested_resource_id: this.requestedRowIds[resourceId] ?? resourceId,
+ resource_id: ancestorId,
+ }))
+ ) };
+ }
+ if (text.includes("FROM gfs_grants")) {
+ this.counts.grants++;
+ return { rows: this.grants };
+ }
+ if (text.includes("FROM gfs_shares")) {
+ this.counts.shares++;
+ return { rows: this.shares };
+ }
+ return { rows: [] };
+ }
+
+ async connect() {
+ return {
+ query: async (text: string, values: unknown[] = []) => {
+ if (text === "BEGIN READ ONLY" || text === "COMMIT" || text === "ROLLBACK" || text.includes("set_config('statement_timeout'")) {
+ this.calls.push({ text, values });
+ return { rows: [] };
+ }
+ return this.query(text, values);
+ },
+ release: () => undefined,
+ };
+ }
+}
+
+class BatchAudit implements AuditSink {
+ events: AuditEvent[] = [];
+ async record(event: AuditEvent, _queryable?: Queryable): Promise<void> {
+ this.events.push(event);
+ }
+}
+
+const context: AuthzContext = {
+ drive: "main",
+ subjects: ["user:u1"],
+ isOperator: false,
+ primarySubject: "u1",
+ requestId: "req-batch",
+};
+
+describe("PermissionClient.authorizeMany", () => {
+ it("returns immediately for an empty batch", async () => {
+ const db = new BatchDb();
+ await expect(new PermissionClient(db, new BatchAudit()).authorizeMany(context, [])).resolves.toEqual([]);
+ expect(db.counts).toEqual({ ancestors: 0, grants: 0, shares: 0 });
+ });
+
+ it("uses a bounded three-query permission snapshot for any batch size", async () => {
+ const db = new BatchDb();
+ db.ancestorChains = {
+ f1: ["f1", "folder", "root"],
+ f2: ["f2", "folder", "root"],
+ f3: ["f3", "folder", "root"],
+ };
+ db.grants = [{
+ resource_id: "folder",
+ subject_type: "user",
+ subject_id: "u1",
+ permissions: ["read"],
+ inherit: true,
+ }];
+ const audit = new BatchAudit();
+ const decisions = await new PermissionClient(db, audit).authorizeMany(context, [
+ { resourceId: "f1", op: "read" },
+ { resourceId: "f2", op: "read" },
+ { resourceId: "f3", op: "write" },
+ ]);
+
+ expect(db.counts).toEqual({ ancestors: 1, grants: 1, shares: 1 });
+ expect(decisions.map((decision) => decision.allowed)).toEqual([true, true, false]);
+ expect(decisions[0]).toMatchObject({
+ matchedSubject: "user:u1",
+ authorizationSource: "inherited_grant",
+ });
+ expect(audit.events.map((event) => event.requestId)).toEqual([
+ "req-batch",
+ "req-batch",
+ "req-batch",
+ ]);
+ });
+
+ it("applies the remaining Copy deadline to every permission-store query", async () => {
+ const db = new BatchDb();
+ db.ancestorChains = { file: ["file"] };
+ await new PermissionClient(db, new BatchAudit()).authorizeMany(context, [
+ { resourceId: "file", op: "read" },
+ ], { deadlineAtMs: 10_000, now: () => 7_500 });
+ expect(db.calls.map(call => call.text)).toEqual([
+ "BEGIN READ ONLY", "SELECT set_config('statement_timeout', $1, true)",
+ expect.stringContaining("WITH RECURSIVE requested"), expect.stringContaining("FROM gfs_grants"),
+ expect.stringContaining("FROM gfs_shares"), "COMMIT",
+ "BEGIN", "SELECT set_config('statement_timeout', $1, true)", "COMMIT",
+ ]);
+ expect(db.calls[1].values).toEqual(["2500"]);
+ expect(db.calls[7].values).toEqual(["2500"]);
+ });
+
+ it("does not query after an exhausted Copy authorization budget", async () => {
+ const db = new BatchDb();
+ await expect(new PermissionClient(db, new BatchAudit()).authorizeMany(context, [
+ { resourceId: "file", op: "read" },
+ ], { deadlineAtMs: 100, now: () => 100 })).rejects.toMatchObject({ code: "precondition_failed" });
+ expect(db.calls).toEqual([]);
+ });
+
+ it("matches compact request RIDs to PostgreSQL UUID rows and direct grants", async () => {
+ const rid = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
+ const uuid = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
+ const db = new BatchDb();
+ db.ancestorChains = { [rid]: [uuid] };
+ db.requestedRowIds = { [rid]: uuid };
+ db.grants = [{
+ resource_id: uuid,
+ subject_type: "user",
+ subject_id: "u1",
+ permissions: ["read"],
+ inherit: false,
+ }];
+
+ const [decision] = await new PermissionClient(db, new BatchAudit()).authorizeMany(context, [
+ { resourceId: rid, op: "read" },
+ ]);
+ expect(decision).toMatchObject({
+ allowed: true,
+ matchedSubject: "user:u1",
+ authorizationSource: "direct_grant",
+ });
+ expect(db.counts).toEqual({ ancestors: 1, grants: 1, shares: 1 });
+ });
+
+ it("audits every node even when an intermediate child denies", async () => {
+ const db = new BatchDb();
+ db.ancestorChains = {
+ parent: ["parent"],
+ denied: ["denied", "parent"],
+ allowed: ["allowed", "parent"],
+ };
+ db.grants = [
+ { resource_id: "parent", subject_type: "user", subject_id: "u1", permissions: ["read"], inherit: false },
+ { resource_id: "allowed", subject_type: "user", subject_id: "u1", permissions: ["read"], inherit: false },
+ ];
+ const audit = new BatchAudit();
+ const decisions = await new PermissionClient(db, audit).authorizeMany(context, [
+ { resourceId: "parent", op: "read" },
+ { resourceId: "denied", op: "read" },
+ { resourceId: "allowed", op: "read" },
+ ]);
+
+ expect(decisions.map((decision) => decision.allowed)).toEqual([true, false, true]);
+ expect(decisions[1]).toEqual({
+ allowed: false,
+ via: null,
+ matchedSubject: null,
+ authorizationSource: null,
+ });
+ for (const decision of decisions) {
+ expect(Object.keys(decision)).not.toContain("path");
+ expect(Object.keys(decision)).not.toContain("name");
+ }
+ expect(audit.events.map((event) => event.resourceId)).toEqual(["parent", "denied", "allowed"]);
+ });
+
+ it("retains underlying attribution on cache hits and flush forces fresh reads", async () => {
+ const db = new BatchDb();
+ db.ancestorChains = { file: ["file", "root"] };
+ db.shares = [{
+ resource_id: "file",
+ subject_type: "user",
+ subject_id: "u1",
+ permissions: ["read"],
+ include_descendants: false,
+ }];
+ const cache = new DecisionCache({ ttlMs: 30_000 });
+ const client = new PermissionClient(db, new BatchAudit(), cache);
+ const request = [{ resourceId: "file", op: "read" as const }];
+
+ const first = await client.authorizeMany(context, request);
+ const second = await client.authorizeMany(context, request);
+ expect(first[0]).toMatchObject({ via: "share", authorizationSource: "direct_share" });
+ expect(second[0]).toMatchObject({
+ via: "cache",
+ matchedSubject: "user:u1",
+ authorizationSource: "direct_share",
+ });
+ expect(db.counts.ancestors).toBe(1);
+
+ cache.flushAll();
+ await client.authorizeMany(context, request);
+ expect(db.counts.ancestors).toBe(2);
+ });
+
+ it("audits every requested node as an error when the batch snapshot fails", async () => {
+ const db = new BatchDb();
+ db.failAncestors = true;
+ const audit = new BatchAudit();
+ const operation = new PermissionClient(db, audit).authorizeMany(context, [
+ { resourceId: "one", op: "read" },
+ { resourceId: "two", op: "read" },
+ ]);
+
+ await expect(operation).rejects.toMatchObject({ code: "not_mounted" });
+ expect(audit.events.map((event) => [event.resourceId, event.outcome, event.requestId])).toEqual([
+ ["one", "error", "req-batch"],
+ ["two", "error", "req-batch"],
+ ]);
+ });
+});
diff --git a/gfs-controller/src/authz/permissionClient.test.ts b/gfs-controller/src/authz/permissionClient.test.ts
index 9cc0616b0..23995be6a 100644
--- a/gfs-controller/src/authz/permissionClient.test.ts
+++ b/gfs-controller/src/authz/permissionClient.test.ts
@@ -25,6 +25,8 @@ describe("resolveDecision (deny-by-default, spec-faithful)", () => {
expect(resolveDecision({ ...base, isOperator: true })).toEqual({
allowed: true,
via: "operator",
+ matchedSubject: null,
+ authorizationSource: "operator",
});
});
@@ -37,7 +39,7 @@ describe("resolveDecision (deny-by-default, spec-faithful)", () => {
...base,
grants: [{ subjectKey: "user:user-1", resourceId: "R", permissions: ["read"], inherit: false }],
});
- expect(d).toEqual({ allowed: true, via: "grant" });
+ expect(d).toMatchObject({ allowed: true, via: "grant", authorizationSource: "direct_grant" });
});
it("inherits an ancestor grant ONLY when inherit = true (§Inheritance)", () => {
@@ -45,7 +47,11 @@ describe("resolveDecision (deny-by-default, spec-faithful)", () => {
...base,
grants: [{ subjectKey: "user:user-1", resourceId: "ROOT", permissions: ["read"], inherit: true }],
});
- expect(inheriting.allowed).toBe(true);
+ expect(inheriting).toMatchObject({
+ allowed: true,
+ matchedSubject: "user:user-1",
+ authorizationSource: "inherited_grant",
+ });
const notInheriting = resolveDecision({
...base,
@@ -54,6 +60,21 @@ describe("resolveDecision (deny-by-default, spec-faithful)", () => {
expect(notInheriting.allowed).toBe(false);
});
+ it("attributes a direct grant before an inherited grant regardless of row order", () => {
+ const decision = resolveDecision({
+ ...base,
+ subjects: new Set(["user:user-1", "team:team-1"]),
+ grants: [
+ { subjectKey: "team:team-1", resourceId: "ROOT", permissions: ["read"], inherit: true },
+ { subjectKey: "user:user-1", resourceId: "R", permissions: ["read"], inherit: false },
+ ],
+ });
+ expect(decision).toMatchObject({
+ matchedSubject: "user:user-1",
+ authorizationSource: "direct_grant",
+ });
+ });
+
it("denies a grant that lacks the op bit or belongs to a different subject", () => {
expect(
resolveDecision({
@@ -84,14 +105,17 @@ describe("resolveDecision (deny-by-default, spec-faithful)", () => {
...base,
shares: [{ subjectKey: "user:user-1", resourceId: "R", permissions: ["read"], includeDescendants: false }],
})
- ).toEqual({ allowed: true, via: "share" });
+ ).toMatchObject({ allowed: true, via: "share", authorizationSource: "direct_share" });
- expect(
- resolveDecision({
+ const inheritedShare = resolveDecision({
...base,
shares: [{ subjectKey: "user:user-1", resourceId: "ROOT", permissions: ["read"], includeDescendants: true }],
- }).allowed
- ).toBe(true);
+ });
+ expect(inheritedShare).toMatchObject({
+ allowed: true,
+ matchedSubject: "user:user-1",
+ authorizationSource: "inherited_share",
+ });
expect(
resolveDecision({
@@ -119,7 +143,15 @@ class FakeDb implements Queryable {
if (text.includes("WITH RECURSIVE")) {
this.cteQueries++;
if (this.failOn === "ancestors") throw new Error("permission store down");
- return { rows: this.ancestors.map((id) => ({ resource_id: id })) };
+ const requested = (values?.[1] as string[]) ?? [];
+ return {
+ rows: requested.flatMap((resourceId) =>
+ this.ancestors.map((id) => ({
+ requested_resource_id: resourceId,
+ resource_id: id,
+ }))
+ ),
+ };
}
if (text.includes("FROM gfs_grants")) {
if (this.failOn === "grants") throw new Error("permission store down");
@@ -135,7 +167,7 @@ class FakeDb implements Queryable {
class RecordingSink implements AuditSink {
events: AuditEvent[] = [];
- async record(event: AuditEvent): Promise<void> {
+ async record(event: AuditEvent, _queryable?: Queryable): Promise<void> {
this.events.push(event);
}
}
@@ -160,7 +192,7 @@ describe("PermissionClient (fail-closed, deny-by-default, audited)", () => {
const db = new FakeDb();
const sink = new RecordingSink();
const decision = await new PermissionClient(db, sink).authorize(operatorCtx, "R", "read");
- expect(decision).toEqual({ allowed: true, via: "operator" });
+ expect(decision).toMatchObject({ allowed: true, via: "operator", authorizationSource: "operator" });
expect(db.cteQueries).toBe(0); // intrinsic — no ancestor lookup needed
expect(sink.events[0]).toMatchObject({ outcome: "allow", reason: "operator", subject: "admin-9" });
});
@@ -237,6 +269,7 @@ describe("PermissionClient + DecisionCache (cache→store, fail-closed)", () =>
expect(first.allowed).toBe(true);
expect(second.allowed).toBe(true);
+ expect(second).toMatchObject({ via: "cache", authorizationSource: "direct_grant" });
expect(db.cteQueries).toBe(1); // store hit once; the 2nd op was a cache hit
expect(sink.events).toHaveLength(2); // BOTH ops audited — cache never skips audit
expect(sink.events[1]).toMatchObject({ outcome: "allow", reason: "cache" });
@@ -305,24 +338,3 @@ describe("PermissionClient + DecisionCache (cache→store, fail-closed)", () =>
expect(db.cteQueries).toBe(0);
});
});
-
-describe("DbAuditSink", () => {
- it("appends an INSERT-only row with a content hash", async () => {
- const db = new FakeDb();
- await new DbAuditSink(db).record({
- subject: "user-1",
- op: "read",
- resourceId: "R",
- drive: "main",
- outcome: "allow",
- requestId: "req-7",
- });
- expect(db.audits).toHaveLength(1);
- const values = db.audits[0];
- expect(values[0]).toBe("user-1");
- expect(values[1]).toBe("read");
- expect(values[2]).toBe("gfs://main/R");
- expect(values[3]).toBe("allow");
- expect(String(values[5])).toMatch(/^[0-9a-f]{64}$/);
- });
-});
diff --git a/gfs-controller/src/authz/permissionClient.ts b/gfs-controller/src/authz/permissionClient.ts
index 729cdce0f..484470962 100644
--- a/gfs-controller/src/authz/permissionClient.ts
+++ b/gfs-controller/src/authz/permissionClient.ts
@@ -1,6 +1,11 @@
-import { createHash } from "node:crypto";
import { GfsError } from "../api/errors";
-import { DecisionCache } from "./cache";
+import type {
+ AuditSink,
+ AuthorizationEvidence,
+ Queryable,
+} from "./audit";
+import { DecisionCache, type PermissionEpoch } from "./cache";
+import { withDeadlineTransaction, type DeadlineBudget, type DeadlinePool } from "../db/deadlineQuery";
import {
Decision,
GfsPermission,
@@ -9,24 +14,15 @@ import {
ShareRow,
} from "./resolve";
-/** Minimal query surface — a pg Pool satisfies this; tests inject a fake. */
-export interface Queryable {
- query(text: string, values?: unknown[]): Promise<{ rows: Record<string, unknown>[] }>;
-}
-
-export interface AuditEvent {
- subject: string;
- op: string;
- resourceId: string;
- drive: string;
- outcome: "allow" | "deny" | "error";
- reason?: string;
- requestId?: string;
-}
-
-export interface AuditSink {
- record(event: AuditEvent): Promise<void>;
-}
+export { DbAuditSink } from "./audit";
+export type {
+ AuditEvent,
+ AuditSink,
+ AuthorizationEvidence,
+ PersistedAuthorizationSource,
+ Queryable,
+} from "./audit";
+export type { PermissionEpoch } from "./cache";
export interface AuthzContext {
drive: string;
@@ -39,6 +35,15 @@ export interface AuthzContext {
requestId?: string;
}
+export interface AuthorizationRequest {
+ resourceId: string;
+ op: GfsPermission;
+}
+
+export type AuthzQueryBudget = DeadlineBudget;
+
+type PermissionDb = Queryable & DeadlinePool;
+
function errMsg(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
@@ -53,6 +58,11 @@ function subjectsKeyOf(subjects: string[]): string {
return [...subjects].sort().join(",");
}
+/** PostgreSQL renders uuid values with hyphens while the HTTP surface uses RID. */
+function resourceLookupKey(resourceId: string): string {
+ return resourceId.replaceAll("-", "").toLowerCase();
+}
+
/**
* Permission-store authorization client (read path).
*
@@ -66,7 +76,7 @@ function subjectsKeyOf(subjects: string[]): string {
*/
export class PermissionClient {
constructor(
- private readonly db: Queryable,
+ private readonly db: PermissionDb,
private readonly audit: AuditSink,
private readonly cache?: DecisionCache
) {}
@@ -76,13 +86,47 @@ export class PermissionClient {
resourceId: string,
op: GfsPermission
): Promise<Decision> {
+ const [decision] = await this.authorizeMany(ctx, [{ resourceId, op }]);
+ return decision;
+ }
+
+ /**
+ * Snapshot the invalidation state so a long-running mutation (copy) can prove,
+ * inside its writer transaction, that no revocation NOTIFY landed after it
+ * authorized. A client with no decision cache cannot hear invalidations at all,
+ * so it reports `bypassed: true` — the mutation then fails closed rather than
+ * publishing against an authorization it cannot re-confirm.
+ */
+ permissionEpoch(): PermissionEpoch {
+ if (!this.cache) return { generation: 0, bypassed: true };
+ return { generation: this.cache.generation, bypassed: this.cache.isBypassed };
+ }
+
+ /**
+ * Resolve a whole operation snapshot with three permission-store reads,
+ * independent of the number of resources: one ancestor forest, one grants
+ * query and one shares query. Decisions are returned in request order and do
+ * not expose resource paths or names.
+ */
+ async authorizeMany(
+ ctx: AuthzContext,
+ requests: readonly AuthorizationRequest[],
+ budget?: AuthzQueryBudget
+ ): Promise<Decision[]> {
+ if (requests.length === 0) return [];
+
// Intrinsic operator authority short-circuits the grant/share lookup, but
// is still audited (and a failing audit still propagates below). Not cached —
// it is already O(1) from ctx.isOperator with no store round-trip to save.
if (ctx.isOperator) {
- const decision: Decision = { allowed: true, via: "operator" };
- await this.auditDecision(ctx, resourceId, op, decision);
- return decision;
+ const decisions = requests.map((): Decision => ({
+ allowed: true,
+ via: "operator",
+ matchedSubject: ctx.subjects.includes("operator:") ? "operator:" : null,
+ authorizationSource: "operator",
+ }));
+ await this.auditBatch(ctx, requests, decisions, budget);
+ return decisions;
}
// Short-TTL decision cache (P2-S03). A HIT skips the store lookup but is
@@ -90,69 +134,101 @@ export class PermissionClient {
// "every op is audited" holds. `get` returns undefined on miss/expiry/bypass
// (fail-closed: a reader that cannot hear invalidations serves nothing), so
// a degraded cache simply means every op re-checks the store.
- const cacheKey = this.cache
- ? { subjectsKey: subjectsKeyOf(ctx.subjects), resourceId, op }
- : null;
- if (cacheKey) {
- const cached = this.cache!.get(cacheKey);
- if (cached !== undefined) {
- const decision: Decision = { allowed: cached, via: cached ? "cache" : null };
- await this.auditDecision(ctx, resourceId, op, decision);
- return decision;
- }
- }
+ const subjectKey = subjectsKeyOf(ctx.subjects);
+ const decisions: Array<Decision | undefined> = new Array(requests.length);
+ const misses: Array<{ index: number; request: AuthorizationRequest }> = [];
+ requests.forEach((request, index) => {
+ const cached = this.cache?.get({ subjectsKey: subjectKey, ...request });
+ if (cached !== undefined) decisions[index] = { ...cached, via: "cache" };
+ else misses.push({ index, request });
+ });
- let decision: Decision;
try {
- const ancestors = await this.ancestors(ctx.drive, resourceId);
- if (ancestors.length === 0) {
- // Resource absent (or fully tombstoned chain) — deny. The read API maps
- // existence (404/410) separately; authorization itself denies.
- decision = { allowed: false, via: null };
- } else {
- const [grants, shares] = await Promise.all([
- this.grantsFor(ctx.drive, ancestors, ctx.subjects),
- this.sharesFor(ctx.drive, ancestors, ctx.subjects),
- ]);
- decision = resolveDecision({
- resourceId: ancestors[0],
- ancestors,
- subjects: new Set(ctx.subjects),
- isOperator: false,
- op,
- grants,
- shares,
+ if (misses.length > 0) {
+ const snapshot = async (db: Queryable) => {
+ const ancestorMap = await this.ancestorsMany(db, ctx.drive, misses.map(({ request }) => request.resourceId));
+ const allAncestors = [...new Set([...ancestorMap.values()].flat())];
+ const grants = await this.grantsFor(db, ctx.drive, allAncestors, ctx.subjects);
+ const shares = await this.sharesFor(db, ctx.drive, allAncestors, ctx.subjects);
+ return { ancestorMap, grants, shares };
+ };
+ const { ancestorMap, grants, shares } = budget
+ ? await withDeadlineTransaction(this.db, budget, true, snapshot)
+ : await snapshot(this.db);
+ misses.forEach(({ index, request }) => {
+ const ancestors = ancestorMap.get(resourceLookupKey(request.resourceId)) ?? [];
+ const decision = ancestors.length === 0
+ ? { allowed: false, via: null, matchedSubject: null, authorizationSource: null } as Decision
+ : resolveDecision({
+ resourceId: ancestors[0],
+ ancestors,
+ subjects: new Set(ctx.subjects),
+ isOperator: false,
+ op: request.op,
+ grants,
+ shares,
+ });
+ decisions[index] = decision;
+ this.cache?.set({ subjectsKey: subjectKey, ...request }, decision);
});
}
} catch (err) {
// Fail closed. Try to audit the error, but the store failure is what we
// surface — never a pathBindings fallback, never a silent allow.
try {
- await this.audit.record({
- subject: ctx.primarySubject,
- op,
- resourceId,
- drive: ctx.drive,
- outcome: "error",
- reason: errMsg(err),
- requestId: ctx.requestId,
- });
+ const append = async (queryable?: Queryable) => {
+ for (const request of requests) await this.audit.record({
+ subject: ctx.primarySubject,
+ op: request.op,
+ resourceId: request.resourceId,
+ drive: ctx.drive,
+ outcome: "error",
+ reason: errMsg(err),
+ requestId: ctx.requestId,
+ recordType: "authorization_decision",
+ matchedSubject: null,
+ authorizationSource: null,
+ cachedAuthorizationSource: null,
+ mutationOutcome: null,
+ }, queryable);
+ };
+ if (budget) await withDeadlineTransaction(this.db, budget, false, append);
+ else await append();
} catch (auditErr) {
console.error(
`[gfsc] failed to audit a store-error denial (subject=${ctx.primarySubject}, ` +
- `resource=${resourceId}): ${errMsg(auditErr)}`
+ `request=${ctx.requestId ?? "unknown"}): ${errMsg(auditErr)}`
);
}
+ if ((err instanceof GfsError && err.code === "precondition_failed")
+ || (budget && ((err as { code?: string }).code === "57014"
+ || budget.signal?.aborted
+ || (budget.now ?? Date.now)() >= budget.deadlineAtMs))) {
+ throw new GfsError("precondition_failed", "synchronous copy deadline exceeded");
+ }
throw new GfsError("not_mounted", `permission store unavailable: ${errMsg(err)}`);
}
- // Populate the cache with the freshly-resolved decision (a no-op while the
- // cache is bypassed). A NOTIFY on any grant/share write flushes this, so a
- // cached allow/deny never outlives a revocation by more than `ttlMs`.
- if (cacheKey) this.cache!.set(cacheKey, decision.allowed);
+ const complete = decisions as Decision[];
+ budget?.signal?.throwIfAborted();
+ await this.auditBatch(ctx, requests, complete, budget);
+ return complete;
+ }
- await this.auditDecision(ctx, resourceId, op, decision);
- return decision;
+ private async auditBatch(
+ ctx: AuthzContext,
+ requests: readonly AuthorizationRequest[],
+ decisions: readonly Decision[],
+ budget?: AuthzQueryBudget
+ ): Promise<void> {
+ const append = async (queryable?: Queryable) => {
+ for (let index = 0; index < requests.length; index += 1) {
+ const request = requests[index];
+ await this.auditDecision(ctx, request.resourceId, request.op, decisions[index], queryable);
+ }
+ };
+ if (budget) await withDeadlineTransaction(this.db, budget, false, append);
+ else await append();
}
/** Audit a decided outcome. Propagates so no un-audited op returns. */
@@ -160,8 +236,21 @@ export class PermissionClient {
ctx: AuthzContext,
resourceId: string,
op: GfsPermission,
- decision: Decision
+ decision: Decision,
+ queryable?: Queryable
): Promise<void> {
+ const evidence: AuthorizationEvidence =
+ decision.via === "cache" &&
+ decision.allowed &&
+ decision.authorizationSource !== null
+ ? {
+ authorizationSource: "cache",
+ cachedAuthorizationSource: decision.authorizationSource,
+ }
+ : {
+ authorizationSource: decision.via === "cache" ? null : decision.authorizationSource,
+ cachedAuthorizationSource: null,
+ };
await this.audit.record({
subject: ctx.primarySubject,
op,
@@ -170,40 +259,69 @@ export class PermissionClient {
outcome: decision.allowed ? "allow" : "deny",
reason: decision.via ?? undefined,
requestId: ctx.requestId,
- });
+ recordType: "authorization_decision",
+ matchedSubject: decision.via === "cache" && !decision.allowed
+ ? null
+ : decision.matchedSubject,
+ ...evidence,
+ mutationOutcome: null,
+ }, queryable);
}
/** Ancestor chain (R first, root last) via a single recursive CTE — not N
* round-trips. Tombstoned rows are excluded. */
- private async ancestors(drive: string, resourceId: string): Promise<string[]> {
+ private async ancestorsMany(
+ db: Queryable,
+ drive: string,
+ resourceIds: readonly string[]
+ ): Promise<Map<string, string[]>> {
const sql = `
- WITH RECURSIVE chain AS (
- SELECT resource_id, parent_resource_id, 0 AS depth
- FROM gfs_resources
- WHERE drive = $1 AND resource_id = $2 AND deleted_at IS NULL
+ WITH RECURSIVE requested(resource_id) AS (
+ SELECT DISTINCT unnest($2::uuid[])
+ ), chain AS (
+ SELECT requested.resource_id AS requested_resource_id,
+ r.resource_id, r.parent_resource_id, 0 AS depth,
+ ARRAY[r.resource_id] AS visited
+ FROM requested
+ JOIN gfs_resources r ON r.resource_id = requested.resource_id
+ WHERE r.drive = $1 AND r.deleted_at IS NULL
UNION ALL
- SELECT r.resource_id, r.parent_resource_id, c.depth + 1
- FROM gfs_resources r
- JOIN chain c ON r.resource_id = c.parent_resource_id
+ SELECT c.requested_resource_id,
+ r.resource_id, r.parent_resource_id, c.depth + 1,
+ c.visited || r.resource_id
+ FROM chain c
+ JOIN gfs_resources r ON r.resource_id = c.parent_resource_id
WHERE r.drive = $1 AND r.deleted_at IS NULL
+ AND NOT r.resource_id = ANY(c.visited)
)
- SELECT resource_id FROM chain ORDER BY depth ASC`;
- const result = await this.db.query(sql, [drive, resourceId]);
- return result.rows.map((row) => String(row.resource_id));
+ SELECT requested_resource_id, resource_id
+ FROM chain
+ ORDER BY requested_resource_id, depth ASC`;
+ const result = await db.query(sql, [drive, resourceIds]);
+ const byResource = new Map<string, string[]>();
+ for (const row of result.rows) {
+ const requested = resourceLookupKey(String(row.requested_resource_id));
+ const chain = byResource.get(requested) ?? [];
+ chain.push(String(row.resource_id));
+ byResource.set(requested, chain);
+ }
+ return byResource;
}
private async grantsFor(
+ db: Queryable,
drive: string,
ancestors: string[],
subjects: string[]
): Promise<GrantRow[]> {
+ if (ancestors.length === 0) return [];
const sql = `
SELECT resource_id, subject_type, subject_id, permissions, inherit
FROM gfs_grants
WHERE drive = $1
AND resource_id = ANY($2::uuid[])
AND (subject_type || ':' || subject_id) = ANY($3::text[])`;
- const result = await this.db.query(sql, [drive, ancestors, subjects]);
+ const result = await db.query(sql, [drive, ancestors, subjects]);
return result.rows.map((row) => ({
subjectKey: `${String(row.subject_type)}:${String(row.subject_id ?? "")}`,
resourceId: String(row.resource_id),
@@ -213,17 +331,19 @@ export class PermissionClient {
}
private async sharesFor(
+ db: Queryable,
drive: string,
ancestors: string[],
subjects: string[]
): Promise<ShareRow[]> {
+ if (ancestors.length === 0) return [];
const sql = `
SELECT resource_id, subject_type, subject_id, permissions, include_descendants
FROM gfs_shares
WHERE drive = $1
AND resource_id = ANY($2::uuid[])
AND (subject_type || ':' || subject_id) = ANY($3::text[])`;
- const result = await this.db.query(sql, [drive, ancestors, subjects]);
+ const result = await db.query(sql, [drive, ancestors, subjects]);
return result.rows.map((row) => ({
subjectKey: `${String(row.subject_type)}:${String(row.subject_id ?? "")}`,
resourceId: String(row.resource_id),
@@ -232,30 +352,3 @@ export class PermissionClient {
}));
}
}
-
-/**
- * Postgres-backed audit sink. Appends one INSERT-only row per authorization
- * decision. Each row carries a content hash (`row_hash`); the full tamper-
- * evident prev_hash -> row_hash chain with a monotonic sequence is completed by
- * the append-only audit writer in P4-S02. gfsc connects as the least-privilege
- * `gfs_controller` role, which holds INSERT-only on gfs_audit.
- */
-export class DbAuditSink implements AuditSink {
- constructor(private readonly db: Queryable) {}
-
- async record(event: AuditEvent): Promise<void> {
- const gfsUri = `gfs://${event.drive}/${event.resourceId}`;
- const rowHash = createHash("sha256")
- .update(
- [event.subject, event.op, gfsUri, event.outcome, event.reason ?? "", event.requestId ?? ""].join(
- " "
- )
- )
- .digest("hex");
- await this.db.query(
- `INSERT INTO gfs_audit (subject, op, gfs_uri, outcome, request_id, row_hash)
- VALUES ($1, $2, $3, $4, $5, $6)`,
- [event.subject, event.op, gfsUri, event.outcome, event.requestId ?? null, rowHash]
- );
- }
-}
diff --git a/gfs-controller/src/authz/resolve.ts b/gfs-controller/src/authz/resolve.ts
index 11c918560..25f749f6f 100644
--- a/gfs-controller/src/authz/resolve.ts
+++ b/gfs-controller/src/authz/resolve.ts
@@ -57,37 +57,81 @@ export interface Decision {
* short-TTL decision cache (so the audit row records the cache hit honestly).
*/
via: "operator" | "grant" | "share" | "cache" | null;
+ /** Canonical subject key that matched the effective grant/share. */
+ matchedSubject: string | null;
+ /**
+ * Effective authority behind the decision. Cache hits retain this underlying
+ * source while `via` reports that the result was served from cache.
+ */
+ authorizationSource:
+ | "operator"
+ | "direct_grant"
+ | "inherited_grant"
+ | "direct_share"
+ | "inherited_share"
+ | null;
}
export function resolveDecision(input: DecisionInput): Decision {
// 1. Intrinsic operator authority — the root of trust, no grant required.
if (input.isOperator) {
- return { allowed: true, via: "operator" };
+ return {
+ allowed: true,
+ via: "operator",
+ matchedSubject: input.subjects.has("operator:") ? "operator:" : null,
+ authorizationSource: "operator",
+ };
}
const ancestorSet = new Set(input.ancestors);
+ const matchingGrants = input.grants
+ .filter((grant) => input.subjects.has(grant.subjectKey) && grant.permissions.includes(input.op))
+ .sort((a, b) => a.subjectKey.localeCompare(b.subjectKey) || a.resourceId.localeCompare(b.resourceId));
// 2. Folder grant: on R itself (always), or on an ancestor ONLY if inherit.
- for (const grant of input.grants) {
- if (!input.subjects.has(grant.subjectKey) || !grant.permissions.includes(input.op)) continue;
- if (grant.resourceId === input.resourceId) {
- return { allowed: true, via: "grant" };
- }
+ const directGrant = matchingGrants.find((grant) => grant.resourceId === input.resourceId);
+ if (directGrant) {
+ return {
+ allowed: true,
+ via: "grant",
+ matchedSubject: directGrant.subjectKey,
+ authorizationSource: "direct_grant",
+ };
+ }
+ for (const grant of matchingGrants) {
if (grant.inherit && ancestorSet.has(grant.resourceId)) {
- return { allowed: true, via: "grant" };
+ return {
+ allowed: true,
+ via: "grant",
+ matchedSubject: grant.subjectKey,
+ authorizationSource: "inherited_grant",
+ };
}
}
// 3. URI share: on R itself, or on an ancestor with includeDescendants.
- for (const share of input.shares) {
- if (!input.subjects.has(share.subjectKey) || !share.permissions.includes(input.op)) continue;
- if (share.resourceId === input.resourceId) {
- return { allowed: true, via: "share" };
- }
+ const matchingShares = input.shares
+ .filter((share) => input.subjects.has(share.subjectKey) && share.permissions.includes(input.op))
+ .sort((a, b) => a.subjectKey.localeCompare(b.subjectKey) || a.resourceId.localeCompare(b.resourceId));
+ const directShare = matchingShares.find((share) => share.resourceId === input.resourceId);
+ if (directShare) {
+ return {
+ allowed: true,
+ via: "share",
+ matchedSubject: directShare.subjectKey,
+ authorizationSource: "direct_share",
+ };
+ }
+ for (const share of matchingShares) {
if (share.includeDescendants && ancestorSet.has(share.resourceId)) {
- return { allowed: true, via: "share" };
+ return {
+ allowed: true,
+ via: "share",
+ matchedSubject: share.subjectKey,
+ authorizationSource: "inherited_share",
+ };
}
}
- return { allowed: false, via: null };
+ return { allowed: false, via: null, matchedSubject: null, authorizationSource: null };
}
diff --git a/gfs-controller/src/authz/storeProbe.test.ts b/gfs-controller/src/authz/storeProbe.test.ts
index 3d73f19d2..af5d969ad 100644
--- a/gfs-controller/src/authz/storeProbe.test.ts
+++ b/gfs-controller/src/authz/storeProbe.test.ts
@@ -61,6 +61,20 @@ interface FakeClientBehavior {
queryHangs?: boolean;
canRead?: boolean;
canAudit?: boolean;
+ immutableSchemaReady?: boolean;
+ canInsertManifests?: boolean;
+ canUpdateManifests?: boolean;
+ canDeleteManifests?: boolean;
+ canInsertResources?: boolean;
+ canUpdateResources?: boolean;
+ auditSchemaReady?: boolean;
+ auditConstraintsReady?: boolean;
+ canMutateResources?: boolean;
+ canMutateGrants?: boolean;
+ canMutateShares?: boolean;
+ canMutateManifests?: boolean;
+ canMutateAudit?: boolean;
+ canUpdateAuditSequence?: boolean;
queryError?: Error;
}
@@ -89,7 +103,28 @@ function fakeClientFactory(behavior: FakeClientBehavior): {
if (behavior.queryError) throw behavior.queryError;
return {
rows: [
- { can_read: behavior.canRead !== false, can_audit: behavior.canAudit !== false },
+ {
+ can_read: behavior.canRead !== false,
+ can_audit: behavior.canAudit !== false,
+ can_read_blob_key: behavior.immutableSchemaReady !== false,
+ can_read_digest: behavior.immutableSchemaReady !== false,
+ can_read_manifests: behavior.immutableSchemaReady !== false,
+ resource_schema_ready: behavior.immutableSchemaReady !== false,
+ manifest_schema_ready: behavior.immutableSchemaReady !== false,
+ can_insert_manifests: behavior.canInsertManifests !== false,
+ can_update_manifests: behavior.canUpdateManifests !== false,
+ can_delete_manifests: behavior.canDeleteManifests !== false,
+ can_insert_resources: behavior.canInsertResources !== false,
+ can_update_resources: behavior.canUpdateResources !== false,
+ audit_schema_ready: behavior.auditSchemaReady !== false,
+ audit_constraints_ready: behavior.auditConstraintsReady !== false,
+ can_mutate_resources: behavior.canMutateResources === true,
+ can_mutate_grants: behavior.canMutateGrants === true,
+ can_mutate_shares: behavior.canMutateShares === true,
+ can_mutate_manifests: behavior.canMutateManifests === true,
+ can_mutate_audit: behavior.canMutateAudit === true,
+ can_update_audit_sequence: behavior.canUpdateAuditSequence === true,
+ },
],
};
},
@@ -116,6 +151,7 @@ describe("createPermissionStoreProbe", () => {
pool: fakePool(),
connectionString: DSN,
intervalMs: INTERVAL,
+ storageRole: "reader",
clientFactory: factory,
now: () => 0,
});
@@ -128,6 +164,7 @@ describe("createPermissionStoreProbe", () => {
pool: fakePool(),
connectionString: DSN,
intervalMs: INTERVAL,
+ storageRole: "reader",
clientFactory: factory,
now: () => 0,
});
@@ -140,12 +177,133 @@ describe("createPermissionStoreProbe", () => {
pool: fakePool(),
connectionString: DSN,
intervalMs: INTERVAL,
+ storageRole: "reader",
clientFactory: factory,
now: () => 0,
});
await expect(probe()).rejects.toThrow(/gfs_audit.*INSERT|INSERT on gfs_audit/s);
});
+ it("rejects a pre-0068 reader schema before serving requests", async () => {
+ const { factory } = fakeClientFactory({ immutableSchemaReady: false });
+ const probe = createPermissionStoreProbe({
+ pool: fakePool(),
+ connectionString: DSN,
+ intervalMs: INTERVAL,
+ storageRole: "reader",
+ clientFactory: factory,
+ now: () => 0,
+ });
+ await expect(probe()).rejects.toThrow(/migration 0068/);
+ });
+
+ it("keeps reader readiness independent of the writer-only manifest schema", async () => {
+ const probeClient = fakeClientFactory({});
+ const probe = createPermissionStoreProbe({
+ pool: fakePool(),
+ connectionString: DSN,
+ intervalMs: INTERVAL,
+ storageRole: "reader",
+ clientFactory: probeClient.factory,
+ now: () => 0,
+ });
+ await expect(probe()).resolves.toBeUndefined();
+ expect(probeClient.lastSql()).not.toContain("manifest_schema_ready");
+ expect(probeClient.lastSql()).not.toContain("candidate_kind, state");
+ expect(probeClient.lastSql()).toContain("FROM pg_attribute");
+ expect(probeClient.lastSql()).toContain("'cached_authorization_source'");
+ expect(probeClient.lastSql()).toContain("gfs_audit_record_type_fields_valid");
+ });
+
+ it.each([
+ ["resource mutation", { canMutateResources: true }],
+ ["grant mutation", { canMutateGrants: true }],
+ ["share mutation", { canMutateShares: true }],
+ ["manifest mutation", { canMutateManifests: true }],
+ ["non-append audit mutation", { canMutateAudit: true }],
+ ["audit sequence update", { canUpdateAuditSequence: true }],
+ ] satisfies Array<[string, FakeClientBehavior]>)
+ ("rejects a reader granted forbidden %s privileges", async (_privilege, behavior) => {
+ const { factory } = fakeClientFactory(behavior);
+ const probe = createPermissionStoreProbe({
+ pool: fakePool(),
+ connectionString: DSN,
+ intervalMs: INTERVAL,
+ storageRole: "reader",
+ clientFactory: factory,
+ now: () => 0,
+ });
+ await expect(probe()).rejects.toThrow(/reader has forbidden GFS mutation privileges.*0069/s);
+ });
+
+ it("does not apply reader-only negative privilege checks to the writer", async () => {
+ const { factory } = fakeClientFactory({
+ canMutateResources: true,
+ canMutateManifests: true,
+ });
+ const probe = createPermissionStoreProbe({
+ pool: fakePool(),
+ connectionString: DSN,
+ intervalMs: INTERVAL,
+ storageRole: "writer",
+ clientFactory: factory,
+ now: () => 0,
+ });
+ await expect(probe()).resolves.toBeUndefined();
+ });
+
+ it.each(["reader", "writer"] as const)(
+ "rejects a %s when migration 0070 audit columns are missing",
+ async (storageRole) => {
+ const { factory } = fakeClientFactory({ auditSchemaReady: false });
+ const probe = createPermissionStoreProbe({
+ pool: fakePool(),
+ connectionString: DSN,
+ intervalMs: INTERVAL,
+ storageRole,
+ clientFactory: factory,
+ now: () => 0,
+ });
+ await expect(probe()).rejects.toThrow(/migration 0070/);
+ }
+ );
+
+ it.each(["reader", "writer"] as const)(
+ "rejects a %s when migration 0070 audit constraints are missing or unvalidated",
+ async (storageRole) => {
+ const { factory } = fakeClientFactory({ auditConstraintsReady: false });
+ const probe = createPermissionStoreProbe({
+ pool: fakePool(),
+ connectionString: DSN,
+ intervalMs: INTERVAL,
+ storageRole,
+ clientFactory: factory,
+ now: () => 0,
+ });
+ await expect(probe()).rejects.toThrow(/migration 0070/);
+ }
+ );
+
+ it.each([
+ ["manifest INSERT", { canInsertManifests: false }],
+ ["manifest UPDATE", { canUpdateManifests: false }],
+ ["manifest DELETE", { canDeleteManifests: false }],
+ ["resource INSERT", { canInsertResources: false }],
+ ["resource UPDATE", { canUpdateResources: false }],
+ ] satisfies Array<[string, FakeClientBehavior]>)
+ ("rejects a writer missing only %s", async (_privilege, behavior) => {
+ const { factory } = fakeClientFactory(behavior);
+ const probe = createPermissionStoreProbe({
+ pool: fakePool(),
+ connectionString: DSN,
+ intervalMs: INTERVAL,
+ storageRole: "writer",
+ clientFactory: factory,
+ now: () => 0,
+ });
+ await expect(probe()).rejects.toThrow(/writer lacks.*0068/s);
+ });
+
it("pins the coherence canary SQL to both least-privilege grants", async () => {
// Regression guard: gutting COHERENCE_SQL (e.g. SELECT true AS can_read...)
// must fail here even though every behavior test uses a fake client.
@@ -154,6 +312,7 @@ describe("createPermissionStoreProbe", () => {
pool: fakePool(),
connectionString: DSN,
intervalMs: INTERVAL,
+ storageRole: "writer",
clientFactory: probeClient.factory,
now: () => 0,
});
@@ -162,6 +321,47 @@ describe("createPermissionStoreProbe", () => {
expect(sql).toContain("has_table_privilege");
expect(sql).toMatch(/gfs_resources'\s*,\s*'SELECT'/);
expect(sql).toMatch(/gfs_audit'\s*,\s*'INSERT'/);
+ expect(sql).toContain("gfs_blob_manifests");
+ expect(sql).toContain("blob_key, content_sha256 FROM gfs_resources WHERE false");
+ expect(sql).toMatch(/gfs_blob_manifests'\s*,\s*'INSERT'/);
+ expect(sql).toMatch(/gfs_blob_manifests'\s*,\s*'UPDATE'/);
+ expect(sql).toMatch(/gfs_blob_manifests'\s*,\s*'DELETE'/);
+ expect(sql).toMatch(/gfs_resources'\s*,\s*'INSERT'/);
+ expect(sql).toMatch(/gfs_resources'\s*,\s*'UPDATE'/);
+ expect(sql).toContain("FROM pg_attribute");
+ expect(sql).toContain("'record_type'");
+ expect(sql).toContain("'matched_subject'");
+ expect(sql).toContain("'authorization_source'");
+ expect(sql).toContain("'cached_authorization_source'");
+ expect(sql).toContain("'mutation_outcome'");
+ expect(sql).toContain("gfs_audit_record_type_valid");
+ expect(sql).toContain("gfs_audit_authorization_source_valid");
+ expect(sql).toContain("gfs_audit_cached_authorization_source_valid");
+ expect(sql).toContain("gfs_audit_mutation_outcome_valid");
+ expect(sql).toContain("gfs_audit_record_type_fields_valid");
+ expect(sql).toContain("convalidated");
+ expect(sql).not.toContain("can_mutate_resources");
+ expect(sql).not.toContain("can_update_audit_sequence");
+ });
+
+ it("pins the reader coherence canary to every forbidden mutation class", async () => {
+ const probeClient = fakeClientFactory({});
+ const probe = createPermissionStoreProbe({
+ pool: fakePool(),
+ connectionString: DSN,
+ intervalMs: INTERVAL,
+ storageRole: "reader",
+ clientFactory: probeClient.factory,
+ now: () => 0,
+ });
+ await probe();
+ const sql = probeClient.lastSql() ?? "";
+ expect(sql).toMatch(/gfs_resources'\s*,\s*'INSERT, UPDATE, DELETE, TRUNCATE'/);
+ expect(sql).toMatch(/gfs_grants'\s*,\s*'INSERT, UPDATE, DELETE, TRUNCATE'/);
+ expect(sql).toMatch(/gfs_shares'\s*,\s*'INSERT, UPDATE, DELETE, TRUNCATE'/);
+ expect(sql).toMatch(/gfs_blob_manifests'\s*,\s*'INSERT, UPDATE, DELETE, TRUNCATE'/);
+ expect(sql).toMatch(/gfs_audit'\s*,\s*'UPDATE, DELETE, TRUNCATE'/);
+ expect(sql).toMatch(/gfs_audit_sequence_no_seq'\s*,\s*'UPDATE'/);
});
it("bounds a hanging coherence QUERY with the probe timeout", async () => {
@@ -171,6 +371,7 @@ describe("createPermissionStoreProbe", () => {
connectionString: DSN,
intervalMs: INTERVAL,
connectTimeoutMs: 20,
+ storageRole: "reader",
clientFactory: hanging.factory,
now: () => 0,
});
@@ -190,6 +391,7 @@ describe("createPermissionStoreProbe", () => {
connectionString: DSN,
intervalMs: INTERVAL,
connectTimeoutMs: 10,
+ storageRole: "reader",
clientFactory: factory,
now: () => 0,
});
@@ -210,6 +412,7 @@ describe("createPermissionStoreProbe", () => {
connectionString: DSN,
intervalMs: INTERVAL,
connectTimeoutMs: 15,
+ storageRole: "reader",
clientFactory: factory,
now: () => 0,
});
@@ -227,6 +430,7 @@ describe("createPermissionStoreProbe", () => {
connectionString: DSN,
intervalMs: INTERVAL,
connectTimeoutMs: 20,
+ storageRole: "reader",
clientFactory: factory,
now: () => 0,
});
@@ -241,6 +445,7 @@ describe("createPermissionStoreProbe", () => {
connectionString: DSN,
intervalMs: INTERVAL,
connectTimeoutMs: 20,
+ storageRole: "reader",
clientFactory: hanging.factory,
now: () => 0,
});
@@ -256,6 +461,7 @@ describe("createPermissionStoreProbe", () => {
pool,
connectionString: DSN,
intervalMs: INTERVAL,
+ storageRole: "reader",
clientFactory: factory,
now: () => t,
});
@@ -273,6 +479,7 @@ describe("createPermissionStoreProbe", () => {
pool: fakePool(),
connectionString: DSN,
intervalMs: INTERVAL,
+ storageRole: "reader",
clientFactory: factory,
now: () => t,
});
@@ -290,6 +497,7 @@ describe("createPermissionStoreProbe", () => {
pool: fakePool(),
connectionString: DSN,
intervalMs: INTERVAL,
+ storageRole: "reader",
clientFactory: factory,
now: () => 0,
});
@@ -306,6 +514,7 @@ describe("createPermissionStoreProbe", () => {
pool,
connectionString: DSN,
intervalMs: INTERVAL,
+ storageRole: "reader",
clientFactory: factory,
now: () => t,
});
@@ -321,6 +530,7 @@ describe("createPermissionStoreProbe", () => {
pool: fakePool(),
connectionString: DSN,
intervalMs: INTERVAL,
+ storageRole: "reader",
clientFactory: success.factory,
now: () => 0,
});
@@ -333,6 +543,7 @@ describe("createPermissionStoreProbe", () => {
pool: fakePool(),
connectionString: DSN,
intervalMs: INTERVAL,
+ storageRole: "reader",
clientFactory: failing.factory,
now: () => 0,
});
diff --git a/gfs-controller/src/authz/storeProbe.ts b/gfs-controller/src/authz/storeProbe.ts
index 6d60c0aaa..09a52cc8f 100644
--- a/gfs-controller/src/authz/storeProbe.ts
+++ b/gfs-controller/src/authz/storeProbe.ts
@@ -45,6 +45,8 @@ export interface StoreProbeOptions {
connectionString: string;
/** Amortization window for the fresh-connection probe (e.g. 60_000). */
intervalMs: number;
+ /** Selects the exact least-privilege readiness contract; never inferred. */
+ storageRole: "writer" | "reader";
/**
* Hard bound on each fresh-probe step (connect AND coherence query).
* Without it, a black-hole partition (unreachable but not refusing) leaves
@@ -81,9 +83,42 @@ function withTimeout<T>(promise: Promise<T>, ms: number, what: string): Promise<
// INSERT on gfs_audit breaks every request too (audit-write failures propagate
// — no un-audited op is served), so either one must flip readiness instead of
// surfacing as chronic per-request 503s.
-const COHERENCE_SQL =
+const BASE_COHERENCE_SQL =
"SELECT has_table_privilege(current_user, 'gfs_resources', 'SELECT') AS can_read, " +
- "has_table_privilege(current_user, 'gfs_audit', 'INSERT') AS can_audit";
+ "has_table_privilege(current_user, 'gfs_audit', 'INSERT') AS can_audit, " +
+ "has_column_privilege(current_user, 'gfs_resources', 'blob_key', 'SELECT') AS can_read_blob_key, " +
+ "has_column_privilege(current_user, 'gfs_resources', 'content_sha256', 'SELECT') AS can_read_digest, " +
+ "EXISTS (SELECT 1 FROM (SELECT blob_key, content_sha256 FROM gfs_resources WHERE false) AS resource_probe) = false AS resource_schema_ready, " +
+ "(SELECT count(*) = 5 AND bool_and(atttypid = 'text'::regtype) " +
+ "AND bool_and(attname <> 'record_type' OR attnotnull) FROM pg_attribute " +
+ "WHERE attrelid = 'gfs_audit'::regclass AND attnum > 0 AND NOT attisdropped " +
+ "AND attname = ANY (ARRAY['record_type', 'matched_subject', 'authorization_source', 'cached_authorization_source', 'mutation_outcome'])) AS audit_schema_ready, " +
+ "(SELECT count(*) = 5 FROM pg_constraint WHERE conrelid = 'gfs_audit'::regclass " +
+ "AND conname = ANY (ARRAY['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']) " +
+ "AND contype = 'c' AND convalidated) AS audit_constraints_ready";
+
+// The reader is deliberately read-only except for append-only audit records.
+// Positive checks alone are insufficient: a stale/manual grant would keep the
+// role Ready while silently expanding its blast radius. These checks use the
+// effective current_user privileges, so inherited or PUBLIC grants fail too.
+const READER_COHERENCE_SQL =
+ BASE_COHERENCE_SQL +
+ ", has_table_privilege(current_user, 'gfs_resources', 'INSERT, UPDATE, DELETE, TRUNCATE') AS can_mutate_resources, " +
+ "has_table_privilege(current_user, 'gfs_grants', 'INSERT, UPDATE, DELETE, TRUNCATE') AS can_mutate_grants, " +
+ "has_table_privilege(current_user, 'gfs_shares', 'INSERT, UPDATE, DELETE, TRUNCATE') AS can_mutate_shares, " +
+ "has_table_privilege(current_user, 'gfs_blob_manifests', 'INSERT, UPDATE, DELETE, TRUNCATE') AS can_mutate_manifests, " +
+ "has_table_privilege(current_user, 'gfs_audit', 'UPDATE, DELETE, TRUNCATE') AS can_mutate_audit, " +
+ "has_sequence_privilege(current_user, 'gfs_audit_sequence_no_seq', 'UPDATE') AS can_update_audit_sequence";
+
+const WRITER_COHERENCE_SQL =
+ BASE_COHERENCE_SQL +
+ ", has_table_privilege(current_user, 'gfs_blob_manifests', 'SELECT') AS can_read_manifests, " +
+ "has_table_privilege(current_user, 'gfs_blob_manifests', 'INSERT') AS can_insert_manifests, " +
+ "has_table_privilege(current_user, 'gfs_blob_manifests', 'UPDATE') AS can_update_manifests, " +
+ "has_table_privilege(current_user, 'gfs_blob_manifests', 'DELETE') AS can_delete_manifests, " +
+ "has_table_privilege(current_user, 'gfs_resources', 'INSERT') AS can_insert_resources, " +
+ "has_table_privilege(current_user, 'gfs_resources', 'UPDATE') AS can_update_resources, " +
+ "EXISTS (SELECT 1 FROM (SELECT blob_key, candidate_kind, state, content_sha256, bytes FROM gfs_blob_manifests WHERE false) AS manifest_probe) = false AS manifest_schema_ready";
export function createPermissionStoreProbe(opts: StoreProbeOptions): () => Promise<void> {
const now = opts.now ?? Date.now;
@@ -159,7 +194,7 @@ export function createPermissionStoreProbe(opts: StoreProbeOptions): () => Promi
// instead of dangling until the OS TCP timeout.
await withTimeout(client.connect(), connectTimeoutMs, "permission store connect");
const result = await withTimeout(
- client.query(COHERENCE_SQL),
+ client.query(opts.storageRole === "writer" ? WRITER_COHERENCE_SQL : READER_COHERENCE_SQL),
connectTimeoutMs,
"permission store coherence query"
);
@@ -176,6 +211,51 @@ export function createPermissionStoreProbe(opts: StoreProbeOptions): () => Promi
"(audit-write failures would 503 every request; control-api migration 0048 not applied?)"
);
}
+ if (
+ row?.can_read_blob_key !== true ||
+ row?.can_read_digest !== true ||
+ row?.resource_schema_ready !== true
+ ) {
+ throw new Error(
+ "permission store coherence check failed: immutable GFS blob schema/reader privileges " +
+ "are missing (control-api migration 0068 not applied?)"
+ );
+ }
+ if (row?.audit_schema_ready !== true || row?.audit_constraints_ready !== true) {
+ throw new Error(
+ "permission store coherence check failed: GFS audit decision evidence schema is missing " +
+ "(control-api migration 0070 not applied?)"
+ );
+ }
+ if (
+ opts.storageRole === "reader" &&
+ (row?.can_mutate_resources !== false ||
+ row?.can_mutate_grants !== false ||
+ row?.can_mutate_shares !== false ||
+ row?.can_mutate_manifests !== false ||
+ row?.can_mutate_audit !== false ||
+ row?.can_update_audit_sequence !== false)
+ ) {
+ throw new Error(
+ "permission store coherence check failed: reader has forbidden GFS mutation privileges " +
+ "(control-api migration 0069 grants drifted?)"
+ );
+ }
+ if (
+ opts.storageRole === "writer" &&
+ (row?.can_read_manifests !== true ||
+ row?.manifest_schema_ready !== true ||
+ row?.can_insert_manifests !== true ||
+ row?.can_update_manifests !== true ||
+ row?.can_delete_manifests !== true ||
+ row?.can_insert_resources !== true ||
+ row?.can_update_resources !== true)
+ ) {
+ throw new Error(
+ "permission store coherence check failed: writer lacks GFS manifest/resource mutation " +
+ "privileges (control-api migration 0068 not applied?)"
+ );
+ }
lastFreshOkAt = now(); // cache SUCCESS only — failures always retry
} finally {
// Best-effort close of the ephemeral client; a close error must not mask
diff --git a/gfs-controller/src/config.test.ts b/gfs-controller/src/config.test.ts
new file mode 100644
index 000000000..9b4d8f1dc
--- /dev/null
+++ b/gfs-controller/src/config.test.ts
@@ -0,0 +1,98 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { loadConfig } from './config'
+
+describe('GFS_STORAGE_ROLE', () => {
+ afterEach(() => {
+ vi.unstubAllEnvs()
+ })
+
+ it.each(['reader', 'writer'] as const)('accepts %s', role => {
+ vi.stubEnv('GFS_DEV_MODE', 'true')
+ vi.stubEnv('GFS_STORAGE_ROLE', role)
+ expect(loadConfig().storageRole).toBe(role)
+ })
+
+ it.each([undefined, ''])('rejects absent or empty role %s instead of granting writer authority', role => {
+ vi.stubEnv('GFS_DEV_MODE', 'true')
+ vi.stubEnv('GFS_STORAGE_ROLE', role)
+ expect(() => loadConfig()).toThrow(/GFS_STORAGE_ROLE must be explicitly set/)
+ })
+
+ it.each(['Writer', 'read', 'writer ', 'unknown'])('rejects unknown value %s', role => {
+ vi.stubEnv('GFS_DEV_MODE', 'true')
+ vi.stubEnv('GFS_STORAGE_ROLE', role)
+ expect(() => loadConfig()).toThrow(/GFS_STORAGE_ROLE must be explicitly set/)
+ })
+})
+
+describe('GFS_SYNC_COPY_*', () => {
+ beforeEach(() => vi.stubEnv('GFS_STORAGE_ROLE', 'writer'))
+ afterEach(() => {
+ vi.unstubAllEnvs()
+ })
+
+ function configWith(name: string, value: string | undefined) {
+ vi.stubEnv('GFS_DEV_MODE', 'true')
+ vi.stubEnv(name, value)
+ return loadConfig()
+ }
+
+ it('uses documented defaults only when the variables are absent', () => {
+ vi.stubEnv('GFS_DEV_MODE', 'true')
+ vi.stubEnv('GFS_SYNC_COPY_MAX_OBJECTS', undefined)
+ vi.stubEnv('GFS_SYNC_COPY_MAX_BYTES', undefined)
+ vi.stubEnv('GFS_SYNC_COPY_TIMEOUT_MS', undefined)
+ vi.stubEnv('GFS_SYNC_RENAME_MAX_OBJECTS', undefined)
+ vi.stubEnv('GFS_SYNC_RENAME_TIMEOUT_MS', undefined)
+ expect(loadConfig()).toMatchObject({
+ syncCopyMaxObjects: 1000,
+ syncCopyMaxBytes: 1073741824,
+ syncCopyTimeoutMs: 30000,
+ syncRenameMaxObjects: 1000,
+ syncRenameTimeoutMs: 30000,
+ })
+ })
+
+ it.each([
+ ['GFS_SYNC_COPY_MAX_OBJECTS', '25', 'syncCopyMaxObjects', 25],
+ ['GFS_SYNC_COPY_MAX_OBJECTS', '2500', 'syncCopyMaxObjects', 2500],
+ ['GFS_SYNC_COPY_MAX_BYTES', '1024', 'syncCopyMaxBytes', 1024],
+ ['GFS_SYNC_COPY_MAX_BYTES', '2147483648', 'syncCopyMaxBytes', 2147483648],
+ ['GFS_SYNC_COPY_TIMEOUT_MS', '5000', 'syncCopyTimeoutMs', 5000],
+ ['GFS_SYNC_COPY_TIMEOUT_MS', '60000', 'syncCopyTimeoutMs', 60000],
+ ['GFS_SYNC_RENAME_MAX_OBJECTS', '250', 'syncRenameMaxObjects', 250],
+ ['GFS_SYNC_RENAME_TIMEOUT_MS', '15000', 'syncRenameTimeoutMs', 15000],
+ ] as const)('accepts %s=%s without a hidden ceiling', (name, raw, field, expected) => {
+ expect(configWith(name, raw)[field]).toBe(expected)
+ })
+
+ it.each([
+ 'GFS_SYNC_COPY_MAX_OBJECTS',
+ 'GFS_SYNC_COPY_MAX_BYTES',
+ 'GFS_SYNC_COPY_TIMEOUT_MS',
+ 'GFS_SYNC_RENAME_MAX_OBJECTS',
+ 'GFS_SYNC_RENAME_TIMEOUT_MS',
+ ])('rejects invalid explicitly configured values for %s', name => {
+ for (const raw of [
+ '',
+ ' ',
+ '0',
+ '-1',
+ '1.5',
+ 'NaN',
+ 'Infinity',
+ '1e3',
+ '9007199254740992',
+ ]) {
+ expect(() => configWith(name, raw), `${name}=${JSON.stringify(raw)}`).toThrow(
+ new RegExp(`${name} must be a positive safe integer`)
+ )
+ }
+ })
+
+ it('accepts the largest safely representable integer', () => {
+ expect(
+ configWith('GFS_SYNC_COPY_MAX_OBJECTS', String(Number.MAX_SAFE_INTEGER)).syncCopyMaxObjects
+ ).toBe(Number.MAX_SAFE_INTEGER)
+ })
+})
diff --git a/gfs-controller/src/config.ts b/gfs-controller/src/config.ts
index 22d30d593..efffd9f5b 100644
--- a/gfs-controller/src/config.ts
+++ b/gfs-controller/src/config.ts
@@ -39,6 +39,19 @@ export interface GfsConfig {
* garbage values fail loud.
*/
credentialProbeIntervalMs: number
+ blobCleanupSafetyWindowMs: number
+ blobCleanupIntervalMs: number
+ blobCleanupBatchSize: number
+ /** Maximum source objects admitted by one synchronous Copy request. */
+ syncCopyMaxObjects: number
+ /** Maximum observed source bytes admitted by one synchronous Copy request. */
+ syncCopyMaxBytes: number
+ /** End-to-end deadline for one synchronous Copy request. */
+ syncCopyTimeoutMs: number
+ /** Maximum live subtree objects admitted by one synchronous rename request. */
+ syncRenameMaxObjects: number
+ /** End-to-end deadline for one synchronous rename request. */
+ syncRenameTimeoutMs: number
devMode: boolean
}
@@ -59,19 +72,68 @@ function tuningMs(name: string, defaultMs: number): number {
return value
}
+function positiveInteger(name: string, defaultValue: number, maximum: number): number {
+ const raw = process.env[name]
+ if (raw === undefined || raw === '') return defaultValue
+ const value = Number(raw)
+ if (!Number.isSafeInteger(value) || value <= 0 || value > maximum) {
+ throw new Error(`[gfsc] ${name} must be an integer between 1 and ${maximum}, got: ${raw}`)
+ }
+ return value
+}
+
+/**
+ * Copy admission limits intentionally have no compiled product ceiling. Only
+ * an absent variable selects the documented default; an explicitly empty or
+ * non-canonical positive decimal fails startup instead of falling back.
+ */
+function syncCopyPositiveInteger(name: string, defaultValue: number): number {
+ const raw = process.env[name]
+ if (raw === undefined) return defaultValue
+ if (!/^[1-9]\d*$/.test(raw)) {
+ throw new Error(`[gfsc] ${name} must be a positive safe integer, got: ${JSON.stringify(raw)}`)
+ }
+ const value = Number(raw)
+ if (!Number.isSafeInteger(value)) {
+ throw new Error(`[gfsc] ${name} must be a positive safe integer, got: ${JSON.stringify(raw)}`)
+ }
+ return value
+}
+
+function storageRole(): GfsConfig['storageRole'] {
+ const value = process.env.GFS_STORAGE_ROLE
+ if (value === 'reader' || value === 'writer') return value
+ throw new Error(`[gfsc] GFS_STORAGE_ROLE must be explicitly set to 'reader' or 'writer', got: ${JSON.stringify(value)}`)
+}
+
export function loadConfig(): GfsConfig {
const devMode = process.env.GFS_DEV_MODE === 'true'
- const storageRole = process.env.GFS_STORAGE_ROLE === 'reader' ? 'reader' : 'writer'
return {
port: Number(process.env.GFS_PORT || 8087),
storageMountPath: required('GFS_STORAGE_PATH', devMode, '/tmp/gfs-data'),
- storageRole,
+ storageRole: storageRole(),
pgConnectionString: required('GFS_PG_CONNECTION_STRING', devMode, ''),
tokenAudience: process.env.GFS_TOKEN_AUDIENCE || 'gfs-controller',
publicKey: process.env.GFS_JWT_PUBLIC_KEY || '',
driveName: process.env.GFS_DRIVE_NAME || 'main',
decisionCacheTtlMs: Number(process.env.GFS_DECISION_CACHE_TTL_MS || 5000),
credentialProbeIntervalMs: tuningMs('GFS_CREDENTIAL_PROBE_INTERVAL_MS', 60000),
+ blobCleanupSafetyWindowMs: positiveInteger(
+ 'GFS_BLOB_CLEANUP_SAFETY_WINDOW_MS',
+ 3600000,
+ 31536000000
+ ),
+ blobCleanupIntervalMs: positiveInteger(
+ 'GFS_BLOB_CLEANUP_INTERVAL_MS',
+ 60000,
+ 2147483647
+ ),
+ blobCleanupBatchSize: positiveInteger('GFS_BLOB_CLEANUP_BATCH_SIZE', 100, 10000),
+ syncCopyMaxObjects: syncCopyPositiveInteger('GFS_SYNC_COPY_MAX_OBJECTS', 1000),
+ syncCopyMaxBytes: syncCopyPositiveInteger('GFS_SYNC_COPY_MAX_BYTES', 1073741824),
+ syncCopyTimeoutMs: syncCopyPositiveInteger('GFS_SYNC_COPY_TIMEOUT_MS', 30000),
+ syncRenameMaxObjects: syncCopyPositiveInteger('GFS_SYNC_RENAME_MAX_OBJECTS', 1000),
+ syncRenameTimeoutMs: syncCopyPositiveInteger('GFS_SYNC_RENAME_TIMEOUT_MS', 30000),
devMode,
}
}
diff --git a/gfs-controller/src/db/blobReconciliation.ts b/gfs-controller/src/db/blobReconciliation.ts
new file mode 100644
index 000000000..a9f39594a
--- /dev/null
+++ b/gfs-controller/src/db/blobReconciliation.ts
@@ -0,0 +1,69 @@
+import type { GfsMetrics } from "../metrics";
+import type { CleanupBlobStore, PgBlobStagingStore } from "./blobStaging";
+
+export interface ReconcileResult {
+ candidates: number;
+ candidateBytes: number;
+ deleted: number;
+ retained: number;
+ failures: number;
+}
+
+function errText(err: unknown): string {
+ return err instanceof Error ? err.message : String(err);
+}
+
+export async function reconcileExpiredBlobs(
+ manifests: PgBlobStagingStore,
+ blobs: CleanupBlobStore,
+ metrics: GfsMetrics,
+ options: { olderThanMs: number; limit: number }
+): Promise<ReconcileResult> {
+ const totals = await manifests.orphanTotals(options.olderThanMs);
+ const result: ReconcileResult = { candidates: totals.count, candidateBytes: totals.bytes, deleted: 0, retained: 0, failures: 0 };
+ metrics.setOrphanCandidates(result.candidates, result.candidateBytes);
+ for (let index = 0; index < options.limit; index += 1) {
+ try {
+ const candidate = await manifests.claimExpiredCandidate(options.olderThanMs);
+ if (!candidate) break;
+ if (await manifests.referenced(candidate)) {
+ await manifests.restoreCommitted(candidate.blobKey);
+ result.retained += 1;
+ continue;
+ }
+ try {
+ if (candidate.candidateKind === "legacy_flat") await blobs.deleteLegacyFlat(candidate.resourceId);
+ else await blobs.deleteByKey(candidate.blobKey);
+ } catch (err) {
+ if ((err as { code?: string }).code !== "not_found") throw err;
+ }
+ await manifests.remove(candidate.blobKey);
+ result.deleted += 1;
+ } catch (err) {
+ // The failure counter alone cannot be diagnosed: log WHY this candidate
+ // failed before deferring the remainder to the next reconciliation run.
+ console.error(`[gfsc] blob cleanup candidate failed: ${errText(err)}`);
+ result.failures += 1;
+ result.retained += 1;
+ metrics.recordBlobCleanupFailure();
+ break;
+ }
+ }
+ if (result.failures === 0) {
+ await manifests.removeCommittedMetadata(options.limit).catch((err: unknown) => {
+ console.error(`[gfsc] committed-manifest metadata cleanup failed: ${errText(err)}`);
+ result.failures += 1;
+ metrics.recordBlobCleanupFailure();
+ });
+ }
+ try {
+ const remaining = await manifests.orphanTotals(options.olderThanMs);
+ metrics.setOrphanCandidates(remaining.count, remaining.bytes);
+ } catch (err) {
+ console.error(`[gfsc] orphan-candidate recount failed: ${errText(err)}`);
+ result.failures += 1;
+ metrics.recordBlobCleanupFailure();
+ }
+ result.retained = Math.max(result.retained, result.candidates - result.deleted);
+ return result;
+}
diff --git a/gfs-controller/src/db/blobStaging.cleanup.test.ts b/gfs-controller/src/db/blobStaging.cleanup.test.ts
new file mode 100644
index 000000000..e57b4be0d
--- /dev/null
+++ b/gfs-controller/src/db/blobStaging.cleanup.test.ts
@@ -0,0 +1,64 @@
+import { existsSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+import { BlobStore, BlobWriteCleanupError } from "../storage/blobStore";
+import { resolveBlobKeyPath } from "../storage/paths";
+import {
+ PgBlobStagingStore,
+ stageVerifiedBlob,
+ type ManifestQueryable,
+} from "./blobStaging";
+
+describe("failed blob staging cleanup", () => {
+ it("retains the staged manifest when write durability fails before ownership returns", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "gfs-staging-cleanup-"));
+ const generation = "11111111-1111-4111-8111-111111111111";
+ const resourceId = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
+ const rid = resourceId.replaceAll("-", "");
+ const events: string[] = [];
+ let failFirstBlobSync = true;
+ const cleanupSyncFailure = new Error("cleanup directory fsync failed");
+ const db: ManifestQueryable = {
+ query: async sql => {
+ if (sql.includes("INSERT INTO gfs_blob_manifests")) events.push("manifest:staged");
+ if (sql.includes("state = 'deleting'")) events.push("manifest:deleting");
+ if (sql.includes("DELETE FROM gfs_blob_manifests")) events.push("manifest:removed");
+ return { rows: [] };
+ },
+ };
+ const blobs = new BlobStore(dir, "writer", async path => {
+ events.push(`sync:${path}`);
+ if (path.endsWith(generation) && failFirstBlobSync) {
+ failFirstBlobSync = false;
+ throw new Error("blob fsync failed");
+ }
+ if (path.endsWith(rid)) throw cleanupSyncFailure;
+ });
+
+ try {
+ await expect(
+ stageVerifiedBlob(
+ new PgBlobStagingStore(db),
+ blobs,
+ {
+ generation: () => generation,
+ requestId: () => "22222222-2222-4222-8222-222222222222",
+ },
+ resourceId,
+ Buffer.from("content")
+ )
+ ).rejects.toMatchObject({
+ name: BlobWriteCleanupError.name,
+ cleanupErrors: expect.arrayContaining([cleanupSyncFailure]),
+ });
+
+ expect(events).toContain("manifest:staged");
+ expect(events).not.toContain("manifest:deleting");
+ expect(events).not.toContain("manifest:removed");
+ expect(existsSync(resolveBlobKeyPath(dir, `${rid}/${generation}`))).toBe(false);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/gfs-controller/src/db/blobStaging.test.ts b/gfs-controller/src/db/blobStaging.test.ts
new file mode 100644
index 000000000..9f0ac9c05
--- /dev/null
+++ b/gfs-controller/src/db/blobStaging.test.ts
@@ -0,0 +1,339 @@
+import { createHash } from "node:crypto";
+import { describe, expect, it } from "vitest";
+import { GfsMetrics } from "../metrics";
+import {
+ PgBlobStagingStore,
+ reconcileExpiredBlobs,
+ stageVerifiedBlob,
+ type ManifestQueryable,
+} from "./blobStaging";
+
+class FakeDb implements ManifestQueryable {
+ calls: Array<{ sql: string; values: unknown[] }> = [];
+ responses: Record<string, unknown>[][] = [];
+ failReferenceProbe = false;
+ failOrphanResample = false;
+ orphanSamples = 0;
+ async query(sql: string, values: unknown[] = []) {
+ this.calls.push({ sql, values });
+ if (sql.includes("count(*)::bigint")) {
+ this.orphanSamples += 1;
+ if (this.failOrphanResample && this.orphanSamples > 1) {
+ throw new Error("resample unavailable");
+ }
+ }
+ if (this.failReferenceProbe && sql.includes("UPDATE gfs_blob_manifests AS manifest")) {
+ throw new Error("db unavailable");
+ }
+ return { rows: this.responses.shift() ?? [] };
+ }
+}
+
+const CANDIDATE = {
+ blob_key: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/11111111-1111-4111-8111-111111111111",
+ request_id: "22222222-2222-4222-8222-222222222222",
+ resource_id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
+ candidate_kind: "generation",
+ content_sha256: "a".repeat(64),
+ bytes: "7",
+ state: "staged",
+};
+
+describe("PgBlobStagingStore", () => {
+ it("records candidates as staged and commits them only in the caller transaction", async () => {
+ const db = new FakeDb();
+ const store = new PgBlobStagingStore(db);
+ await store.recordStaged({
+ blobKey: String(CANDIDATE.blob_key),
+ requestId: String(CANDIDATE.request_id),
+ resourceId: String(CANDIDATE.resource_id),
+ candidateKind: "generation",
+ contentSha256: String(CANDIDATE.content_sha256),
+ bytes: 7,
+ });
+ db.responses.push([{ blob_key: CANDIDATE.blob_key }]);
+ await store.markCommitted(db, String(CANDIDATE.blob_key));
+ expect(db.calls[0].sql).toContain("'staged'");
+ expect(db.calls[1].sql).toContain("state = 'committed'");
+ });
+
+ it("never writes physical bytes when durable manifest reservation fails", async () => {
+ const db: ManifestQueryable = {
+ query: async () => {
+ throw new Error("manifest unavailable");
+ },
+ };
+ let writes = 0;
+ await expect(
+ stageVerifiedBlob(
+ new PgBlobStagingStore(db),
+ {
+ writeImmutable: async () => {
+ writes += 1;
+ throw new Error("must not run");
+ },
+ verify: async () => undefined,
+ deleteByKey: async () => undefined,
+ deleteLegacyFlat: async () => undefined,
+ },
+ { generation: () => "11111111-1111-4111-8111-111111111111", requestId: () => String(CANDIDATE.request_id) },
+ String(CANDIDATE.resource_id),
+ Buffer.from("content")
+ )
+ ).rejects.toThrow("manifest unavailable");
+ expect(writes).toBe(0);
+ });
+
+ it("rejects invalid generated keys before manifest SQL", async () => {
+ const db = new FakeDb();
+ await expect(
+ stageVerifiedBlob(
+ new PgBlobStagingStore(db),
+ {
+ writeImmutable: async () => { throw new Error("must not write"); },
+ verify: async () => undefined,
+ deleteByKey: async () => undefined,
+ deleteLegacyFlat: async () => undefined,
+ },
+ { generation: () => "../escape", requestId: () => String(CANDIDATE.request_id) },
+ String(CANDIDATE.resource_id),
+ Buffer.from("content")
+ )
+ ).rejects.toMatchObject({ code: "path_invalid" });
+ expect(db.calls).toEqual([]);
+ });
+
+ it("retains the create/replace manifest and never deletes after pre-return EIO", async () => {
+ const db = new FakeDb();
+ let deletes = 0;
+ await expect(
+ stageVerifiedBlob(
+ new PgBlobStagingStore(db),
+ {
+ writeImmutable: async () => {
+ throw Object.assign(new Error("disk write failed"), { code: "EIO" });
+ },
+ verify: async () => undefined,
+ deleteByKey: async () => {
+ deletes += 1;
+ },
+ deleteLegacyFlat: async () => undefined,
+ },
+ { generation: () => "11111111-1111-4111-8111-111111111111", requestId: () => String(CANDIDATE.request_id) },
+ String(CANDIDATE.resource_id),
+ Buffer.from("content")
+ )
+ ).rejects.toMatchObject({ code: "EIO" });
+ expect(deletes).toBe(0);
+ expect(db.calls[0].sql).toContain("'staged'");
+ expect(db.calls.some(call => call.sql.includes("state = 'deleting'"))).toBe(false);
+ expect(db.calls.some(call => call.sql.includes("DELETE FROM gfs_blob_manifests"))).toBe(false);
+ });
+
+ it.each([false, true])(
+ "durably handles an owned create/replace candidate when cleanup failure is %s",
+ async cleanupFails => {
+ const db = new FakeDb();
+ let deletes = 0;
+ await expect(
+ stageVerifiedBlob(
+ new PgBlobStagingStore(db),
+ {
+ writeImmutable: async () => ({
+ blobKey: String(CANDIDATE.blob_key),
+ bytes: 7,
+ contentSha256: createHash("sha256").update("content").digest("hex"),
+ }),
+ verify: async () => { throw new Error("verification failed"); },
+ deleteByKey: async () => {
+ deletes += 1;
+ if (cleanupFails) throw new Error("cleanup failed");
+ },
+ deleteLegacyFlat: async () => undefined,
+ },
+ { generation: () => "11111111-1111-4111-8111-111111111111", requestId: () => String(CANDIDATE.request_id) },
+ String(CANDIDATE.resource_id),
+ Buffer.from("content")
+ )
+ ).rejects.toThrow("verification failed");
+ expect(deletes).toBe(1);
+ expect(db.calls.some(call => call.sql.includes("state = 'deleting'"))).toBe(true);
+ expect(db.calls.some(call => call.sql.includes("DELETE FROM gfs_blob_manifests"))).toBe(!cleanupFails);
+ }
+ );
+
+ it("never deletes a generation that writeImmutable reports as EEXIST", async () => {
+ const db = new FakeDb();
+ let deletes = 0;
+ await expect(
+ stageVerifiedBlob(
+ new PgBlobStagingStore(db),
+ {
+ writeImmutable: async () => {
+ throw Object.assign(new Error("generation exists"), { code: "EEXIST" });
+ },
+ verify: async () => undefined,
+ deleteByKey: async () => {
+ deletes += 1;
+ },
+ deleteLegacyFlat: async () => undefined,
+ },
+ { generation: () => "11111111-1111-4111-8111-111111111111", requestId: () => String(CANDIDATE.request_id) },
+ String(CANDIDATE.resource_id),
+ Buffer.from("content")
+ )
+ ).rejects.toMatchObject({ code: "EEXIST" });
+ expect(deletes).toBe(0);
+ expect(db.calls.some(call => call.sql.includes("state = 'deleting'"))).toBe(false);
+ });
+
+ it("resolves an ambiguous publication only from the committed resource pointer", async () => {
+ const db = new FakeDb();
+ db.responses.push([{ resource_id: CANDIDATE.resource_id, blob_key: CANDIDATE.blob_key }]);
+ const row = await new PgBlobStagingStore(db).resolvePublished(
+ "main",
+ String(CANDIDATE.resource_id),
+ String(CANDIDATE.blob_key)
+ );
+ expect(row?.blob_key).toBe(CANDIDATE.blob_key);
+ expect(db.calls[0].sql).toContain("blob_key = $3");
+ });
+});
+
+describe("reconcileExpiredBlobs", () => {
+ it("deletes only an expired candidate freshly proven unreferenced", async () => {
+ const db = new FakeDb();
+ db.responses.push(
+ [{ count: "1", bytes: "7" }],
+ [CANDIDATE],
+ [{ referenced: false }],
+ [],
+ [],
+ [],
+ [{ count: "0", bytes: "0" }]
+ );
+ const deleted: string[] = [];
+ const metrics = new GfsMetrics();
+ const result = await reconcileExpiredBlobs(
+ new PgBlobStagingStore(db),
+ { deleteByKey: async key => void deleted.push(key), deleteLegacyFlat: async () => undefined },
+ metrics,
+ { olderThanMs: 60_000, limit: 10 }
+ );
+ expect(result).toMatchObject({ candidates: 1, deleted: 1, failures: 0 });
+ expect(deleted).toEqual([CANDIDATE.blob_key]);
+ expect(metrics.snapshot()).toMatchObject({ orphanCandidates: 0, orphanBytes: 0 });
+ });
+
+ it("retains a referenced candidate", async () => {
+ const db = new FakeDb();
+ db.responses.push(
+ [{ count: "1", bytes: "7" }],
+ [CANDIDATE],
+ [{ referenced: true }],
+ [],
+ [],
+ [],
+ [{ count: "0", bytes: "0" }]
+ );
+ const deleted: string[] = [];
+ const result = await reconcileExpiredBlobs(
+ new PgBlobStagingStore(db),
+ { deleteByKey: async key => void deleted.push(key), deleteLegacyFlat: async () => undefined },
+ new GfsMetrics(),
+ { olderThanMs: 1, limit: 10 }
+ );
+ expect(result).toMatchObject({ deleted: 0, retained: 1 });
+ expect(deleted).toEqual([]);
+ });
+
+ it("retains and reports a candidate when the fresh DB proof is unavailable", async () => {
+ const db = new FakeDb();
+ db.responses.push([{ count: "1", bytes: "7" }], [{ count: "1", bytes: "7" }]);
+ db.failReferenceProbe = true;
+ const metrics = new GfsMetrics();
+ const result = await reconcileExpiredBlobs(
+ new PgBlobStagingStore(db),
+ { deleteByKey: async () => undefined, deleteLegacyFlat: async () => undefined },
+ metrics,
+ { olderThanMs: 1, limit: 10 }
+ );
+ expect(result).toMatchObject({ deleted: 0, retained: 1, failures: 1 });
+ expect(metrics.snapshot().blobCleanupFailures).toBe(1);
+ expect(metrics.snapshot()).toMatchObject({ orphanCandidates: 1, orphanBytes: 7 });
+ });
+
+ it("reports aggregate orphan count and bytes independently of the cleanup batch", async () => {
+ const db = new FakeDb();
+ db.responses.push(
+ [{ count: "5", bytes: "35" }],
+ [CANDIDATE],
+ [{ referenced: false }],
+ [],
+ [],
+ [{ count: "4", bytes: "28" }]
+ );
+ const metrics = new GfsMetrics();
+ const result = await reconcileExpiredBlobs(
+ new PgBlobStagingStore(db),
+ { deleteByKey: async () => undefined, deleteLegacyFlat: async () => undefined },
+ metrics,
+ { olderThanMs: 1, limit: 1 }
+ );
+ expect(result).toMatchObject({ candidates: 5, candidateBytes: 35, deleted: 1, retained: 4 });
+ expect(metrics.snapshot()).toMatchObject({ orphanCandidates: 4, orphanBytes: 28 });
+ expect(db.calls[0].sql).toContain("count(*)::bigint");
+ expect(db.calls[0].sql).not.toContain("LIMIT");
+ });
+
+ it("retains the last confirmed gauges and records failure when post-pass resampling fails", async () => {
+ const db = new FakeDb();
+ db.failOrphanResample = true;
+ db.responses.push([{ count: "3", bytes: "21" }], [], []);
+ const metrics = new GfsMetrics();
+ const result = await reconcileExpiredBlobs(
+ new PgBlobStagingStore(db),
+ { deleteByKey: async () => undefined, deleteLegacyFlat: async () => undefined },
+ metrics,
+ { olderThanMs: 1, limit: 1 }
+ );
+ expect(result.failures).toBe(1);
+ expect(metrics.snapshot()).toMatchObject({
+ orphanCandidates: 3,
+ orphanBytes: 21,
+ blobCleanupFailures: 1,
+ });
+ });
+
+ it("deletes a legacy flat blob only from an explicit unreferenced ledger row", async () => {
+ const legacy = { ...CANDIDATE, blob_key: "a".repeat(32), candidate_kind: "legacy_flat", content_sha256: null };
+ const db = new FakeDb();
+ db.responses.push([{ count: "1", bytes: "7" }], [legacy], [{ referenced: false }], [], [], []);
+ const deleted: string[] = [];
+ await reconcileExpiredBlobs(
+ new PgBlobStagingStore(db),
+ { deleteByKey: async () => { throw new Error("generation delete must not run"); }, deleteLegacyFlat: async id => void deleted.push(id) },
+ new GfsMetrics(),
+ { olderThanMs: 1, limit: 1 }
+ );
+ expect(deleted).toEqual([CANDIDATE.resource_id]);
+ expect(db.calls[1].sql).toContain("candidate.candidate_kind = 'legacy_flat'");
+ });
+
+ it("claims with one locked unreferenced transition so publication cannot race deletion", async () => {
+ const db = new FakeDb();
+ db.responses.push([CANDIDATE]);
+ await new PgBlobStagingStore(db).claimExpiredCandidate(60_000);
+ const sql = db.calls[0].sql;
+ expect(sql).toContain("FOR UPDATE SKIP LOCKED");
+ expect(sql).toContain("NOT EXISTS");
+ expect(sql).toContain("state = 'deleting'");
+ });
+
+ it("reconciles committed and collision-staged manifests only when metadata references them", async () => {
+ const db = new FakeDb();
+ await new PgBlobStagingStore(db).removeCommittedMetadata(10);
+ expect(db.calls[0].sql).toContain("state IN ('committed', 'staged')");
+ expect(db.calls[0].sql).toContain("EXISTS");
+ });
+});
diff --git a/gfs-controller/src/db/blobStaging.ts b/gfs-controller/src/db/blobStaging.ts
new file mode 100644
index 000000000..f8dfa2e5b
--- /dev/null
+++ b/gfs-controller/src/db/blobStaging.ts
@@ -0,0 +1,358 @@
+import { createHash } from "node:crypto";
+import type { Readable } from "node:stream";
+import type { ImmutableWriteOptions } from "../storage/blobStore";
+import { generationBlobKey } from "../storage/paths";
+import { withDeadlineTransaction, type DeadlineBudget, type DeadlineClient } from "./deadlineQuery";
+import { matchesPublishedTree, type PublishedTreeRef } from "./publishedTree";
+export { reconcileExpiredBlobs, type ReconcileResult } from "./blobReconciliation";
+export { stageCopiedBlob, type CopyBlobSource, type StageCopiedBlobInput } from "./copyBlobStaging";
+export type { PublishedTreeRef } from "./publishedTree";
+
+export type BlobManifestState = "staged" | "committed" | "deleting";
+
+export interface ManifestRow {
+ blobKey: string;
+ requestId: string;
+ resourceId: string;
+ candidateKind: "generation" | "legacy_flat";
+ contentSha256: string | null;
+ bytes: number;
+ state: BlobManifestState;
+}
+
+export interface ManifestQueryable {
+ query(text: string, values?: unknown[]): Promise<{ rows: Record<string, unknown>[] }>;
+ connect?: () => Promise<DeadlineClient>;
+}
+
+export type ManifestQueryBudget = DeadlineBudget;
+
+async function manifestQuery(
+ db: ManifestQueryable,
+ text: string,
+ values: unknown[],
+ budget?: ManifestQueryBudget,
+ readOnly = false
+): Promise<{ rows: Record<string, unknown>[] }> {
+ if (!budget) return db.query(text, values);
+ return withDeadlineTransaction(db, budget, readOnly, client => client.query(text, values));
+}
+
+export interface CleanupBlobStore {
+ deleteByKey(blobKey: string): Promise<void>;
+ deleteLegacyFlat(resourceId: string): Promise<void>;
+}
+
+export interface StagingBlobStore extends CleanupBlobStore {
+ writeImmutable(
+ resourceId: string,
+ generation: string,
+ data: Readable | Buffer,
+ options?: ImmutableWriteOptions
+ ): Promise<{ blobKey: string; bytes: number; contentSha256: string }>;
+ verify(blobKey: string, expectedBytes: number, expectedSha256: string, options?: ImmutableWriteOptions): Promise<void>;
+}
+
+function mapManifest(row: Record<string, unknown>): ManifestRow {
+ return {
+ blobKey: String(row.blob_key),
+ requestId: String(row.request_id),
+ resourceId: String(row.resource_id),
+ candidateKind: String(row.candidate_kind) === "legacy_flat" ? "legacy_flat" : "generation",
+ contentSha256: row.content_sha256 == null ? null : String(row.content_sha256),
+ bytes: Number(row.bytes),
+ state: String(row.state) as BlobManifestState,
+ };
+}
+
+export class PgBlobStagingStore {
+ constructor(private readonly db: ManifestQueryable) {}
+
+ async recordStaged(manifest: Omit<ManifestRow, "state">, budget?: ManifestQueryBudget): Promise<void> {
+ await manifestQuery(this.db,
+ `INSERT INTO gfs_blob_manifests
+ (blob_key, request_id, resource_id, candidate_kind, content_sha256, bytes, state)
+ VALUES ($1, $2, $3, $4, $5, $6, 'staged')`,
+ [
+ manifest.blobKey,
+ manifest.requestId,
+ manifest.resourceId,
+ manifest.candidateKind,
+ manifest.contentSha256,
+ manifest.bytes,
+ ],
+ budget
+ );
+ budget?.signal?.throwIfAborted();
+ }
+
+ async markCommitted(client: ManifestQueryable, blobKey: string): Promise<void> {
+ const result = await client.query(
+ `UPDATE gfs_blob_manifests
+ SET state = 'committed', updated_at = now()
+ WHERE blob_key = $1 AND state = 'staged'
+ RETURNING blob_key`,
+ [blobKey]
+ );
+ if (result.rows.length !== 1) throw new Error("staged blob manifest missing");
+ }
+
+ async markCommittedMany(client: ManifestQueryable, requestId: string, blobKeys: readonly string[]): Promise<void> {
+ if (blobKeys.length === 0) return;
+ const unique = [...new Set(blobKeys)];
+ if (unique.length !== blobKeys.length) throw new Error("duplicate staged blob key");
+ const result = await client.query(
+ `UPDATE gfs_blob_manifests
+ SET state = 'committed', updated_at = now()
+ WHERE request_id = $1 AND blob_key = ANY($2::text[]) AND state = 'staged'
+ RETURNING blob_key`,
+ [requestId, unique]
+ );
+ const changed = new Set(result.rows.map(row => String(row.blob_key)));
+ if (changed.size !== unique.length || unique.some(key => !changed.has(key))) {
+ throw new Error("staged blob manifest set is incomplete");
+ }
+ }
+
+ async removeCommitted(blobKey: string): Promise<void> {
+ await this.db.query(
+ `DELETE FROM gfs_blob_manifests WHERE blob_key = $1 AND state = 'committed'`,
+ [blobKey]
+ );
+ }
+
+ async removeCommittedMany(requestId: string, blobKeys: readonly string[], budget?: ManifestQueryBudget): Promise<void> {
+ if (blobKeys.length === 0) return;
+ const unique = [...new Set(blobKeys)];
+ if (unique.length !== blobKeys.length) throw new Error("duplicate committed blob key");
+ const result = await manifestQuery(this.db,
+ `DELETE FROM gfs_blob_manifests
+ WHERE request_id = $1 AND blob_key = ANY($2::text[]) AND state = 'committed'
+ RETURNING blob_key`,
+ [requestId, unique],
+ budget
+ );
+ const removed = new Set(result.rows.map(row => String(row.blob_key)));
+ if (removed.size !== unique.length || unique.some(key => !removed.has(key))) {
+ throw new Error("committed blob manifest set is incomplete");
+ }
+ }
+
+ async markSuperseded(
+ client: ManifestQueryable,
+ manifest: Omit<ManifestRow, "requestId" | "state" | "candidateKind">
+ ): Promise<void> {
+ await client.query(
+ `INSERT INTO gfs_blob_manifests
+ (blob_key, request_id, resource_id, candidate_kind, content_sha256, bytes, state)
+ VALUES ($1, gen_random_uuid(), $2, 'generation', $3, $4, 'deleting')
+ ON CONFLICT (blob_key) DO UPDATE
+ SET state = 'deleting', updated_at = now()`,
+ [manifest.blobKey, manifest.resourceId, manifest.contentSha256, manifest.bytes]
+ );
+ }
+
+ async markLegacySuperseded(
+ client: ManifestQueryable,
+ resourceId: string,
+ bytes: number
+ ): Promise<void> {
+ const blobKey = resourceId.replaceAll("-", "").toLowerCase();
+ await client.query(
+ `INSERT INTO gfs_blob_manifests
+ (blob_key, request_id, resource_id, candidate_kind, content_sha256, bytes, state)
+ VALUES ($1, gen_random_uuid(), $2, 'legacy_flat', NULL, $3, 'deleting')
+ ON CONFLICT (blob_key) DO UPDATE
+ SET state = 'deleting', updated_at = now()`,
+ [blobKey, resourceId, bytes]
+ );
+ }
+
+ async markDeleting(blobKey: string, budget?: ManifestQueryBudget): Promise<void> {
+ await manifestQuery(this.db,
+ `UPDATE gfs_blob_manifests SET state = 'deleting', updated_at = now() WHERE blob_key = $1`,
+ [blobKey],
+ budget
+ );
+ }
+
+ async restoreCommitted(blobKey: string): Promise<void> {
+ await this.db.query(
+ `UPDATE gfs_blob_manifests SET state = 'committed', updated_at = now()
+ WHERE blob_key = $1 AND state = 'deleting'`,
+ [blobKey]
+ );
+ }
+
+ async remove(blobKey: string, budget?: ManifestQueryBudget): Promise<void> {
+ await manifestQuery(this.db,
+ `DELETE FROM gfs_blob_manifests WHERE blob_key = $1`,
+ [blobKey],
+ budget
+ );
+ }
+
+ async resolvePublished(
+ drive: string,
+ resourceId: string,
+ blobKey: string
+ ): Promise<Record<string, unknown> | null> {
+ const result = await this.db.query(
+ `SELECT resource_id, drive, parent_resource_id, name, kind, path_cache,
+ version, bytes, blob_key, content_sha256, deleted_at
+ FROM gfs_resources
+ WHERE drive = $1 AND resource_id = $2 AND blob_key = $3`,
+ [drive, resourceId, blobKey]
+ );
+ return result.rows[0] ?? null;
+ }
+
+ async resolvePublishedTree(drive: string, expected: readonly PublishedTreeRef[], budget?: ManifestQueryBudget): Promise<Record<string, unknown>[] | null> {
+ if (expected.length === 0) return [];
+ const ids = expected.map(item => item.resourceId);
+ const keys = expected.flatMap(item => item.blobKey === null ? [] : [item.blobKey]);
+ if (new Set(ids).size !== ids.length || new Set(keys).size !== keys.length) {
+ throw new Error("duplicate expected published resource");
+ }
+ const result = await manifestQuery(this.db,
+ `SELECT resource_id, drive, parent_resource_id, name, kind, path_cache,
+ version, bytes, blob_key, content_sha256, deleted_at
+ FROM gfs_resources
+ WHERE drive = $1 AND resource_id = ANY($2::uuid[])`,
+ [drive, ids],
+ budget,
+ true
+ );
+ return matchesPublishedTree(drive, expected, result.rows) ? result.rows : null;
+ }
+
+ async orphanTotals(olderThanMs: number): Promise<{ count: number; bytes: number }> {
+ const result = await this.db.query(
+ `SELECT count(*)::bigint AS count, coalesce(sum(candidate.bytes), 0)::bigint AS bytes
+ FROM gfs_blob_manifests AS candidate
+ WHERE candidate.state IN ('staged', 'deleting')
+ AND candidate.updated_at < now() - ($1::bigint * interval '1 millisecond')
+ AND NOT EXISTS (
+ SELECT 1 FROM gfs_resources AS resource
+ WHERE (candidate.candidate_kind = 'generation' AND resource.blob_key = candidate.blob_key)
+ OR (candidate.candidate_kind = 'legacy_flat'
+ AND resource.resource_id = candidate.resource_id AND resource.blob_key IS NULL)
+ )`,
+ [olderThanMs]
+ );
+ return { count: Number(result.rows[0]?.count ?? 0), bytes: Number(result.rows[0]?.bytes ?? 0) };
+ }
+
+ async claimExpiredCandidate(olderThanMs: number): Promise<ManifestRow | null> {
+ const result = await this.db.query(
+ `UPDATE gfs_blob_manifests AS manifest
+ SET state = 'deleting', updated_at = now()
+ WHERE manifest.blob_key = (
+ SELECT candidate.blob_key
+ FROM gfs_blob_manifests AS candidate
+ WHERE candidate.state IN ('staged', 'deleting')
+ AND candidate.updated_at < now() - ($1::bigint * interval '1 millisecond')
+ AND NOT EXISTS (
+ SELECT 1 FROM gfs_resources AS resource
+ WHERE (candidate.candidate_kind = 'generation' AND resource.blob_key = candidate.blob_key)
+ OR (candidate.candidate_kind = 'legacy_flat'
+ AND resource.resource_id = candidate.resource_id AND resource.blob_key IS NULL)
+ )
+ ORDER BY candidate.updated_at, candidate.blob_key
+ FOR UPDATE SKIP LOCKED
+ LIMIT 1
+ )
+ RETURNING manifest.blob_key, manifest.request_id, manifest.resource_id,
+ manifest.candidate_kind, manifest.content_sha256, manifest.bytes, manifest.state`,
+ [olderThanMs]
+ );
+ return result.rows[0] ? mapManifest(result.rows[0]) : null;
+ }
+
+ async referenced(candidate: ManifestRow): Promise<boolean> {
+ const result = await this.db.query(
+ `SELECT EXISTS (
+ SELECT 1 FROM gfs_resources
+ WHERE ($2 = 'generation' AND blob_key = $1)
+ OR ($2 = 'legacy_flat' AND resource_id = $3 AND blob_key IS NULL)
+ ) AS referenced`,
+ [candidate.blobKey, candidate.candidateKind, candidate.resourceId]
+ );
+ return result.rows[0]?.referenced === true;
+ }
+
+ async removeCommittedMetadata(limit: number): Promise<number> {
+ const result = await this.db.query(
+ `DELETE FROM gfs_blob_manifests AS manifest
+ WHERE manifest.blob_key IN (
+ SELECT candidate.blob_key
+ FROM gfs_blob_manifests AS candidate
+ WHERE candidate.state IN ('committed', 'staged')
+ AND EXISTS (SELECT 1 FROM gfs_resources r WHERE r.blob_key = candidate.blob_key)
+ ORDER BY candidate.updated_at, candidate.blob_key
+ FOR UPDATE SKIP LOCKED
+ LIMIT $1
+ )
+ RETURNING manifest.blob_key`,
+ [limit]
+ );
+ return result.rows.length;
+ }
+}
+
+export async function discardCandidate(
+ manifests: PgBlobStagingStore,
+ blobs: CleanupBlobStore,
+ blobKey: string,
+ budget?: ManifestQueryBudget
+): Promise<void> {
+ await manifests.markDeleting(blobKey, budget);
+ try {
+ await blobs.deleteByKey(blobKey);
+ } catch (err) {
+ if ((err as { code?: string }).code !== "not_found") throw err;
+ }
+ await manifests.remove(blobKey, budget);
+}
+
+export async function stageVerifiedBlob(
+ manifests: PgBlobStagingStore,
+ blobs: StagingBlobStore,
+ ids: { generation: () => string; requestId: () => string },
+ resourceId: string,
+ content: Buffer
+): Promise<{ blobKey: string; bytes: number; contentSha256: string }> {
+ const generation = ids.generation();
+ const blobKey = generationBlobKey(resourceId, generation);
+ const contentSha256 = createHash("sha256").update(content).digest("hex");
+ await manifests.recordStaged({
+ blobKey,
+ requestId: ids.requestId(),
+ resourceId,
+ candidateKind: "generation",
+ contentSha256,
+ bytes: content.length,
+ });
+ let physicalCandidateOwned = false;
+ try {
+ const written = await blobs.writeImmutable(resourceId, generation, content);
+ physicalCandidateOwned = true;
+ if (
+ written.blobKey !== blobKey ||
+ written.bytes !== content.length ||
+ written.contentSha256 !== contentSha256
+ ) {
+ throw new Error("staged blob verification mismatch");
+ }
+ await blobs.verify(blobKey, content.length, contentSha256);
+ return written;
+ } catch (err) {
+ // A failure before writeImmutable returns does not prove that this request
+ // owns the physical key. Keep the staged manifest so reconciliation can
+ // make a fresh durable reference check without risking pre-existing bytes.
+ if (physicalCandidateOwned) {
+ await discardCandidate(manifests, blobs, blobKey).catch(() => undefined);
+ }
+ throw err;
+ }
+}
diff --git a/gfs-controller/src/db/copyBlobStaging.test.ts b/gfs-controller/src/db/copyBlobStaging.test.ts
new file mode 100644
index 000000000..881070936
--- /dev/null
+++ b/gfs-controller/src/db/copyBlobStaging.test.ts
@@ -0,0 +1,330 @@
+import { createHash } from "node:crypto";
+import { existsSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { Readable } from "node:stream";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { BlobStore, BlobVerificationError, BlobWriteCleanupError } from "../storage/blobStore";
+import { resolveBlobKeyPath } from "../storage/paths";
+import { PgBlobStagingStore, type ManifestQueryable, type PublishedTreeRef } from "./blobStaging";
+import { stageCopiedBlob } from "./copyBlobStaging";
+
+const REQUEST = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
+const RID1 = "11111111-1111-4111-8111-111111111111";
+const RID2 = "22222222-2222-4222-8222-222222222222";
+const GEN1 = "33333333-3333-4333-8333-333333333333";
+const GEN2 = "44444444-4444-4444-8444-444444444444";
+const digest = (bytes: Buffer) => createHash("sha256").update(bytes).digest("hex");
+const key = (rid: string, gen: string) => `${rid.replaceAll("-", "")}/${gen}`;
+const published = (
+ resourceId: string,
+ blobKey: string | null,
+ overrides: Partial<PublishedTreeRef> = {}
+): PublishedTreeRef => ({
+ resourceId,
+ parentResourceId: null,
+ name: "copied",
+ kind: blobKey === null ? "directory" : "file",
+ pathCache: "/copied",
+ version: 1,
+ bytes: blobKey === null ? 0n : 3n,
+ blobKey,
+ contentSha256: blobKey === null ? null : "a".repeat(64),
+ ...overrides,
+});
+const dbRow = (item: PublishedTreeRef, overrides: Record<string, unknown> = {}) => ({
+ resource_id: item.resourceId,
+ drive: "main",
+ parent_resource_id: item.parentResourceId,
+ name: item.name,
+ kind: item.kind,
+ path_cache: item.pathCache,
+ version: item.version,
+ bytes: item.bytes.toString(),
+ blob_key: item.blobKey,
+ content_sha256: item.contentSha256,
+ deleted_at: null,
+ ...overrides,
+});
+
+class FakeDb implements ManifestQueryable {
+ calls: Array<{ sql: string; values: unknown[] }> = [];
+ responses: Record<string, unknown>[][] = [];
+ async query(sql: string, values: unknown[] = []) {
+ this.calls.push({ sql, values });
+ return { rows: this.responses.shift() ?? [] };
+ }
+ async connect() {
+ return {
+ query: async (sql: string, values: unknown[] = []) => {
+ if (sql === "BEGIN" || sql === "BEGIN READ ONLY" || sql === "COMMIT" || sql === "ROLLBACK" || sql.includes("set_config('statement_timeout'")) {
+ this.calls.push({ sql, values });
+ return { rows: [] };
+ }
+ return this.query(sql, values);
+ },
+ release: () => undefined,
+ };
+ }
+}
+
+describe("recursive copy blob staging", () => {
+ let dir: string;
+ beforeEach(() => { dir = mkdtempSync(join(tmpdir(), "gfs-copy-stage-")); });
+ afterEach(() => { rmSync(dir, { recursive: true, force: true }); });
+
+ it("stages every file under the caller's one common request id", async () => {
+ const db = new FakeDb();
+ const manifests = new PgBlobStagingStore(db);
+ const blobs = new BlobStore(dir, "writer");
+ for (const [destinationResourceId, generation, bytes] of [
+ [RID1, GEN1, Buffer.from("one")],
+ [RID2, GEN2, Buffer.from("two")],
+ ] as const) {
+ await stageCopiedBlob(manifests, blobs, {
+ requestId: REQUEST,
+ destinationResourceId,
+ generation,
+ source: { kind: "generation", stream: Readable.from(bytes) },
+ expectedBytes: bytes.length,
+ expectedSha256: digest(bytes),
+ deadlineAtMs: Date.now() + 10_000,
+ });
+ }
+ const inserts = db.calls.filter(call => call.sql.includes("INSERT INTO gfs_blob_manifests"));
+ expect(inserts).toHaveLength(2);
+ expect(inserts.map(call => call.values[1])).toEqual([REQUEST, REQUEST]);
+ });
+
+ it("requires legacy preflight to reopen a fresh stream", async () => {
+ const bytes = Buffer.from("legacy bytes");
+ let reopens = 0;
+ const result = await stageCopiedBlob(new PgBlobStagingStore(new FakeDb()), new BlobStore(dir, "writer"), {
+ requestId: REQUEST,
+ destinationResourceId: RID1,
+ generation: GEN1,
+ source: { kind: "legacy_flat", reopen: async () => { reopens += 1; return Readable.from(bytes); } },
+ expectedBytes: bytes.length,
+ expectedSha256: digest(bytes),
+ deadlineAtMs: Date.now() + 10_000,
+ });
+ expect(reopens).toBe(1);
+ expect(result.contentSha256).toBe(digest(bytes));
+ });
+
+ it.each([
+ { expectedBytes: 99, expectedSha256: digest(Buffer.from("actual")) },
+ { expectedBytes: 6, expectedSha256: "0".repeat(64) },
+ ])("rejects source size/digest drift and durably cleans the candidate", async expected => {
+ const db = new FakeDb();
+ const physical = resolveBlobKeyPath(dir, key(RID1, GEN1));
+ await expect(stageCopiedBlob(new PgBlobStagingStore(db), new BlobStore(dir, "writer"), {
+ requestId: REQUEST,
+ destinationResourceId: RID1,
+ generation: GEN1,
+ source: { kind: "generation", stream: Readable.from(Buffer.from("actual")) },
+ ...expected,
+ deadlineAtMs: Date.now() + 10_000,
+ })).rejects.toMatchObject({ code: "precondition_failed" });
+ expect(existsSync(physical)).toBe(false);
+ expect(db.calls.some(call => call.sql.includes("state = 'deleting'"))).toBe(true);
+ expect(db.calls.some(call => call.sql.includes("DELETE FROM gfs_blob_manifests"))).toBe(true);
+ });
+
+ it("retains the staged manifest when the physical write fails before returning", async () => {
+ const db = new FakeDb();
+ const blobs = new BlobStore(dir, "writer", async () => { throw new Error("sync failed"); });
+ await expect(stageCopiedBlob(new PgBlobStagingStore(db), blobs, {
+ requestId: REQUEST,
+ destinationResourceId: RID1,
+ generation: GEN1,
+ source: { kind: "generation", stream: Readable.from(Buffer.from("actual")) },
+ expectedBytes: 6,
+ expectedSha256: digest(Buffer.from("actual")),
+ deadlineAtMs: Date.now() + 10_000,
+ })).rejects.toBeInstanceOf(BlobWriteCleanupError);
+ expect(db.calls.some(call => call.sql.includes("state = 'deleting'"))).toBe(false);
+ expect(db.calls.some(call => call.sql.includes("DELETE FROM gfs_blob_manifests"))).toBe(false);
+ });
+
+ it.each(["generation write", "legacy reopen"] as const)(
+ "never deletes a pre-existing recursive copy key after %s EIO",
+ async failurePoint => {
+ const bytes = Buffer.from("existing");
+ const physicalStore = new BlobStore(dir, "writer");
+ await physicalStore.writeImmutable(RID1, GEN1, bytes);
+ const db = new FakeDb();
+ let deletes = 0;
+ let writes = 0;
+ const eio = Object.assign(new Error("open failed"), { code: "EIO" });
+ const blobs = {
+ writeImmutable: async () => {
+ writes += 1;
+ throw eio;
+ },
+ verify: async () => undefined,
+ deleteByKey: async (blobKey: string) => {
+ deletes += 1;
+ await physicalStore.deleteByKey(blobKey);
+ },
+ deleteLegacyFlat: async () => undefined,
+ };
+ const source = failurePoint === "generation write"
+ ? { kind: "generation" as const, stream: Readable.from(bytes) }
+ : { kind: "legacy_flat" as const, reopen: async () => { throw eio; } };
+
+ await expect(stageCopiedBlob(new PgBlobStagingStore(db), blobs, {
+ requestId: REQUEST,
+ destinationResourceId: RID1,
+ generation: GEN1,
+ source,
+ expectedBytes: bytes.length,
+ expectedSha256: digest(bytes),
+ deadlineAtMs: Date.now() + 10_000,
+ })).rejects.toMatchObject({ code: "EIO" });
+ expect(writes).toBe(failurePoint === "generation write" ? 1 : 0);
+ expect(deletes).toBe(0);
+ expect(existsSync(resolveBlobKeyPath(dir, key(RID1, GEN1)))).toBe(true);
+ expect(db.calls.some(call => call.sql.includes("state = 'deleting'"))).toBe(false);
+ expect(db.calls.some(call => call.sql.includes("DELETE FROM gfs_blob_manifests"))).toBe(false);
+ }
+ );
+
+ it.each([false, true])(
+ "durably handles an owned recursive copy candidate when cleanup failure is %s",
+ async cleanupFails => {
+ const bytes = Buffer.from("actual");
+ const db = new FakeDb();
+ let deletes = 0;
+ await expect(stageCopiedBlob(new PgBlobStagingStore(db), {
+ writeImmutable: async () => ({ blobKey: key(RID1, GEN1), bytes: bytes.length, contentSha256: digest(bytes) }),
+ verify: async () => { throw new BlobVerificationError(); },
+ deleteByKey: async () => {
+ deletes += 1;
+ if (cleanupFails) throw new Error("cleanup failed");
+ },
+ deleteLegacyFlat: async () => undefined,
+ }, {
+ requestId: REQUEST,
+ destinationResourceId: RID1,
+ generation: GEN1,
+ source: { kind: "generation", stream: Readable.from(bytes) },
+ expectedBytes: bytes.length,
+ expectedSha256: digest(bytes),
+ deadlineAtMs: Date.now() + 10_000,
+ })).rejects.toMatchObject({ code: "precondition_failed" });
+ expect(deletes).toBe(1);
+ expect(db.calls.some(call => call.sql.includes("state = 'deleting'"))).toBe(true);
+ expect(db.calls.some(call => call.sql.includes("DELETE FROM gfs_blob_manifests"))).toBe(!cleanupFails);
+ }
+ );
+
+ it("propagates abort without an unmanifested or partial destination", async () => {
+ const db = new FakeDb();
+ const controller = new AbortController();
+ const stream = Readable.from((async function* () {
+ yield Buffer.from("a");
+ controller.abort();
+ yield Buffer.from("b");
+ })());
+ await expect(stageCopiedBlob(new PgBlobStagingStore(db), new BlobStore(dir, "writer"), {
+ requestId: REQUEST,
+ destinationResourceId: RID1,
+ generation: GEN1,
+ source: { kind: "generation", stream },
+ expectedBytes: 2,
+ expectedSha256: digest(Buffer.from("ab")),
+ deadlineAtMs: Date.now() + 10_000,
+ signal: controller.signal,
+ })).rejects.toThrow();
+ expect(db.calls.some(call => call.sql.includes("INSERT INTO gfs_blob_manifests"))).toBe(true);
+ expect(existsSync(resolveBlobKeyPath(dir, key(RID1, GEN1)))).toBe(false);
+ });
+
+ it("fails an expired operation before reserving a manifest", async () => {
+ const db = new FakeDb();
+ await expect(stageCopiedBlob(new PgBlobStagingStore(db), new BlobStore(dir, "writer"), {
+ requestId: REQUEST,
+ destinationResourceId: RID1,
+ generation: GEN1,
+ source: { kind: "generation", stream: Readable.from(Buffer.from("x")) },
+ expectedBytes: 1,
+ expectedSha256: digest(Buffer.from("x")),
+ deadlineAtMs: 10,
+ now: () => 10,
+ })).rejects.toMatchObject({ code: "precondition_failed" });
+ expect(db.calls).toEqual([]);
+ });
+});
+
+describe("tree manifest publication", () => {
+ it("marks and removes the exact complete candidate set", async () => {
+ const db = new FakeDb();
+ const keys = [key(RID1, GEN1), key(RID2, GEN2)];
+ db.responses.push(keys.map(blob_key => ({ blob_key })), keys.map(blob_key => ({ blob_key })));
+ const store = new PgBlobStagingStore(db);
+ await store.markCommittedMany(db, REQUEST, keys);
+ await store.removeCommittedMany(REQUEST, keys);
+ expect(db.calls[0].values).toEqual([REQUEST, keys]);
+ expect(db.calls[1].values).toEqual([REQUEST, keys]);
+ expect(db.calls[0].sql).toContain("request_id = $1");
+ expect(db.calls[1].sql).toContain("request_id = $1");
+ });
+
+ it("rejects a missing second/last file instead of accepting partial publication", async () => {
+ const db = new FakeDb();
+ const first = published(RID1, key(RID1, GEN1));
+ const second = published(RID2, key(RID2, GEN2));
+ db.responses.push([dbRow(first)]);
+ const result = await new PgBlobStagingStore(db).resolvePublishedTree("main", [
+ first,
+ second,
+ ]);
+ expect(result).toBeNull();
+ });
+
+ it("requires directories as well as files for an exact published tree", async () => {
+ const db = new FakeDb();
+ const directory = published(RID1, null);
+ const file = published(RID2, key(RID2, GEN2), { parentResourceId: RID1, pathCache: "/copied/file", name: "file" });
+ db.responses.push([dbRow(directory), dbRow(file)]);
+ const result = await new PgBlobStagingStore(db).resolvePublishedTree("main", [directory, file]);
+ expect(result).toHaveLength(2);
+ expect(db.calls[0].values).toEqual(["main", [RID1, RID2]]);
+ });
+
+ it.each([
+ ["resourceId", { resource_id: RID2 }],
+ ["parentResourceId", { parent_resource_id: RID2 }],
+ ["name", { name: "wrong" }],
+ ["kind", { kind: "directory" }],
+ ["pathCache", { path_cache: "/wrong" }],
+ ["version", { version: 2 }],
+ ["bytes", { bytes: "4" }],
+ ["blobKey", { blob_key: key(RID2, GEN2) }],
+ ["contentSha256", { content_sha256: "b".repeat(64) }],
+ ])("rejects ambiguous publication when %s differs", async (_field, mismatch) => {
+ const db = new FakeDb();
+ const expected = published(RID1, key(RID1, GEN1));
+ db.responses.push([dbRow(expected, mismatch)]);
+ await expect(new PgBlobStagingStore(db).resolvePublishedTree("main", [expected])).resolves.toBeNull();
+ });
+
+ it("does not mark a same-key manifest belonging to another request", async () => {
+ const db = new FakeDb();
+ const keys = [key(RID1, GEN1), key(RID2, GEN2)];
+ db.responses.push([{ blob_key: keys[0] }]);
+ await expect(new PgBlobStagingStore(db).markCommittedMany(db, REQUEST, keys))
+ .rejects.toThrow("manifest set is incomplete");
+ expect(db.calls[0].values).toEqual([REQUEST, keys]);
+ });
+
+ it("does not silently remove only part of a committed manifest set", async () => {
+ const db = new FakeDb();
+ db.responses.push([{ blob_key: key(RID1, GEN1) }]);
+ await expect(new PgBlobStagingStore(db).removeCommittedMany(REQUEST, [
+ key(RID1, GEN1), key(RID2, GEN2),
+ ])).rejects.toThrow("manifest set is incomplete");
+ expect(db.calls[0].values[0]).toBe(REQUEST);
+ });
+});
diff --git a/gfs-controller/src/db/copyBlobStaging.ts b/gfs-controller/src/db/copyBlobStaging.ts
new file mode 100644
index 000000000..3425c2689
--- /dev/null
+++ b/gfs-controller/src/db/copyBlobStaging.ts
@@ -0,0 +1,85 @@
+import type { Readable } from "node:stream";
+import { GfsError } from "../api/errors";
+import { BlobVerificationError } from "../storage/blobStore";
+import { generationBlobKey } from "../storage/paths";
+import { discardCandidate, type PgBlobStagingStore, type StagingBlobStore } from "./blobStaging";
+
+export type CopyBlobSource =
+ | { kind: "generation"; stream: Readable }
+ | { kind: "legacy_flat"; reopen: () => Promise<Readable> };
+
+export interface StageCopiedBlobInput {
+ requestId: string;
+ destinationResourceId: string;
+ generation: string;
+ source: CopyBlobSource;
+ expectedBytes: number;
+ expectedSha256: string;
+ deadlineAtMs: number;
+ signal?: AbortSignal;
+ now?: () => number;
+}
+
+function precondition(message: string): never {
+ throw new GfsError("precondition_failed", message);
+}
+
+/** Stage one copy candidate. The caller supplies one request id for the whole tree. */
+export async function stageCopiedBlob(
+ manifests: PgBlobStagingStore,
+ blobs: StagingBlobStore,
+ input: StageCopiedBlobInput
+): Promise<{ blobKey: string; bytes: number; contentSha256: string }> {
+ if (!Number.isSafeInteger(input.expectedBytes) || input.expectedBytes < 0) {
+ precondition("copy source size is invalid");
+ }
+ if (!/^[0-9a-f]{64}$/.test(input.expectedSha256)) {
+ precondition("copy source digest is invalid");
+ }
+ if (!Number.isFinite(input.deadlineAtMs)) precondition("copy deadline is invalid");
+ const now = input.now ?? Date.now;
+ const checkDeadline = (): void => {
+ input.signal?.throwIfAborted();
+ if (now() >= input.deadlineAtMs) precondition("synchronous copy deadline exceeded");
+ };
+ checkDeadline();
+ const blobKey = generationBlobKey(input.destinationResourceId, input.generation);
+ const budget = { deadlineAtMs: input.deadlineAtMs, signal: input.signal, now: input.now };
+ await manifests.recordStaged({
+ blobKey,
+ requestId: input.requestId,
+ resourceId: input.destinationResourceId,
+ candidateKind: "generation",
+ contentSha256: input.expectedSha256,
+ bytes: input.expectedBytes,
+ }, budget);
+ let physicalCandidateOwned = false;
+ try {
+ checkDeadline();
+ // Legacy rows have no committed digest. Their preflight must hash and close
+ // one stream, then provide this explicit reopen callback for the copy pass.
+ const stream = input.source.kind === "generation" ? input.source.stream : await input.source.reopen();
+ checkDeadline();
+ const options = { signal: input.signal, checkDeadline };
+ const written = await blobs.writeImmutable(input.destinationResourceId, input.generation, stream, options);
+ physicalCandidateOwned = true;
+ if (
+ written.blobKey !== blobKey ||
+ written.bytes !== input.expectedBytes ||
+ written.contentSha256 !== input.expectedSha256
+ ) {
+ precondition("copy source changed after preflight");
+ }
+ await blobs.verify(blobKey, input.expectedBytes, input.expectedSha256, options);
+ return written;
+ } catch (err) {
+ // Reopen and write failures occur before ownership is established. Keep
+ // the staged manifest for reconciliation rather than deleting a key that
+ // may already belong to a committed request.
+ if (physicalCandidateOwned) {
+ await discardCandidate(manifests, blobs, blobKey, budget).catch(() => undefined);
+ }
+ if (err instanceof BlobVerificationError) precondition("copy source or staged bytes changed after preflight");
+ throw err;
+ }
+}
diff --git a/gfs-controller/src/db/copyPublication.failures.test.ts b/gfs-controller/src/db/copyPublication.failures.test.ts
new file mode 100644
index 000000000..dd5b58a62
--- /dev/null
+++ b/gfs-controller/src/db/copyPublication.failures.test.ts
@@ -0,0 +1,123 @@
+import { describe, expect, it, vi } from "vitest";
+import { copyFixture } from "../../test/copyPublicationTestKit";
+
+describe("copy rollback and ambiguous commit outcomes", () => {
+ it.each([1, 2])("cleans completed candidates and retains file %s manifest when staging hits ENOSPC", async failWriteAt => {
+ const fixture = copyFixture();
+ fixture.blobs.failWriteAt = failWriteAt;
+ await expect(fixture.writes.copy(fixture.input)).rejects.toMatchObject({ code: "ENOSPC" });
+ expect(fixture.db.resources.size).toBe(6);
+ expect([...fixture.db.manifests.values()]).toEqual(["staged"]);
+ expect(fixture.blobs.deletes).toHaveLength(failWriteAt - 1);
+ });
+
+ it("fails capacity before allocating identities or staging a blob", async () => {
+ const fixture = copyFixture();
+ fixture.blobs.capacity = fixture.input.plan.totalBytes - 1n;
+ await expect(fixture.writes.copy(fixture.input)).rejects.toMatchObject({ code: "payload_too_large" });
+ expect(fixture.blobs.writes).toEqual([]);
+ expect(fixture.db.manifests.size).toBe(0);
+ expect(fixture.audit.records).toHaveLength(1);
+ expect(fixture.audit.records[0]).toMatchObject({ transactional: false, event: {
+ recordType: "mutation_outcome", resourceId: fixture.input.plan.nodes[0].resourceId.replaceAll("-", ""),
+ outcome: "error", mutationOutcome: "failed", requestId: fixture.input.requestId,
+ } });
+ });
+
+ it("audits a deadline failure that occurs before capacity and staging", async () => {
+ const fixture = copyFixture();
+ const audit = vi.spyOn(fixture.audit, "record");
+ fixture.input.now = () => 1000;
+ await expect(fixture.writes.copy(fixture.input)).rejects.toMatchObject({ code: "precondition_failed" });
+ expect(fixture.blobs.capacityCalls).toBe(0);
+ expect(fixture.audit.records).toHaveLength(1);
+ expect(fixture.audit.records[0]).toMatchObject({ transactional: false, event: { mutationOutcome: "failed" } });
+ expect(audit.mock.calls[0][2]).toMatchObject({ deadlineAtMs: expect.any(Number) });
+ });
+
+ it("propagates an append failure from the definitive failed-outcome audit", async () => {
+ const fixture = copyFixture();
+ fixture.blobs.capacity = 0n;
+ fixture.audit.failOutside = true;
+ await expect(fixture.writes.copy(fixture.input)).rejects.toThrow("failure audit failed");
+ });
+
+ it("rolls back and cleans every candidate on metadata or manifest publication failures", async () => {
+ const metadata = copyFixture();
+ metadata.db.failInsert = new Error("metadata failed");
+ await expect(metadata.writes.copy(metadata.input)).rejects.toThrow("metadata failed");
+ expect(metadata.blobs.deletes).toHaveLength(2);
+ expect(metadata.db.manifests.size).toBe(0);
+
+ const manifests = copyFixture();
+ manifests.db.failCommitManifests = true;
+ await expect(manifests.writes.copy(manifests.input)).rejects.toThrow("manifest commit failed");
+ expect(manifests.db.resources.size).toBe(6);
+ expect(manifests.blobs.deletes).toHaveLength(2);
+ });
+
+ it("rolls back a failed atomic success audit, cleans blobs, then records failure outside the transaction", async () => {
+ const fixture = copyFixture();
+ fixture.audit.failTransactional = true;
+ await expect(fixture.writes.copy(fixture.input)).rejects.toThrow("success audit failed");
+ expect(fixture.db.resources.size).toBe(6);
+ expect(fixture.db.manifests.size).toBe(0);
+ expect(fixture.blobs.deletes).toHaveLength(2);
+ expect(fixture.audit.records).toHaveLength(2);
+ expect(fixture.audit.records[0]).toMatchObject({ transactional: true, event: { mutationOutcome: "succeeded" } });
+ expect(fixture.audit.records[1]).toMatchObject({ transactional: false, event: { mutationOutcome: "failed", outcome: "error" } });
+ });
+
+ it("maps a publication unique violation to already_exists and cleans candidates", async () => {
+ const fixture = copyFixture();
+ fixture.db.failInsert = Object.assign(new Error("duplicate"), { code: "23505" });
+ await expect(fixture.writes.copy(fixture.input)).rejects.toMatchObject({ code: "already_exists" });
+ expect(fixture.blobs.deletes).toHaveLength(2);
+ });
+
+ it("times out before commit, rolls back metadata and preserves unresolved candidates for reconciliation", async () => {
+ const fixture = copyFixture();
+ let calls = 0;
+ fixture.input.now = () => (++calls > 8 ? 1000 : 0);
+ await expect(fixture.writes.copy(fixture.input)).rejects.toMatchObject({ code: "precondition_failed" });
+ expect(fixture.db.resources.size).toBe(6);
+ expect(fixture.db.manifests.size).toBeGreaterThan(0);
+ });
+
+ it("treats an exact fully published ambiguous commit as success after the request is aborted", async () => {
+ const fixture = copyFixture({ ambiguity: "full", abortOnAmbiguity: true });
+ await expect(fixture.writes.copy(fixture.input)).resolves.toMatchObject({ objectCount: 4 });
+ expect(fixture.input.signal?.aborted).toBe(true);
+ expect(fixture.db.manifests.size).toBe(0);
+ expect(fixture.blobs.deletes).toEqual([]);
+ expect(fixture.audit.records).toHaveLength(1);
+ expect(fixture.audit.records[0]).toMatchObject({ transactional: true, event: { mutationOutcome: "succeeded" } });
+ });
+
+ it("cleans an exact-zero ambiguous rollback after the request is aborted", async () => {
+ const zero = copyFixture({ ambiguity: "zero", abortOnAmbiguity: true });
+ await expect(zero.writes.copy(zero.input)).rejects.toMatchObject({ name: "CommitOutcomeUnknownError" });
+ expect(zero.input.signal?.aborted).toBe(true);
+ expect(zero.db.manifests.size).toBe(0);
+ expect(zero.blobs.deletes).toHaveLength(2);
+ expect(zero.audit.records.map(record => record.event.mutationOutcome)).toEqual(["succeeded", "failed"]);
+ });
+
+ it("retains subset candidates without a definitive audit after the request is aborted", async () => {
+ const subset = copyFixture({ ambiguity: "subset", abortOnAmbiguity: true });
+ await expect(subset.writes.copy(subset.input)).rejects.toMatchObject({ name: "CommitOutcomeUnknownError" });
+ expect(subset.input.signal?.aborted).toBe(true);
+ expect(subset.db.manifests.size).toBe(2);
+ expect(subset.blobs.deletes).toEqual([]);
+ expect(subset.audit.records.filter(record => !record.transactional)).toEqual([]);
+ });
+
+ it("retains every candidate without a definitive audit when aborted inspection is unavailable", async () => {
+ const fixture = copyFixture({ ambiguity: "full", inspectUnavailable: true, abortOnAmbiguity: true });
+ await expect(fixture.writes.copy(fixture.input)).rejects.toMatchObject({ name: "CommitOutcomeUnknownError" });
+ expect(fixture.input.signal?.aborted).toBe(true);
+ expect(fixture.db.manifests.size).toBe(2);
+ expect(fixture.blobs.deletes).toEqual([]);
+ expect(fixture.audit.records.filter(record => !record.transactional)).toEqual([]);
+ });
+});
diff --git a/gfs-controller/src/db/copyPublication.test.ts b/gfs-controller/src/db/copyPublication.test.ts
new file mode 100644
index 000000000..554d671a7
--- /dev/null
+++ b/gfs-controller/src/db/copyPublication.test.ts
@@ -0,0 +1,243 @@
+import { describe, expect, it } from "vitest";
+import { copyFixture, DEST, FILE, SOURCE, sourceNodes } from "../../test/copyPublicationTestKit";
+
+describe("transactional recursive copy publication", () => {
+ it("publishes a nested tree with new identities in one metadata insert", async () => {
+ const { db, blobs, audit, writes, input } = copyFixture();
+ const before = new Map(db.resources);
+ const copied = await writes.copy(input);
+ expect(copied).toMatchObject({ requestId: input.requestId, objectCount: 4, fileCount: 2, folderCount: 2, totalBytes: 10n });
+ expect(copied.root).toMatchObject({ parentResourceId: DEST, name: "source", pathCache: "/archive/source", version: 0 });
+ const added = [...db.resources.values()].filter(row => !before.has(String(row.resource_id)));
+ expect(added).toHaveLength(4);
+ expect(new Set(added.map(row => row.resource_id)).size).toBe(4);
+ expect(added.map(row => row.path_cache)).toEqual(expect.arrayContaining([
+ "/archive/source", "/archive/source/file.txt", "/archive/source/empty", "/archive/source/empty/café.txt",
+ ]));
+ expect(added.find(row => row.path_cache === "/archive/source/empty")).toMatchObject({ bytes: 0, blob_key: null });
+ expect(sourceNodes().every(node => db.resources.get(node.resourceId)?.version === node.version)).toBe(true);
+ expect(blobs.writes).toHaveLength(2);
+ expect(blobs.reads.filter(id => id === FILE)).toHaveLength(1);
+ expect(blobs.reads.filter(id => id !== FILE)).toHaveLength(2);
+ expect(db.calls.filter(call => call.sql.includes("INSERT INTO gfs_resources"))).toHaveLength(1);
+ expect(audit.records).toHaveLength(1);
+ expect(audit.records[0]).toMatchObject({
+ transactional: true,
+ event: {
+ recordType: "mutation_outcome", subject: "agent:test", op: "copy", drive: "main",
+ resourceId: copied.root.resourceId.replaceAll("-", ""), requestId: input.requestId, outcome: "allow",
+ mutationOutcome: "succeeded", matchedSubject: null, authorizationSource: null,
+ cachedAuthorizationSource: null,
+ },
+ });
+ const resourceInsert = db.calls.findIndex(call => call.sql.includes("INSERT INTO gfs_resources"));
+ const manifestCommit = db.calls.findIndex(call => call.sql.includes("UPDATE gfs_blob_manifests") && call.sql.includes("committed"));
+ const auditInsert = db.calls.findIndex(call => call.sql.includes("INSERT INTO gfs_audit"));
+ expect(resourceInsert).toBeLessThan(manifestCommit);
+ expect(manifestCommit).toBeLessThan(auditInsert);
+ });
+
+ it("admits exact available capacity without a post-staging capacity check", async () => {
+ const fixture = copyFixture();
+ fixture.blobs.capacity = fixture.input.plan.totalBytes;
+ await expect(fixture.writes.copy(fixture.input)).resolves.toMatchObject({ totalBytes: 10n });
+ expect(fixture.blobs.capacityCalls).toBe(1);
+ });
+
+ it("publishes a directory-only tree without blob or manifest work", async () => {
+ const fixture = copyFixture({ nodes: [sourceNodes()[0]] });
+ await expect(fixture.writes.copy(fixture.input)).resolves.toMatchObject({ objectCount: 1, fileCount: 0, folderCount: 1 });
+ expect(fixture.blobs.writes).toEqual([]);
+ expect(fixture.db.manifests.size).toBe(0);
+ });
+
+ it("publishes more than 6553 directories with one fixed-size JSONB parameter", async () => {
+ const source = sourceNodes()[0];
+ const descendants = Array.from({ length: 6_553 }, (_, index) => {
+ const suffix = String(index + 1).padStart(12, "0");
+ const name = `directory-${index + 1}`;
+ return {
+ ...source,
+ resourceId: `20000000-0000-4000-8000-${suffix}`,
+ parentResourceId: SOURCE,
+ name,
+ pathCache: `/source/${name}`,
+ version: 0,
+ depth: 1,
+ };
+ });
+ const fixture = copyFixture({ nodes: [source, ...descendants], maxObjects: 7_000 });
+
+ await expect(fixture.writes.copy(fixture.input)).resolves.toMatchObject({
+ objectCount: 6_554,
+ folderCount: 6_554,
+ fileCount: 0,
+ });
+ const insert = fixture.db.calls.find(call => call.sql.includes("INSERT INTO gfs_resources"))!;
+ expect(insert.sql).toContain("jsonb_to_recordset($1::jsonb)");
+ expect(insert.sql).toContain("resource_id uuid");
+ expect(insert.sql).toContain("parent_resource_id uuid");
+ expect(insert.sql).toContain("bytes bigint");
+ expect(insert.sql).toContain("kind text");
+ expect(insert.sql).toContain("version integer");
+ expect(insert.sql).toContain("ORDER BY ordinal");
+ expect(insert.values).toHaveLength(1);
+ expect(JSON.parse(String(insert.values[0]))).toHaveLength(6_554);
+ });
+
+ it.each(["addition", "deletion", "reparent", "replacement"])(
+ "rejects a concurrent source %s",
+ async kind => {
+ const fixture = copyFixture();
+ if (kind === "addition") {
+ fixture.db.resources.set("00000000-0000-4000-8000-000000000099", {
+ resource_id: "00000000-0000-4000-8000-000000000099", drive: "main",
+ parent_resource_id: SOURCE, name: "late", kind: "directory", path_cache: "/source/late",
+ version: 0, bytes: "0", blob_key: null, content_sha256: null, deleted_at: null,
+ });
+ } else if (kind === "deletion") {
+ fixture.db.resources.delete(FILE);
+ } else if (kind === "reparent") {
+ fixture.db.resources.get(FILE)!.parent_resource_id = DEST;
+ } else {
+ Object.assign(fixture.db.resources.get(FILE)!, { version: 99, blob_key: "changed/key" });
+ }
+ await expect(fixture.writes.copy(fixture.input)).rejects.toMatchObject({ code: "precondition_failed" });
+ expect(fixture.blobs.deletes).toHaveLength(2);
+ }
+ );
+
+ it("ignores tombstone-only history but rejects a live node hidden below it", async () => {
+ const history = copyFixture();
+ history.db.resources.set("00000000-0000-4000-8000-000000000090", {
+ resource_id: "00000000-0000-4000-8000-000000000090", drive: "main", parent_resource_id: SOURCE,
+ name: "old", kind: "directory", path_cache: "/source/old", version: 1, bytes: "0",
+ blob_key: null, content_sha256: null, deleted_at: new Date("2026-01-01T00:00:00Z"),
+ });
+ await expect(history.writes.copy(history.input)).resolves.toMatchObject({ objectCount: 4 });
+
+ const hidden = copyFixture();
+ hidden.db.resources.set("00000000-0000-4000-8000-000000000090", {
+ resource_id: "00000000-0000-4000-8000-000000000090", drive: "main", parent_resource_id: SOURCE,
+ name: "old", kind: "directory", path_cache: "/source/old", version: 1, bytes: "0",
+ blob_key: null, content_sha256: null, deleted_at: new Date("2026-01-01T00:00:00Z"),
+ });
+ hidden.db.resources.set("00000000-0000-4000-8000-000000000091", {
+ resource_id: "00000000-0000-4000-8000-000000000091", drive: "main", parent_resource_id: "00000000-0000-4000-8000-000000000090",
+ name: "live", kind: "directory", path_cache: "/source/old/live", version: 0, bytes: "0",
+ blob_key: null, content_sha256: null, deleted_at: null,
+ });
+ await expect(hidden.writes.copy(hidden.input)).rejects.toMatchObject({ code: "precondition_failed" });
+ });
+
+ it("bounds live-tree revalidation at the frozen object count plus one", async () => {
+ const fixture = copyFixture();
+ await fixture.writes.copy(fixture.input);
+ const query = fixture.db.calls.find(call => call.sql.includes("WITH RECURSIVE copy_recheck"))!;
+ expect(query.sql).toContain("WHERE depth = 0 OR deleted_at IS NULL");
+ expect(query.sql).toContain("LIMIT $3");
+ expect(query.values[2]).toBe(BigInt(fixture.input.plan.objectCount) + 1n);
+ });
+
+ it("rejects destination changes and late root collisions", async () => {
+ const changed = copyFixture();
+ changed.db.resources.get(DEST)!.version = 8;
+ await expect(changed.writes.copy(changed.input)).rejects.toMatchObject({ code: "precondition_failed" });
+
+ const collision = copyFixture();
+ collision.db.resources.set("00000000-0000-4000-8000-000000000098", {
+ resource_id: "00000000-0000-4000-8000-000000000098", drive: "main", parent_resource_id: DEST,
+ name: "source", kind: "directory", path_cache: "/archive/source", version: 0, bytes: "0",
+ blob_key: null, content_sha256: null, deleted_at: null,
+ });
+ await expect(collision.writes.copy(collision.input)).rejects.toMatchObject({ code: "already_exists" });
+ expect(collision.db.calls.some(call => call.sql.includes("INSERT INTO gfs_resources"))).toBe(false);
+ });
+
+ it("does not couple copy publication to access-control or sharing tables", async () => {
+ const fixture = copyFixture();
+ await fixture.writes.copy(fixture.input);
+ const sql = fixture.db.calls.map(call => call.sql).join("\n");
+ expect(sql).not.toContain("gfs_gr" + "ants");
+ expect(sql).not.toContain("gfs_sh" + "ares");
+ });
+});
+
+describe("copy permission-epoch re-check (TOCTOU close)", () => {
+ const STABLE = { generation: 7, bypassed: false } as const;
+
+ it("publishes when the epoch is unchanged between authorization and the writer tx", async () => {
+ const fixture = copyFixture();
+ const input = {
+ ...fixture.input,
+ authzEpoch: { captured: { ...STABLE }, current: () => ({ ...STABLE }) },
+ };
+ await expect(fixture.writes.copy(input)).resolves.toMatchObject({ objectCount: 4 });
+ expect(fixture.db.calls.some(call => call.sql.includes("INSERT INTO gfs_resources"))).toBe(true);
+ });
+
+ it("rejects before INSERT when a revocation bumped the generation mid-copy", async () => {
+ const fixture = copyFixture();
+ const input = {
+ ...fixture.input,
+ authzEpoch: {
+ captured: { generation: 7, bypassed: false },
+ current: () => ({ generation: 8, bypassed: false }),
+ },
+ };
+ await expect(fixture.writes.copy(input)).rejects.toMatchObject({
+ code: "precondition_failed",
+ message: "authorization changed during copy",
+ });
+ // The re-check runs under the advisory lock, immediately before the INSERT —
+ // so a revoked grant never publishes.
+ expect(fixture.db.calls.some(call => call.sql.includes("INSERT INTO gfs_resources"))).toBe(false);
+ // Staged blobs are rolled back rather than orphaned.
+ expect(fixture.blobs.deletes).toHaveLength(2);
+ });
+
+ it("fails closed when the live epoch reports a degraded (bypassed) LISTEN", async () => {
+ const fixture = copyFixture();
+ const input = {
+ ...fixture.input,
+ authzEpoch: {
+ captured: { generation: 7, bypassed: false },
+ current: () => ({ generation: 7, bypassed: true }),
+ },
+ };
+ await expect(fixture.writes.copy(input)).rejects.toMatchObject({ code: "precondition_failed" });
+ expect(fixture.db.calls.some(call => call.sql.includes("INSERT INTO gfs_resources"))).toBe(false);
+ });
+
+ it("fails closed when the epoch was already bypassed at authorization time", async () => {
+ const fixture = copyFixture();
+ const input = {
+ ...fixture.input,
+ authzEpoch: {
+ captured: { generation: 7, bypassed: true },
+ current: () => ({ generation: 7, bypassed: true }),
+ },
+ };
+ await expect(fixture.writes.copy(input)).rejects.toMatchObject({ code: "precondition_failed" });
+ expect(fixture.db.calls.some(call => call.sql.includes("INSERT INTO gfs_resources"))).toBe(false);
+ });
+
+ it("re-reads the live epoch inside the writer transaction, not once at capture", async () => {
+ const fixture = copyFixture();
+ let epochReads = 0;
+ const input = {
+ ...fixture.input,
+ authzEpoch: {
+ captured: { generation: 7, bypassed: false },
+ current: () => {
+ epochReads += 1;
+ return { generation: 7, bypassed: false };
+ },
+ },
+ };
+ await expect(fixture.writes.copy(input)).resolves.toMatchObject({ objectCount: 4 });
+ // `current()` is invoked during revalidate (inside the tx), proving the
+ // re-check reads the LIVE epoch rather than trusting the captured snapshot.
+ expect(epochReads).toBeGreaterThanOrEqual(1);
+ });
+});
diff --git a/gfs-controller/src/db/copyPublication.ts b/gfs-controller/src/db/copyPublication.ts
new file mode 100644
index 000000000..eca730e55
--- /dev/null
+++ b/gfs-controller/src/db/copyPublication.ts
@@ -0,0 +1,359 @@
+import { createHash } from "node:crypto";
+import type { Readable } from "node:stream";
+import type { CopyDestinationSnapshot, CopyPreflightPlan, CopySnapshotNode } from "../api/copy";
+import { GfsError } from "../api/errors";
+import type { GfsResource } from "../api/read";
+import { normalizeResourceId } from "../storage/paths";
+import { discardCandidate, stageCopiedBlob, type PgBlobStagingStore, type PublishedTreeRef } from "./blobStaging";
+import type { DeadlineBudget } from "./deadlineQuery";
+import type { BlobWriter, CommitOutcomeUnknownError, CopyInput, Transactor, TxClient } from "./writeStore";
+
+interface Dependencies {
+ tx: Transactor;
+ blobs: BlobWriter;
+ manifests: PgBlobStagingStore;
+ ids: { resourceId: () => string; generation: () => string };
+}
+
+interface ReservedNode extends PublishedTreeRef {
+ source: CopySnapshotNode;
+ generation: string | null;
+}
+
+export interface CopyPublicationResult {
+ root: GfsResource;
+ requestId: string;
+ objectCount: number;
+ fileCount: number;
+ folderCount: number;
+ totalBytes: bigint;
+}
+
+const RETURNING = "resource_id, drive, parent_resource_id, name, kind, path_cache, version, bytes, blob_key, content_sha256, deleted_at";
+const AMBIGUOUS_COMMIT_INSPECTION_MS = 2_000;
+const POST_FAILURE_AUDIT_MS = 2_000;
+
+function dbId(value: string): string {
+ const rid = normalizeResourceId(value);
+ return `${rid.slice(0, 8)}-${rid.slice(8, 12)}-${rid.slice(12, 16)}-${rid.slice(16, 20)}-${rid.slice(20)}`;
+}
+
+function deadline(input: CopyInput): void {
+ input.signal?.throwIfAborted();
+ if ((input.now ?? Date.now)() >= input.deadlineAtMs) {
+ throw new GfsError("precondition_failed", "synchronous copy deadline exceeded");
+ }
+}
+
+function capabilities(blobs: BlobWriter): asserts blobs is BlobWriter & {
+ read(resourceId: string, blobKey?: string | null): Promise<Readable>;
+ availableBytes(): Promise<bigint>;
+} {
+ if (!blobs.read || !blobs.availableBytes) throw new Error("copy requires readable capacity-aware blob storage");
+}
+
+function nullable(value: unknown): string | null {
+ return value == null ? null : String(value);
+}
+
+function matchesSnapshot(row: Record<string, unknown>, expected: CopySnapshotNode): boolean {
+ let bytes: bigint;
+ try { bytes = BigInt(String(row.bytes)); } catch { return false; }
+ return String(row.resource_id) === dbId(expected.resourceId)
+ && String(row.drive) === expected.drive
+ && nullable(row.parent_resource_id) === (expected.parentResourceId === null ? null : dbId(expected.parentResourceId))
+ && String(row.name) === expected.name
+ && String(row.kind) === expected.kind
+ && nullable(row.path_cache) === expected.pathCache
+ && Number(row.version) === expected.version
+ && bytes === expected.bytes
+ && nullable(row.blob_key) === expected.blobKey
+ && nullable(row.content_sha256) === expected.contentSha256
+ && nullable(row.deleted_at) === expected.deletedAt
+ && (!("depth" in row) || Number(row.depth) === expected.depth)
+ && (!("cycle" in row) || Boolean(row.cycle) === expected.cycle)
+ && (!("under_tombstone" in row) || Boolean(row.under_tombstone) === expected.underTombstone);
+}
+
+function sameRows(rows: Record<string, unknown>[], expected: readonly CopySnapshotNode[]): boolean {
+ if (rows.length !== expected.length) return false;
+ const byId = new Map(rows.map(row => [String(row.resource_id), row]));
+ return expected.every(node => {
+ const row = byId.get(dbId(node.resourceId));
+ return row !== undefined && matchesSnapshot(row, node);
+ });
+}
+
+function sameChildren(rows: Record<string, unknown>[], expected: CopyDestinationSnapshot["liveChildren"]): boolean {
+ if (rows.length !== expected.length) return false;
+ const actual = rows.map(row => `${String(row.resource_id)}\0${String(row.name)}`).sort();
+ const wanted = expected.map(child => `${dbId(child.resourceId)}\0${child.name}`).sort();
+ return actual.every((value, index) => value === wanted[index]);
+}
+
+function resource(ref: PublishedTreeRef, drive: string): GfsResource {
+ return {
+ resourceId: ref.resourceId, drive, parentResourceId: ref.parentResourceId,
+ name: ref.name, kind: ref.kind, pathCache: ref.pathCache, version: 0,
+ bytes: Number(ref.bytes), blobKey: ref.blobKey, contentSha256: ref.contentSha256, deletedAt: null,
+ };
+}
+
+async function hashLegacy(stream: Readable, input: CopyInput, expectedBytes: bigint): Promise<string> {
+ const hash = createHash("sha256");
+ let bytes = 0n;
+ for await (const chunk of stream) {
+ deadline(input);
+ const value = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
+ bytes += BigInt(value.length);
+ hash.update(value);
+ }
+ if (bytes !== expectedBytes) throw new GfsError("precondition_failed", "legacy copy source changed after preflight");
+ return hash.digest("hex");
+}
+
+function reserve(plan: CopyPreflightPlan, input: CopyInput, deps: Dependencies): ReservedNode[] {
+ const ids = new Map(plan.nodes.map(node => [normalizeResourceId(node.resourceId), dbId(deps.ids.resourceId())]));
+ const destinationId = dbId(input.destinationParentId);
+ const destination = input.destination.ancestors.find(node => dbId(node.resourceId) === destinationId && node.depth === 0)!;
+ const paths = new Map<string, string>();
+ return plan.nodes.map(source => {
+ const sourceId = normalizeResourceId(source.resourceId);
+ const oldParent = plan.parentByResourceId.get(sourceId);
+ if (oldParent === undefined) throw new GfsError("precondition_failed", "copy plan parent map is incomplete");
+ const parentResourceId = oldParent === null ? destinationId : ids.get(oldParent)!;
+ const name = oldParent === null ? plan.rootName : source.name;
+ const parentPath = oldParent === null ? destination.pathCache! : paths.get(oldParent)!;
+ const pathCache = parentPath === "/" ? `/${name}` : `${parentPath}/${name}`;
+ paths.set(sourceId, pathCache);
+ return {
+ source, resourceId: ids.get(sourceId)!, parentResourceId, name, kind: source.kind,
+ pathCache, version: 0, bytes: source.bytes, blobKey: null, contentSha256: null,
+ generation: source.kind === "file" ? deps.ids.generation() : null,
+ };
+ });
+}
+
+async function cleanup(deps: Dependencies, budget: DeadlineBudget, blobKeys: readonly string[]): Promise<void> {
+ await Promise.all(blobKeys.map(key => discardCandidate(deps.manifests, deps.blobs, key, budget).catch(() => undefined)));
+}
+
+function inputBudget(input: CopyInput): DeadlineBudget {
+ return { deadlineAtMs: input.deadlineAtMs, signal: input.signal, now: input.now };
+}
+function ambiguousCommitBudget(): DeadlineBudget {
+ return { deadlineAtMs: Date.now() + AMBIGUOUS_COMMIT_INSPECTION_MS };
+}
+function postFailureAuditBudget(): DeadlineBudget {
+ return { deadlineAtMs: Date.now() + POST_FAILURE_AUDIT_MS };
+}
+
+async function revalidate(client: TxClient, input: CopyInput): Promise<void> {
+ deadline(input);
+ await client.query(`SELECT pg_advisory_xact_lock(hashtext('gfs:structure:' || $1)::bigint)`, [input.drive]);
+ deadline(input);
+ const observedIds = [...new Set([
+ ...input.plan.nodes.map(node => dbId(node.resourceId)),
+ ...input.destination.ancestors.map(node => dbId(node.resourceId)),
+ ...input.destination.liveChildren.map(node => dbId(node.resourceId)),
+ ])].sort();
+ await client.query(`SELECT resource_id FROM gfs_resources WHERE resource_id = ANY($1::uuid[]) ORDER BY resource_id FOR UPDATE`, [observedIds]);
+ deadline(input);
+ const source = await client.query(
+ `WITH RECURSIVE copy_recheck AS (
+ SELECT r.*, 0 AS depth, ARRAY[r.resource_id]::uuid[] AS visited,
+ false AS cycle, false AS under_tombstone
+ FROM gfs_resources r WHERE r.drive = $1 AND r.resource_id = $2
+ UNION ALL
+ SELECT child.*, parent.depth + 1, parent.visited || child.resource_id,
+ child.resource_id = ANY(parent.visited) AS cycle,
+ parent.under_tombstone OR child.deleted_at IS NOT NULL AS under_tombstone
+ FROM copy_recheck parent
+ JOIN gfs_resources child ON child.drive = $1 AND child.parent_resource_id = parent.resource_id
+ WHERE NOT parent.cycle
+ )
+ SELECT ${RETURNING}, depth, cycle, under_tombstone
+ FROM copy_recheck
+ WHERE depth = 0 OR deleted_at IS NULL
+ LIMIT $3`,
+ [input.drive, dbId(input.plan.nodes[0].resourceId), BigInt(input.plan.objectCount) + 1n]
+ );
+ deadline(input);
+ const ancestors = await client.query(`SELECT ${RETURNING} FROM gfs_resources WHERE drive = $1 AND resource_id = ANY($2::uuid[]) ORDER BY resource_id`, [input.drive, input.destination.ancestors.map(node => dbId(node.resourceId))]);
+ deadline(input);
+ const children = await client.query(
+ `SELECT resource_id, name FROM gfs_resources
+ WHERE drive = $1 AND parent_resource_id = $2 AND deleted_at IS NULL AND name = $3
+ ORDER BY resource_id`,
+ [input.drive, dbId(input.destinationParentId), input.plan.rootName]
+ );
+ deadline(input);
+ if (children.rows.some(row => String(row.name) === input.plan.rootName)) {
+ throw new GfsError("already_exists", `a resource named '${input.plan.rootName}' already exists here`);
+ }
+ if (!sameRows(source.rows, input.plan.nodes)
+ || !sameRows(ancestors.rows, input.destination.ancestors)
+ || !sameChildren(children.rows, input.destination.liveChildren)) {
+ throw new GfsError("precondition_failed", "copy source or destination changed after preflight");
+ }
+ // Permission-epoch re-check (TOCTOU close): the snapshot was authorized before
+ // blobs were staged, so a grant revoked mid-copy must be caught here — inside
+ // the writer transaction, under the advisory lock, immediately before INSERT.
+ // A bumped `generation` means a revocation NOTIFY flushed the cache after we
+ // authorized; a `bypassed` epoch (either at capture or now) means the LISTEN is
+ // degraded and NOTIFYs are not processed, so a revocation cannot be observed —
+ // both fail closed rather than publishing against stale authorization.
+ if (input.authzEpoch) {
+ const started = input.authzEpoch.captured;
+ const nowEpoch = input.authzEpoch.current();
+ if (started.bypassed || nowEpoch.bypassed || nowEpoch.generation !== started.generation) {
+ throw new GfsError("precondition_failed", "authorization changed during copy");
+ }
+ }
+}
+
+function insertSql(nodes: readonly ReservedNode[]): { sql: string; values: unknown[] } {
+ const payload = nodes.map((node, ordinal) => ({
+ ordinal, resource_id: node.resourceId, drive: node.source.drive,
+ parent_resource_id: node.parentResourceId, name: node.name, kind: node.kind,
+ path_cache: node.pathCache, bytes: node.bytes.toString(), blob_key: node.blobKey,
+ content_sha256: node.contentSha256, version: 0,
+ }));
+ return {
+ sql: `INSERT INTO gfs_resources (resource_id, drive, parent_resource_id, name, kind, path_cache, bytes, blob_key, content_sha256, version)
+ SELECT resource_id, drive, parent_resource_id, name, kind, path_cache, bytes, blob_key, content_sha256, version
+ FROM jsonb_to_recordset($1::jsonb) AS node(resource_id uuid, drive text, parent_resource_id uuid,
+ name text, kind text, path_cache text, bytes bigint, blob_key text, content_sha256 text, version integer, ordinal bigint)
+ ORDER BY ordinal
+ RETURNING ${RETURNING}`,
+ values: [JSON.stringify(payload)],
+ };
+}
+
+function result(input: CopyInput, root: PublishedTreeRef): CopyPublicationResult {
+ return { root: resource(root, input.drive), requestId: input.requestId, objectCount: input.plan.objectCount,
+ fileCount: input.plan.fileCount, folderCount: input.plan.folderCount, totalBytes: input.plan.totalBytes };
+}
+
+function auditEvent(input: CopyInput, resourceId: string, mutationOutcome: "succeeded" | "failed", reason?: string) {
+ return {
+ recordType: "mutation_outcome" as const,
+ subject: input.subject,
+ op: "copy",
+ resourceId: normalizeResourceId(resourceId),
+ drive: input.drive,
+ outcome: mutationOutcome === "succeeded" ? "allow" as const : "error" as const,
+ reason,
+ requestId: input.requestId,
+ matchedSubject: null,
+ authorizationSource: null,
+ cachedAuthorizationSource: null,
+ mutationOutcome,
+ };
+}
+
+async function auditFailure(input: CopyInput, error: unknown): Promise<void> {
+ const sourceRoot = input.plan.nodes[0];
+ const reason = error instanceof GfsError ? error.code : "internal_error";
+ await input.audit.record(
+ auditEvent(input, sourceRoot.resourceId, "failed", reason),
+ undefined,
+ postFailureAuditBudget()
+ );
+}
+
+async function inspectAmbiguous(
+ deps: Dependencies,
+ input: CopyInput,
+ reserved: ReservedNode[],
+ budget: DeadlineBudget
+): Promise<"full" | "zero" | "unsafe"> {
+ try {
+ const published = await deps.manifests.resolvePublishedTree(input.drive, reserved, budget);
+ if (published !== null) return "full";
+ return await deps.tx.transaction(async client => {
+ const rows = await client.query(`SELECT resource_id FROM gfs_resources WHERE drive = $1 AND resource_id = ANY($2::uuid[])`, [input.drive, reserved.map(node => node.resourceId)]);
+ if (rows.rows.length === 0) return "zero";
+ return "unsafe";
+ }, budget);
+ } catch { return "unsafe"; }
+}
+
+export async function publishCopy(deps: Dependencies, input: CopyInput): Promise<CopyPublicationResult> {
+ capabilities(deps.blobs);
+ const blobs = deps.blobs;
+ let reserved: ReservedNode[] = [];
+ const stagedKeys: string[] = [];
+ try {
+ deadline(input);
+ if (input.plan.totalBytes > await blobs.availableBytes()) throw new GfsError("payload_too_large", "insufficient destination capacity for copy");
+ deadline(input);
+ reserved = reserve(input.plan, input, deps);
+ for (const node of reserved.filter(item => item.kind === "file")) {
+ deadline(input);
+ const sourceId = dbId(node.source.resourceId);
+ let digest = node.source.contentSha256;
+ if (node.source.blobKey === null) digest = await hashLegacy(await blobs.read(sourceId, null), input, node.source.bytes);
+ if (!digest) throw new GfsError("precondition_failed", "copy source has no committed digest");
+ const generationStream = node.source.blobKey === null ? null : await blobs.read(sourceId, node.source.blobKey);
+ let staged: { blobKey: string; bytes: number; contentSha256: string };
+ try {
+ staged = await stageCopiedBlob(deps.manifests, deps.blobs, {
+ requestId: input.requestId, destinationResourceId: node.resourceId, generation: node.generation!,
+ source: generationStream === null
+ ? { kind: "legacy_flat", reopen: () => blobs.read(sourceId, null) }
+ : { kind: "generation", stream: generationStream },
+ expectedBytes: Number(node.source.bytes), expectedSha256: digest,
+ deadlineAtMs: input.deadlineAtMs, signal: input.signal, now: input.now,
+ });
+ } catch (error) {
+ generationStream?.destroy();
+ throw error;
+ }
+ node.blobKey = staged.blobKey;
+ node.contentSha256 = staged.contentSha256;
+ stagedKeys.push(staged.blobKey);
+ }
+ const root = reserved[0];
+ await deps.tx.transaction(async client => {
+ await revalidate(client, input);
+ deadline(input);
+ const insert = insertSql(reserved);
+ try {
+ await client.query(insert.sql, insert.values);
+ } catch (error) {
+ if ((error as { code?: string }).code === "23505") {
+ throw new GfsError("already_exists", `a resource named '${input.plan.rootName}' already exists here`);
+ }
+ throw error;
+ }
+ await deps.manifests.markCommittedMany(client, input.requestId, stagedKeys);
+ await input.audit.record(auditEvent(input, root.resourceId, "succeeded"), client);
+ deadline(input);
+ }, { deadlineAtMs: input.deadlineAtMs, signal: input.signal, now: input.now });
+ await deps.manifests.removeCommittedMany(input.requestId, stagedKeys, {
+ deadlineAtMs: input.deadlineAtMs, signal: input.signal, now: input.now,
+ }).catch(() => undefined);
+ return result(input, root);
+ } catch (error) {
+ if ((error as Error).name === "CommitOutcomeUnknownError") {
+ // COMMIT uncertainty is resolved with a fresh, short budget. The request
+ // signal/deadline commonly caused the original uncertainty and therefore
+ // cannot safely gate the independent read-back.
+ const recoveryBudget = ambiguousCommitBudget();
+ const outcome = await inspectAmbiguous(deps, input, reserved, recoveryBudget);
+ if (outcome === "full") {
+ await deps.manifests.removeCommittedMany(input.requestId, stagedKeys, ambiguousCommitBudget()).catch(() => undefined);
+ return result(input, reserved[0]);
+ }
+ if (outcome === "zero") {
+ await cleanup(deps, ambiguousCommitBudget(), stagedKeys);
+ await auditFailure(input, error);
+ }
+ throw error as CommitOutcomeUnknownError;
+ }
+ await cleanup(deps, inputBudget(input), stagedKeys);
+ await auditFailure(input, error);
+ throw error;
+ }
+}
diff --git a/gfs-controller/src/db/deadlineQuery.test.ts b/gfs-controller/src/db/deadlineQuery.test.ts
new file mode 100644
index 000000000..d3e38fc11
--- /dev/null
+++ b/gfs-controller/src/db/deadlineQuery.test.ts
@@ -0,0 +1,168 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { DeadlineCommitOutcomeUnknownError, withDeadlineTransaction } from "./deadlineQuery";
+
+class Pool {
+ calls: Array<{ sql: string; values: unknown[] }> = [];
+ releaseError: Error | boolean | undefined;
+ fail = "";
+ async connect() {
+ return {
+ query: async (sql: string, values: unknown[] = []) => {
+ this.calls.push({ sql, values });
+ if (sql === this.fail) throw Object.assign(new Error(`failed ${sql}`), sql.includes("pg_sleep") ? { code: "57014" } : {});
+ return { rows: [{ ok: true }] };
+ },
+ release: (error?: Error | boolean) => { this.releaseError = error; },
+ };
+ }
+}
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ let reject!: (reason?: unknown) => void;
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise;
+ reject = rejectPromise;
+ });
+ return { promise, resolve, reject };
+}
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe("deadline-bounded PostgreSQL transactions", () => {
+ it("installs statement_timeout before useful SQL in one checked-out READ ONLY transaction", async () => {
+ const pool = new Pool();
+ await withDeadlineTransaction(pool, { deadlineAtMs: 5000, now: () => 1000 }, true,
+ client => client.query("SELECT pg_sleep(0)"));
+ expect(pool.calls).toEqual([
+ { sql: "BEGIN READ ONLY", values: [] },
+ { sql: "SELECT set_config('statement_timeout', $1, true)", values: ["4000"] },
+ { sql: "SELECT pg_sleep(0)", values: [] },
+ { sql: "COMMIT", values: [] },
+ ]);
+ });
+
+ it("maps a real PostgreSQL statement-timeout code after rollback", async () => {
+ const pool = new Pool(); pool.fail = "SELECT pg_sleep(10)";
+ await expect(withDeadlineTransaction(pool, { deadlineAtMs: 5000, now: () => 1000 }, true,
+ client => client.query("SELECT pg_sleep(10)"))).rejects.toMatchObject({ code: "precondition_failed" });
+ expect(pool.calls.at(-1)?.sql).toBe("ROLLBACK");
+ expect(pool.releaseError).toBeUndefined();
+ });
+
+ it("destroys the connection and preserves commit ambiguity", async () => {
+ const pool = new Pool(); pool.fail = "COMMIT";
+ await expect(withDeadlineTransaction(pool, { deadlineAtMs: 5000, now: () => 1000 }, false,
+ client => client.query("UPDATE durable_state SET value = 1"))).rejects.toBeInstanceOf(DeadlineCommitOutcomeUnknownError);
+ expect(pool.releaseError).toBeInstanceOf(Error);
+ });
+
+ it("bounds pool acquisition and releases a client that arrives after the deadline without issuing SQL", async () => {
+ vi.useFakeTimers();
+ const acquisition = deferred<Awaited<ReturnType<Pool["connect"]>>>();
+ const lateClient = await new Pool().connect();
+ const query = vi.spyOn(lateClient, "query");
+ const release = vi.spyOn(lateClient, "release");
+ const operation = vi.fn();
+ const pool = { connect: () => acquisition.promise };
+
+ const transaction = withDeadlineTransaction(
+ pool,
+ { deadlineAtMs: 10, now: () => 0 },
+ true,
+ operation
+ );
+ const rejected = expect(transaction).rejects.toMatchObject({ code: "precondition_failed" });
+ await vi.advanceTimersByTimeAsync(10);
+ await rejected;
+
+ expect(operation).not.toHaveBeenCalled();
+ acquisition.resolve(lateClient);
+ await vi.runAllTimersAsync();
+ await Promise.resolve();
+ expect(query).not.toHaveBeenCalled();
+ expect(release).toHaveBeenCalledOnce();
+ });
+
+ it("re-arms deadlines larger than Node's maximum timer delay instead of expiring early", async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(0);
+ const maxTimerMs = 2_147_483_647;
+ const acquisition = deferred<Awaited<ReturnType<Pool["connect"]>>>();
+ const transaction = withDeadlineTransaction(
+ { connect: () => acquisition.promise },
+ { deadlineAtMs: maxTimerMs + 50 },
+ true,
+ vi.fn()
+ );
+ let settled = false;
+ void transaction.then(() => { settled = true; }, () => { settled = true; });
+
+ await vi.advanceTimersByTimeAsync(maxTimerMs);
+ expect(settled).toBe(false);
+ await vi.advanceTimersByTimeAsync(49);
+ expect(settled).toBe(false);
+ const rejected = expect(transaction).rejects.toMatchObject({ code: "precondition_failed" });
+ await vi.advanceTimersByTimeAsync(1);
+ await rejected;
+ });
+
+ it("handles a pool acquisition that rejects after the deadline", async () => {
+ vi.useFakeTimers();
+ const acquisition = deferred<Awaited<ReturnType<Pool["connect"]>>>();
+ const operation = vi.fn();
+ const transaction = withDeadlineTransaction(
+ { connect: () => acquisition.promise },
+ { deadlineAtMs: 5, now: () => 0 },
+ false,
+ operation
+ );
+ const rejected = expect(transaction).rejects.toMatchObject({ code: "precondition_failed" });
+ await vi.advanceTimersByTimeAsync(5);
+ await rejected;
+
+ acquisition.reject(new Error("late connect failure"));
+ await Promise.resolve();
+ expect(operation).not.toHaveBeenCalled();
+ });
+
+ it("abandons a pending pool acquisition when the request is aborted", async () => {
+ const acquisition = deferred<Awaited<ReturnType<Pool["connect"]>>>();
+ const controller = new AbortController();
+ const lateClient = await new Pool().connect();
+ const query = vi.spyOn(lateClient, "query");
+ const release = vi.spyOn(lateClient, "release");
+ const operation = vi.fn();
+ const transaction = withDeadlineTransaction(
+ { connect: () => acquisition.promise },
+ { deadlineAtMs: Date.now() + 10_000, signal: controller.signal },
+ true,
+ operation
+ );
+
+ controller.abort();
+ await expect(transaction).rejects.toMatchObject({ code: "precondition_failed" });
+ acquisition.resolve(lateClient);
+ await Promise.resolve();
+
+ expect(operation).not.toHaveBeenCalled();
+ expect(query).not.toHaveBeenCalled();
+ expect(release).toHaveBeenCalledOnce();
+ });
+
+ it("does not start pool acquisition for an already-aborted request", async () => {
+ const controller = new AbortController();
+ controller.abort();
+ const connect = vi.fn();
+
+ await expect(withDeadlineTransaction(
+ { connect },
+ { deadlineAtMs: Date.now() + 10_000, signal: controller.signal },
+ true,
+ vi.fn()
+ )).rejects.toMatchObject({ code: "precondition_failed" });
+ expect(connect).not.toHaveBeenCalled();
+ });
+});
diff --git a/gfs-controller/src/db/deadlineQuery.ts b/gfs-controller/src/db/deadlineQuery.ts
new file mode 100644
index 000000000..98ab6d266
--- /dev/null
+++ b/gfs-controller/src/db/deadlineQuery.ts
@@ -0,0 +1,153 @@
+import { GfsError } from "../api/errors";
+
+export interface DeadlineBudget {
+ deadlineAtMs: number;
+ signal?: AbortSignal;
+ now?: () => number;
+}
+
+export interface DeadlineClient {
+ query(text: string, values?: unknown[]): Promise<{ rows: Record<string, unknown>[] }>;
+ release(error?: Error | boolean): void;
+}
+
+export interface DeadlinePool {
+ connect?: () => Promise<DeadlineClient>;
+}
+
+export class DeadlineCommitOutcomeUnknownError extends Error {
+ constructor(readonly cause: unknown) {
+ super("deadline-bounded transaction commit outcome is unknown");
+ this.name = "DeadlineCommitOutcomeUnknownError";
+ }
+}
+
+export class DeadlineRollbackOutcomeUnknownError extends Error {
+ constructor(readonly cause: unknown, readonly rollbackCause: unknown) {
+ super("deadline-bounded transaction rollback outcome is unknown");
+ this.name = "DeadlineRollbackOutcomeUnknownError";
+ }
+}
+
+function remainingMs(budget: DeadlineBudget): number {
+ budget.signal?.throwIfAborted();
+ const remaining = budget.deadlineAtMs - (budget.now ?? Date.now)();
+ if (remaining <= 0) throw new GfsError("precondition_failed", "synchronous mutation deadline exceeded");
+ return Math.max(1, Math.min(remaining, 2_147_483_647));
+}
+
+function deadlineError(error: unknown, budget: DeadlineBudget): boolean {
+ return (error as { code?: string }).code === "57014"
+ || budget.signal?.aborted === true
+ || (budget.now ?? Date.now)() >= budget.deadlineAtMs;
+}
+
+const MAX_TIMER_MS = 2_147_483_647;
+
+export async function acquireBeforeDeadline(
+ connect: () => Promise<DeadlineClient>,
+ budget: DeadlineBudget
+): Promise<DeadlineClient> {
+ if (budget.signal?.aborted || (budget.now ?? Date.now)() >= budget.deadlineAtMs) {
+ throw new GfsError("precondition_failed", "synchronous mutation deadline exceeded");
+ }
+ let orphaned = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let abortListener: (() => void) | undefined;
+
+ const acquire = connect();
+ // Promise.race cannot cancel pool.connect(). If the deadline wins, return a
+ // client that arrives later without ever issuing SQL. Handle late rejection
+ // too, so neither outcome can become an unhandled promise rejection.
+ void acquire.then(
+ client => {
+ if (!orphaned) return;
+ try {
+ client.release();
+ } catch {
+ // release() is synchronous and there is no further recovery action;
+ // swallowing here prevents a late cleanup error from going unhandled.
+ }
+ },
+ () => undefined
+ );
+
+ const deadline = new Promise<never>((_, reject) => {
+ let remainingToWait = budget.deadlineAtMs - (budget.now ?? Date.now)();
+ const rejectDeadline = () => {
+ // Mark the acquire orphaned before settling the deadline promise. This
+ // keeps cleanup correct even when connect resolves in the narrow window
+ // before the awaiting continuation runs.
+ orphaned = true;
+ reject(new GfsError("precondition_failed", "synchronous mutation deadline exceeded"));
+ };
+ const armDeadline = () => {
+ if (remainingToWait <= 0 || (budget.now ?? Date.now)() >= budget.deadlineAtMs) {
+ rejectDeadline();
+ return;
+ }
+ // Node clamps larger delays to 1ms. Re-arm at its supported maximum so
+ // a valid long deadline never expires early.
+ const delay = Math.max(1, Math.min(remainingToWait, MAX_TIMER_MS));
+ remainingToWait -= delay;
+ timer = setTimeout(armDeadline, delay);
+ timer.unref?.();
+ };
+ armDeadline();
+ if (budget.signal) {
+ if (budget.signal.aborted) {
+ rejectDeadline();
+ } else {
+ abortListener = rejectDeadline;
+ budget.signal.addEventListener("abort", abortListener, { once: true });
+ }
+ }
+ });
+
+ try {
+ return await Promise.race([acquire, deadline]);
+ } finally {
+ if (timer) clearTimeout(timer);
+ if (abortListener) budget.signal?.removeEventListener("abort", abortListener);
+ }
+}
+
+/** A dedicated short transaction whose timeout is installed before useful SQL. */
+export async function withDeadlineTransaction<T>(
+ pool: DeadlinePool,
+ budget: DeadlineBudget,
+ readOnly: boolean,
+ operation: (client: DeadlineClient) => Promise<T>
+): Promise<T> {
+ if (!pool.connect) throw new Error("deadline-bounded database operation requires a checked-out client");
+ const client = await acquireBeforeDeadline(() => pool.connect!(), budget);
+ let commitSent = false;
+ let poison: Error | undefined;
+ try {
+ budget.signal?.throwIfAborted();
+ await client.query(readOnly ? "BEGIN READ ONLY" : "BEGIN");
+ await client.query("SELECT set_config('statement_timeout', $1, true)", [String(remainingMs(budget))]);
+ const result = await operation(client);
+ remainingMs(budget);
+ commitSent = true;
+ await client.query("COMMIT");
+ return result;
+ } catch (error) {
+ let rollbackFailure: unknown;
+ await client.query("ROLLBACK").catch(failure => { rollbackFailure = failure; });
+ if (commitSent || rollbackFailure !== undefined) {
+ const cause = rollbackFailure ?? error;
+ poison = cause instanceof Error ? cause : new Error(String(cause));
+ }
+ if (commitSent) throw new DeadlineCommitOutcomeUnknownError(error);
+ if (rollbackFailure !== undefined) {
+ throw new DeadlineRollbackOutcomeUnknownError(error, rollbackFailure);
+ }
+ if (deadlineError(error, budget)) {
+ throw new GfsError("precondition_failed", "synchronous mutation deadline exceeded");
+ }
+ throw error;
+ } finally {
+ client.release(poison);
+ }
+}
diff --git a/gfs-controller/src/db/managedMutationAudit.ts b/gfs-controller/src/db/managedMutationAudit.ts
new file mode 100644
index 000000000..86a1bba01
--- /dev/null
+++ b/gfs-controller/src/db/managedMutationAudit.ts
@@ -0,0 +1,82 @@
+import type { AuditSink, Queryable } from "../authz/audit";
+import type { GfsResource } from "../api/read";
+import { normalizeResourceId } from "../storage/paths";
+import type { Transactor } from "./writeStore";
+
+export interface ManagedMutationContext {
+ subject: string;
+ requestId: string;
+ audit: AuditSink;
+}
+
+export async function recordManagedMutation(
+ context: ManagedMutationContext | undefined,
+ input: { op: "create" | "replace"; resourceId: string; drive: string },
+ outcome: "succeeded" | "failed",
+ reason?: string,
+ queryable?: Queryable
+): Promise<void> {
+ if (!context) return;
+ await context.audit.record({
+ recordType: "mutation_outcome", subject: context.subject, op: input.op,
+ resourceId: normalizeResourceId(input.resourceId), drive: input.drive,
+ outcome: outcome === "succeeded" ? "allow" : "error", reason,
+ requestId: context.requestId, matchedSubject: null, authorizationSource: null,
+ cachedAuthorizationSource: null, mutationOutcome: outcome,
+ }, queryable);
+}
+
+function nullable(value: unknown): string | null {
+ return value == null ? null : String(value);
+}
+
+function matchesPrevious(row: Record<string, unknown>, previous: GfsResource): boolean {
+ return String(row.resource_id) === previous.resourceId
+ && String(row.drive) === previous.drive
+ && nullable(row.parent_resource_id) === previous.parentResourceId
+ && String(row.name) === previous.name
+ && String(row.kind) === previous.kind
+ && nullable(row.path_cache) === previous.pathCache
+ && Number(row.version) === previous.version
+ && Number(row.bytes) === previous.bytes
+ && nullable(row.blob_key) === previous.blobKey
+ && nullable(row.content_sha256) === previous.contentSha256
+ && row.deleted_at == null;
+}
+
+export async function inspectCreateOutcome(
+ tx: Transactor,
+ drive: string,
+ resourceId: string,
+ expected?: GfsResource
+): Promise<"full" | "zero" | "unsafe"> {
+ try {
+ return await tx.transaction(async client => {
+ const result = await client.query(
+ `SELECT resource_id, drive, parent_resource_id, name, kind, path_cache, version,
+ bytes, blob_key, content_sha256, deleted_at
+ FROM gfs_resources WHERE drive = $1 AND resource_id = $2`,
+ [drive, resourceId]
+ );
+ if (result.rows.length === 0) return "zero";
+ return expected && matchesPrevious(result.rows[0], expected) ? "full" : "unsafe";
+ });
+ } catch { return "unsafe"; }
+}
+
+export async function inspectReplaceRollback(
+ tx: Transactor,
+ previous: GfsResource
+): Promise<"old" | "unsafe"> {
+ try {
+ return await tx.transaction(async client => {
+ const result = await client.query(
+ `SELECT resource_id, drive, parent_resource_id, name, kind, path_cache, version,
+ bytes, blob_key, content_sha256, deleted_at
+ FROM gfs_resources WHERE drive = $1 AND resource_id = $2`,
+ [previous.drive, previous.resourceId]
+ );
+ return result.rows.length === 1 && matchesPrevious(result.rows[0], previous) ? "old" : "unsafe";
+ });
+ } catch { return "unsafe"; }
+}
diff --git a/gfs-controller/src/db/publishedTree.ts b/gfs-controller/src/db/publishedTree.ts
new file mode 100644
index 000000000..cd82f97fb
--- /dev/null
+++ b/gfs-controller/src/db/publishedTree.ts
@@ -0,0 +1,54 @@
+export interface PublishedTreeRef {
+ resourceId: string;
+ parentResourceId: string | null;
+ name: string;
+ kind: "file" | "directory";
+ pathCache: string;
+ version: number;
+ bytes: bigint;
+ blobKey: string | null;
+ contentSha256: string | null;
+}
+
+function nullableString(value: unknown): string | null {
+ return value == null ? null : String(value);
+}
+
+function matchesRow(drive: string, expected: PublishedTreeRef, row: Record<string, unknown>): boolean {
+ let bytes: bigint;
+ try {
+ bytes = BigInt(String(row.bytes));
+ } catch {
+ return false;
+ }
+ return String(row.resource_id) === expected.resourceId
+ && String(row.drive) === drive
+ && nullableString(row.parent_resource_id) === expected.parentResourceId
+ && String(row.name) === expected.name
+ && String(row.kind) === expected.kind
+ && String(row.path_cache) === expected.pathCache
+ && Number(row.version) === expected.version
+ && bytes === expected.bytes
+ && nullableString(row.blob_key) === expected.blobKey
+ && nullableString(row.content_sha256) === expected.contentSha256
+ && row.deleted_at == null;
+}
+
+/** An ambiguous COMMIT is published only when every reserved row matches exactly. */
+export function matchesPublishedTree(
+ drive: string,
+ expected: readonly PublishedTreeRef[],
+ rows: readonly Record<string, unknown>[]
+): boolean {
+ if (rows.length !== expected.length) return false;
+ const byId = new Map<string, Record<string, unknown>>();
+ for (const row of rows) {
+ const id = String(row.resource_id);
+ if (byId.has(id)) return false;
+ byId.set(id, row);
+ }
+ return expected.every(item => {
+ const row = byId.get(item.resourceId);
+ return row !== undefined && matchesRow(drive, item, row);
+ });
+}
diff --git a/gfs-controller/src/db/renamePublication.realPostgres.integration.test.ts b/gfs-controller/src/db/renamePublication.realPostgres.integration.test.ts
new file mode 100644
index 000000000..a22e71247
--- /dev/null
+++ b/gfs-controller/src/db/renamePublication.realPostgres.integration.test.ts
@@ -0,0 +1,220 @@
+import { Pool } from "pg";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import type { AuditSink } from "../authz/audit";
+import { publishRename } from "./renamePublication";
+import { PgTransactor, type Transactor, type TxClient } from "./writeStore";
+
+// Regression harness for the served rename SQL. The unit suite runs the
+// publication against a scripted client, so a statement that only breaks on a
+// real parser — like the RETURNING list turning ambiguous once the
+// jsonb_to_recordset path alias is in scope — sails through it. This test
+// executes the exact statements on real PostgreSQL. Gated like the control-api
+// real-PG suites so one environment variable drives all of them.
+const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL;
+const describeRealPostgres = adminUrl ? describe : describe.skip;
+
+function databaseUrl(base: string, database: string): string {
+ const url = new URL(base);
+ url.pathname = `/${database}`;
+ return url.toString();
+}
+
+describeRealPostgres("renamePublication on real PostgreSQL", () => {
+ const database = `gfsc_rename_pub_${Date.now()}`;
+ let adminPool: Pool;
+ let pool: Pool;
+
+ const tx: Transactor = {
+ async transaction<T>(fn: (client: TxClient) => Promise<T>): Promise<T> {
+ const client = await pool.connect();
+ try {
+ await client.query("BEGIN");
+ const result = await fn({
+ query: (text: string, values?: unknown[]) => client.query(text, values as never[]),
+ });
+ await client.query("COMMIT");
+ return result;
+ } catch (error) {
+ await client.query("ROLLBACK").catch(() => undefined);
+ throw error;
+ } finally {
+ client.release();
+ }
+ },
+ };
+
+ const noopAudit: AuditSink = { record: async () => undefined };
+
+ beforeAll(async () => {
+ adminPool = new Pool({ connectionString: adminUrl });
+ await adminPool.query(`CREATE DATABASE ${database}`);
+ pool = new Pool({ connectionString: databaseUrl(adminUrl as string, database) });
+ // Minimal live-schema shape for the statements under test; full-schema
+ // semantics stay covered by the control-api real-PG migration suites.
+ await pool.query(`
+ CREATE TABLE gfs_resources (
+ resource_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ drive TEXT NOT NULL,
+ parent_resource_id UUID NULL,
+ name TEXT NOT NULL,
+ kind TEXT NOT NULL,
+ path_cache TEXT NULL,
+ version INTEGER NOT NULL DEFAULT 0,
+ bytes BIGINT NOT NULL DEFAULT 0,
+ blob_key TEXT NULL,
+ content_sha256 TEXT NULL,
+ deleted_at TIMESTAMPTZ NULL,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+ );
+ `);
+ });
+
+ 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 ${database}`);
+ await adminPool.end();
+ });
+
+ it("renames a folder root and rewrites every descendant path in one transaction", async () => {
+ const seeded = await pool.query(`
+ WITH drive_root AS (
+ INSERT INTO gfs_resources (drive, parent_resource_id, name, kind, path_cache)
+ VALUES ('main', NULL, '', 'directory', '/')
+ RETURNING resource_id
+ ),
+ root AS (
+ INSERT INTO gfs_resources (drive, parent_resource_id, name, kind, path_cache, version)
+ SELECT 'main', resource_id, 'projects', 'directory', '/projects', 4 FROM drive_root
+ RETURNING resource_id
+ ),
+ child_dir AS (
+ INSERT INTO gfs_resources (drive, parent_resource_id, name, kind, path_cache)
+ SELECT 'main', resource_id, 'docs', 'directory', '/projects/docs' FROM root
+ RETURNING resource_id
+ ),
+ child_file AS (
+ INSERT INTO gfs_resources (drive, parent_resource_id, name, kind, path_cache, bytes)
+ SELECT 'main', resource_id, 'notes.txt', 'file', '/projects/docs/notes.txt', 12 FROM child_dir
+ RETURNING resource_id
+ )
+ SELECT root.resource_id::text AS root_id,
+ child_dir.resource_id::text AS dir_id,
+ child_file.resource_id::text AS file_id
+ FROM root, child_dir, child_file;
+ `);
+ const { root_id: rootId, dir_id: dirId, file_id: fileId } = seeded.rows[0] as {
+ root_id: string;
+ dir_id: string;
+ file_id: string;
+ };
+
+ const renamed = await publishRename(tx, {
+ requestId: "req-rename-realpg-1",
+ subject: "host:1st:mcp-host/agent-a",
+ audit: noopAudit,
+ drive: "main",
+ resourceId: rootId,
+ newName: "archive",
+ ifMatch: 4,
+ maxObjects: 1000,
+ deadlineAtMs: Date.now() + 30_000,
+ });
+
+ expect(renamed.name).toBe("archive");
+
+ const rows = await pool.query(
+ `SELECT resource_id::text AS id, name, path_cache, version
+ FROM gfs_resources ORDER BY path_cache`
+ );
+ const byId = new Map(rows.rows.map(row => [row.id as string, row]));
+ expect(byId.get(rootId)).toMatchObject({ name: "archive", path_cache: "/archive", version: 5 });
+ expect(byId.get(dirId)).toMatchObject({ name: "docs", path_cache: "/archive/docs", version: 0 });
+ expect(byId.get(fileId)).toMatchObject({
+ name: "notes.txt",
+ path_cache: "/archive/docs/notes.txt",
+ version: 0,
+ });
+ });
+
+ // The admission bounds run through the REAL transactor here: PgTransactor
+ // arms statement_timeout on a live session and gates acquisition on the
+ // deadline, so both paths execute against the actual PostgreSQL parser and
+ // pool instead of the scripted client the unit suite uses.
+ it("rejects an oversized subtree with payload_too_large via the real LIMIT before any UPDATE", async () => {
+ const seeded = await pool.query(`
+ WITH drive_root AS (
+ INSERT INTO gfs_resources (drive, parent_resource_id, name, kind, path_cache)
+ VALUES ('bound', NULL, '', 'directory', '/')
+ RETURNING resource_id
+ ),
+ root AS (
+ INSERT INTO gfs_resources (drive, parent_resource_id, name, kind, path_cache, version)
+ SELECT 'bound', resource_id, 'big', 'directory', '/big', 1 FROM drive_root
+ RETURNING resource_id
+ ),
+ children AS (
+ INSERT INTO gfs_resources (drive, parent_resource_id, name, kind, path_cache)
+ SELECT 'bound', root.resource_id, 'file-' || n, 'file', '/big/file-' || n
+ FROM root, generate_series(1, 2) AS n
+ RETURNING resource_id
+ )
+ SELECT root.resource_id::text AS root_id FROM root;
+ `);
+ const rootId = (seeded.rows[0] as { root_id: string }).root_id;
+ const realTx = new PgTransactor(pool);
+
+ await expect(publishRename(realTx, {
+ requestId: "req-rename-realpg-2",
+ subject: "host:1st:mcp-host/agent-a",
+ audit: noopAudit,
+ drive: "bound",
+ resourceId: rootId,
+ newName: "renamed-big",
+ ifMatch: 1,
+ maxObjects: 2,
+ deadlineAtMs: Date.now() + 30_000,
+ })).rejects.toMatchObject({ code: "payload_too_large" });
+
+ const after = await pool.query(
+ `SELECT name, path_cache FROM gfs_resources WHERE drive = 'bound' AND resource_id = $1`,
+ [rootId]
+ );
+ expect(after.rows[0]).toMatchObject({ name: "big", path_cache: "/big" });
+ });
+
+ it("fails precondition_failed through the real transactor when the rename deadline is already exhausted", async () => {
+ const existing = await pool.query(
+ `SELECT resource_id::text AS id, name FROM gfs_resources
+ WHERE drive = 'bound' AND name = 'big' LIMIT 1`
+ );
+ const rootId = (existing.rows[0] as { id: string }).id;
+ const realTx = new PgTransactor(pool);
+
+ await expect(publishRename(realTx, {
+ requestId: "req-rename-realpg-3",
+ subject: "host:1st:mcp-host/agent-a",
+ audit: noopAudit,
+ drive: "bound",
+ resourceId: rootId,
+ newName: "too-late",
+ ifMatch: 1,
+ maxObjects: 1000,
+ deadlineAtMs: Date.now() - 1,
+ })).rejects.toMatchObject({
+ code: "precondition_failed",
+ message: "synchronous mutation deadline exceeded",
+ });
+
+ const after = await pool.query(
+ `SELECT name FROM gfs_resources WHERE drive = 'bound' AND resource_id = $1`,
+ [rootId]
+ );
+ expect(after.rows[0]).toMatchObject({ name: "big" });
+ });
+});
diff --git a/gfs-controller/src/db/renamePublication.test.ts b/gfs-controller/src/db/renamePublication.test.ts
new file mode 100644
index 000000000..a14dc436d
--- /dev/null
+++ b/gfs-controller/src/db/renamePublication.test.ts
@@ -0,0 +1,210 @@
+import { describe, expect, it } from "vitest";
+import type { AuditEvent, AuditSink, Queryable } from "../authz/audit";
+import type { DeadlineBudget } from "./deadlineQuery";
+import { CommitOutcomeUnknownError, GfsWriteService, type BlobWriter, type Transactor, type TxClient } from "./writeStore";
+import { PgBlobStagingStore } from "./blobStaging";
+
+const PARENT = "00000000-0000-4000-8000-000000000001";
+const TARGET = "00000000-0000-4000-8000-000000000002";
+const CHILD = "00000000-0000-4000-8000-000000000003";
+const REQUEST = "00000000-0000-4000-8000-000000000004";
+const TOMBSTONE = "00000000-0000-4000-8000-000000000005";
+const HIDDEN_LIVE = "00000000-0000-4000-8000-000000000006";
+
+function record(over: Record<string, unknown> = {}) {
+ return { resource_id: TARGET, drive: "main", parent_resource_id: PARENT, name: "old", kind: "directory",
+ path_cache: "/docs/old", version: 4, bytes: 0, blob_key: null, content_sha256: null,
+ deleted_at: null, updated_at: "2026-07-17T00:00:00.000Z", depth: 0, cycle: false,
+ under_tombstone: false, ...over };
+}
+
+class Db implements TxClient {
+ calls: Array<{ sql: string; values: unknown[] }> = [];
+ tree = [record(), record({ resource_id: CHILD, parent_resource_id: TARGET, name: "file.txt", kind: "file",
+ path_cache: "/docs/old/file.txt", version: 7, bytes: 5, blob_key: "blob/key", content_sha256: "a".repeat(64), depth: 1 })];
+ collision = false;
+ mutateSecondLoad = false;
+ loads = 0;
+ async query(sql: string, values: unknown[] = []) {
+ this.calls.push({ sql, values });
+ if (sql.includes("pg_advisory_xact_lock") || sql.includes("FOR UPDATE")) return { rows: [] };
+ if (sql.includes("WITH RECURSIVE rename_tree")) {
+ this.loads += 1;
+ if (this.loads === 2 && this.mutateSecondLoad) this.tree[1] = { ...this.tree[1], version: 8 };
+ return { rows: this.tree.filter(item => item.depth === 0 || item.deleted_at == null).map(item => ({ ...item })) };
+ }
+ if (sql.includes("SELECT path_cache, deleted_at")) return { rows: [{ path_cache: "/docs", deleted_at: null }] };
+ if (sql.includes("SELECT 1 FROM gfs_resources")) return { rows: this.collision ? [{ "?column?": 1 }] : [] };
+ if (sql.includes("UPDATE gfs_resources")) {
+ const [rootId, newName, encodedPaths] = values as [string, string, string];
+ const paths = new Map((JSON.parse(encodedPaths) as Array<{ resource_id: string; path_cache: string }>).map(item => [item.resource_id, item.path_cache]));
+ this.tree = this.tree.map(item => {
+ const path = paths.get(String(item.resource_id));
+ if (path === undefined) return item;
+ return item.resource_id === rootId
+ ? { ...item, name: newName, path_cache: path, version: Number(item.version) + 1,
+ updated_at: "2026-07-17T00:00:01.000Z" }
+ : { ...item, path_cache: path, updated_at: "2026-07-17T00:00:01.000Z" };
+ });
+ return { rows: this.tree.filter(item => paths.has(String(item.resource_id))).map(item => ({ ...item })) };
+ }
+ if (sql.includes("gfs_audit")) return { rows: [] };
+ if (sql.includes("gfs_blob_manifests")) return { rows: [] };
+ throw new Error(`unexpected query: ${sql}`);
+ }
+}
+
+class Audit implements AuditSink {
+ calls: Array<{ event: AuditEvent; transactional: boolean; budget?: DeadlineBudget }> = [];
+ async record(event: AuditEvent, queryable?: Queryable, budget?: DeadlineBudget): Promise<void> {
+ this.calls.push({ event, transactional: queryable !== undefined, budget });
+ if (queryable) await queryable.query("INSERT INTO gfs_audit DEFAULT VALUES");
+ }
+}
+
+const blobs: BlobWriter = {
+ writeImmutable: async () => ({ blobKey: "unused", bytes: 0, contentSha256: "" }),
+ verify: async () => undefined, deleteByKey: async () => undefined, deleteLegacyFlat: async () => undefined,
+};
+
+function fixture(options: { ambiguity?: "full" | "zero" | "partial"; inspectUnavailable?: boolean } = {}) {
+ const db = new Db(); const audit = new Audit();
+ const snapshot = () => db.tree.map(item => ({ ...item }));
+ let ambiguityThrown = false;
+ const recoveryBudgets: Array<DeadlineBudget | undefined> = [];
+ const tx: Transactor = { transaction: async (fn, budget) => {
+ if (ambiguityThrown) recoveryBudgets.push(budget);
+ if (ambiguityThrown && options.inspectUnavailable) throw new Error("inspection unavailable");
+ const before = snapshot(); const value = await fn(db);
+ if (options.ambiguity && !ambiguityThrown) {
+ ambiguityThrown = true;
+ if (options.ambiguity === "zero") db.tree = before;
+ if (options.ambiguity === "partial") db.tree[1] = before[1];
+ throw new CommitOutcomeUnknownError(new Error("commit response unavailable"));
+ }
+ return value;
+ } };
+ const writes = new GfsWriteService(tx, blobs, new PgBlobStagingStore(db));
+ const input = { requestId: REQUEST, subject: "agent:test", audit, drive: "main",
+ resourceId: TARGET, newName: "new", ifMatch: 4,
+ maxObjects: 1000, deadlineAtMs: Date.now() + 30_000 };
+ return { db, audit, tx, writes, input, recoveryBudgets };
+}
+
+describe("transactional rename publication", () => {
+ it("renames root and subtree paths while preserving identity, parent, drive and blob", async () => {
+ const f = fixture(); const beforeChild = { ...f.db.tree[1] };
+ const renamed = await f.writes.rename(f.input);
+ expect(renamed).toMatchObject({ resourceId: TARGET, parentResourceId: PARENT, drive: "main", name: "new", pathCache: "/docs/new", version: 5 });
+ expect(f.db.tree[1]).toMatchObject({ resource_id: CHILD, parent_resource_id: TARGET, path_cache: "/docs/new/file.txt",
+ version: beforeChild.version, blob_key: beforeChild.blob_key, content_sha256: beforeChild.content_sha256 });
+ expect(f.audit.calls).toHaveLength(1);
+ expect(f.audit.calls[0]).toMatchObject({ transactional: true, event: { op: "rename", mutationOutcome: "succeeded", resourceId: TARGET.replaceAll("-", "") } });
+ const update = f.db.calls.findIndex(call => call.sql.includes("UPDATE gfs_resources"));
+ const audit = f.db.calls.findIndex(call => call.sql.includes("gfs_audit"));
+ expect(update).toBeLessThan(audit);
+ });
+
+ it("rejects a subtree above maxObjects with payload_too_large before any UPDATE", async () => {
+ const f = fixture(); f.input.maxObjects = 1;
+ await expect(f.writes.rename(f.input)).rejects.toMatchObject({ code: "payload_too_large" });
+ expect(f.db.calls.some(call => call.sql.includes("UPDATE gfs_resources"))).toBe(false);
+ const load = f.db.calls.find(call => call.sql.includes("WITH RECURSIVE rename_tree"))!;
+ expect(load.sql).toContain("LIMIT $3");
+ expect(load.values[2]).toBe(2);
+ });
+
+ it("arms the publication transaction with the rename deadline", async () => {
+ const budgets: Array<{ deadlineAtMs: number } | undefined> = [];
+ const f = fixture();
+ const spyTx: Transactor = { transaction: async (fn, budget) => {
+ budgets.push(budget as { deadlineAtMs: number } | undefined);
+ return f.tx.transaction(fn, budget);
+ } };
+ const writes = new GfsWriteService(spyTx, blobs, new PgBlobStagingStore(f.db));
+ await expect(writes.rename(f.input)).resolves.toMatchObject({ name: "new" });
+ expect(budgets[0]).toMatchObject({ deadlineAtMs: f.input.deadlineAtMs });
+ });
+
+ it("rejects collision and stale If-Match with definitive failed audit", async () => {
+ const collision = fixture(); collision.db.collision = true;
+ await expect(collision.writes.rename(collision.input)).rejects.toMatchObject({ code: "already_exists" });
+ expect(collision.audit.calls.at(-1)).toMatchObject({ transactional: false, event: { mutationOutcome: "failed" } });
+ const stale = fixture(); stale.input.ifMatch = 3;
+ await expect(stale.writes.rename(stale.input)).rejects.toMatchObject({ code: "precondition_failed" });
+ });
+
+ it("rejects a concurrent subtree mutation after deterministic row locking", async () => {
+ const f = fixture(); f.db.mutateSecondLoad = true;
+ await expect(f.writes.rename(f.input)).rejects.toMatchObject({ code: "precondition_failed" });
+ expect(f.db.calls.find(call => call.sql.includes("FOR UPDATE"))?.values[0]).toEqual([PARENT, TARGET, CHILD].sort());
+ });
+
+ it("rejects a corrupt descendant path instead of propagating its prefix", async () => {
+ const f = fixture(); f.db.tree[1].path_cache = "/docs/old/wrong/file.txt";
+ await expect(f.writes.rename(f.input)).rejects.toMatchObject({ code: "precondition_failed" });
+ expect(f.db.calls.some(call => call.sql.includes("UPDATE gfs_resources"))).toBe(false);
+ });
+
+ it("renames the live tree without rewriting historical tombstoned descendants", async () => {
+ const f = fixture();
+ const deletedAt = new Date("2026-01-01T00:00:00.000Z");
+ f.db.tree.push(record({ resource_id: TOMBSTONE, parent_resource_id: TARGET, name: "old.txt", kind: "file",
+ path_cache: "/docs/old/old.txt", version: 2, deleted_at: deletedAt, depth: 1 }));
+
+ await expect(f.writes.rename(f.input)).resolves.toMatchObject({ name: "new", pathCache: "/docs/new" });
+
+ expect(f.db.tree.find(item => item.resource_id === TOMBSTONE)).toMatchObject({
+ path_cache: "/docs/old/old.txt", version: 2, deleted_at: deletedAt,
+ });
+ const update = f.db.calls.find(call => call.sql.includes("UPDATE gfs_resources"))!;
+ expect(JSON.parse(String(update.values[2]))).not.toEqual(expect.arrayContaining([
+ expect.objectContaining({ resource_id: TOMBSTONE }),
+ ]));
+ const load = f.db.calls.find(call => call.sql.includes("WITH RECURSIVE rename_tree"))!;
+ expect(load.sql).toContain("WHERE depth = 0 OR deleted_at IS NULL");
+ });
+
+ it("rejects a corrupt live descendant reached through a tombstoned ancestor", async () => {
+ const f = fixture();
+ f.db.tree.push(
+ record({ resource_id: TOMBSTONE, parent_resource_id: TARGET, name: "old", kind: "directory",
+ path_cache: "/docs/old/old", deleted_at: new Date("2026-01-01T00:00:00.000Z"), depth: 1,
+ under_tombstone: true }),
+ record({ resource_id: HIDDEN_LIVE, parent_resource_id: TOMBSTONE, name: "live.txt", kind: "file",
+ path_cache: "/docs/old/old/live.txt", depth: 2, under_tombstone: true }),
+ );
+
+ await expect(f.writes.rename(f.input)).rejects.toMatchObject({ code: "precondition_failed" });
+ expect(f.db.calls.some(call => call.sql.includes("UPDATE gfs_resources"))).toBe(false);
+ });
+
+ it("returns success when a fresh bounded read proves the full rename committed", async () => {
+ const f = fixture({ ambiguity: "full" });
+ await expect(f.writes.rename(f.input)).resolves.toMatchObject({ name: "new", pathCache: "/docs/new", version: 5 });
+ expect(f.audit.calls).toHaveLength(1);
+ expect(f.audit.calls[0]).toMatchObject({ transactional: true, event: { mutationOutcome: "succeeded" } });
+ expect(f.recoveryBudgets).toHaveLength(1);
+ expect(f.recoveryBudgets[0]).toMatchObject({ deadlineAtMs: expect.any(Number) });
+ expect(f.recoveryBudgets[0]?.signal).toBeUndefined();
+ });
+
+ it("records a bounded failed outcome only when a fresh read proves zero mutation", async () => {
+ const f = fixture({ ambiguity: "zero" });
+ await expect(f.writes.rename(f.input)).rejects.toMatchObject({ name: "CommitOutcomeUnknownError" });
+ expect(f.audit.calls.map(call => call.event.mutationOutcome)).toEqual(["succeeded", "failed"]);
+ expect(f.audit.calls[1]).toMatchObject({ transactional: false, budget: { deadlineAtMs: expect.any(Number) } });
+ expect(f.recoveryBudgets).toHaveLength(1);
+ });
+
+ it.each([
+ { name: "partial state", options: { ambiguity: "partial" as const } },
+ { name: "unqueryable state", options: { ambiguity: "full" as const, inspectUnavailable: true } },
+ ])("keeps $name unknown without a fabricated failed outcome", async ({ options }) => {
+ const f = fixture(options);
+ await expect(f.writes.rename(f.input)).rejects.toMatchObject({ name: "CommitOutcomeUnknownError" });
+ expect(f.audit.calls).toHaveLength(1);
+ expect(f.audit.calls[0]).toMatchObject({ transactional: true, event: { mutationOutcome: "succeeded" } });
+ expect(f.recoveryBudgets).toHaveLength(1);
+ });
+});
diff --git a/gfs-controller/src/db/renamePublication.ts b/gfs-controller/src/db/renamePublication.ts
new file mode 100644
index 000000000..aa70bb390
--- /dev/null
+++ b/gfs-controller/src/db/renamePublication.ts
@@ -0,0 +1,282 @@
+import type { AuditSink } from "../authz/audit";
+import { GfsError } from "../api/errors";
+import type { GfsResource } from "../api/read";
+import { normalizeResourceId } from "../storage/paths";
+import type { CommitOutcomeUnknownError, Transactor, TxClient } from "./writeStore";
+
+const AMBIGUOUS_COMMIT_INSPECTION_MS = 2_000;
+const POST_FAILURE_AUDIT_MS = 2_000;
+
+export interface RenameInput {
+ requestId: string;
+ subject: string;
+ audit: AuditSink;
+ drive: string;
+ resourceId: string;
+ newName: string;
+ ifMatch: number;
+ /** Maximum live subtree size admitted by one synchronous rename. */
+ maxObjects: number;
+ /** Absolute deadline; arms statement_timeout on the publication transaction. */
+ deadlineAtMs: number;
+ now?: () => number;
+}
+
+interface Row {
+ resourceId: string;
+ drive: string;
+ parentResourceId: string | null;
+ name: string;
+ kind: "file" | "directory";
+ pathCache: string | null;
+ version: number;
+ bytes: number;
+ blobKey: string | null;
+ contentSha256: string | null;
+ deletedAt: string | null;
+ updatedAt: string | null;
+ depth: number;
+ cycle: boolean;
+ underTombstone: boolean;
+}
+
+const COLUMNS = "resource_id, drive, parent_resource_id, name, kind, path_cache, version, bytes, blob_key, content_sha256, deleted_at, updated_at";
+// The publication UPDATE joins jsonb_to_recordset AS path(resource_id, ...),
+// so its RETURNING list must qualify every column: an unqualified resource_id
+// there is ambiguous between the updated row and the path record set.
+const RETURNING_COLUMNS = COLUMNS.split(", ")
+ .map(column => `resource.${column}`)
+ .join(", ");
+
+function dbId(value: string): string {
+ const rid = normalizeResourceId(value);
+ return `${rid.slice(0, 8)}-${rid.slice(8, 12)}-${rid.slice(12, 16)}-${rid.slice(16, 20)}-${rid.slice(20)}`;
+}
+
+function iso(value: unknown): string | null {
+ if (value == null) return null;
+ return value instanceof Date ? value.toISOString() : String(value);
+}
+
+function row(value: Record<string, unknown>): Row {
+ return {
+ resourceId: String(value.resource_id), drive: String(value.drive),
+ parentResourceId: value.parent_resource_id == null ? null : String(value.parent_resource_id),
+ name: String(value.name), kind: String(value.kind) === "directory" ? "directory" : "file",
+ pathCache: value.path_cache == null ? null : String(value.path_cache), version: Number(value.version),
+ bytes: Number(value.bytes), blobKey: value.blob_key == null ? null : String(value.blob_key),
+ contentSha256: value.content_sha256 == null ? null : String(value.content_sha256),
+ deletedAt: iso(value.deleted_at), updatedAt: iso(value.updated_at),
+ depth: Number(value.depth ?? 0), cycle: value.cycle === true,
+ underTombstone: value.under_tombstone === true,
+ };
+}
+
+function resource(value: Row): GfsResource {
+ return { resourceId: value.resourceId, drive: value.drive, parentResourceId: value.parentResourceId,
+ name: value.name, kind: value.kind, pathCache: value.pathCache, version: value.version,
+ bytes: value.bytes, blobKey: value.blobKey, contentSha256: value.contentSha256, deletedAt: value.deletedAt };
+}
+
+function same(a: readonly Row[], b: readonly Row[]): boolean {
+ return a.length === b.length && a.every((item, index) => {
+ const other = b[index];
+ return other !== undefined && JSON.stringify(item) === JSON.stringify(other);
+ });
+}
+
+// The drive predicate on the recursive join is redundant with validateTree's
+// cross-drive rejection, but it lets the planner drive-lead the
+// (drive, parent_resource_id) index instead of scanning per recursion level.
+// LIMIT bounds the rows materialized into this process; the SQL-side work is
+// bounded by the transaction's statement_timeout.
+async function loadTree(client: TxClient, drive: string, resourceId: string, limit: number): Promise<Row[]> {
+ const result = await client.query(
+ `WITH RECURSIVE rename_tree AS (
+ SELECT r.*, 0 AS depth, ARRAY[r.resource_id]::uuid[] AS visited,
+ false AS cycle, false AS under_tombstone
+ FROM gfs_resources r WHERE r.drive = $1 AND r.resource_id = $2
+ UNION ALL
+ SELECT child.*, parent.depth + 1, parent.visited || child.resource_id,
+ child.resource_id = ANY(parent.visited) AS cycle,
+ parent.under_tombstone OR child.deleted_at IS NOT NULL AS under_tombstone
+ FROM rename_tree parent
+ JOIN gfs_resources child ON child.drive = $1 AND child.parent_resource_id = parent.resource_id
+ WHERE NOT parent.cycle
+ )
+ SELECT ${COLUMNS}, depth, cycle, under_tombstone
+ FROM rename_tree
+ WHERE depth = 0 OR deleted_at IS NULL
+ ORDER BY resource_id
+ LIMIT $3`,
+ [drive, resourceId, limit]
+ );
+ return result.rows.map(row);
+}
+
+function loadLimit(input: RenameInput): number {
+ return input.maxObjects + 1;
+}
+
+function assertWithinLimit(tree: readonly Row[], input: RenameInput): void {
+ if (tree.length > input.maxObjects) {
+ throw new GfsError("payload_too_large", "rename subtree exceeds the synchronous rename object limit");
+ }
+}
+
+function validateTree(tree: readonly Row[], input: RenameInput): { root: Row; oldPath: string } {
+ const root = tree.find(item => item.resourceId === dbId(input.resourceId) && item.depth === 0);
+ if (!root) throw new GfsError("not_found", "rename resource not found");
+ if (root.parentResourceId === null) throw new GfsError("path_invalid", "drive root cannot be renamed");
+ if (root.deletedAt !== null) throw GfsError.gone("resource is deleted", "resource_deleted");
+ if (root.version !== input.ifMatch) throw new GfsError("precondition_failed", "rename If-Match is stale");
+ const ids = new Set<string>();
+ for (const item of tree) {
+ if (ids.has(item.resourceId) || item.cycle || item.underTombstone
+ || item.drive !== input.drive || item.deletedAt !== null) {
+ throw new GfsError("precondition_failed", "rename subtree is not a stable live tree");
+ }
+ ids.add(item.resourceId);
+ }
+ return { root, oldPath: root.pathCache ?? "" };
+}
+
+function childPath(parentPath: string, name: string): string {
+ return parentPath === "/" ? `/${name}` : `${parentPath}/${name}`;
+}
+
+function buildPaths(tree: readonly Row[], root: Row, parentPath: string, newName: string) {
+ const oldPaths = new Map<string, string>();
+ const newPaths = new Map<string, string>();
+ const ordered = [...tree].sort((a, b) => a.depth - b.depth || a.resourceId.localeCompare(b.resourceId));
+ for (const item of ordered) {
+ if (item.resourceId === root.resourceId) {
+ const expected = childPath(parentPath, item.name);
+ if (item.pathCache !== expected) throw new GfsError("precondition_failed", "rename root path is non-canonical");
+ oldPaths.set(item.resourceId, expected);
+ newPaths.set(item.resourceId, childPath(parentPath, newName));
+ continue;
+ }
+ if (item.parentResourceId === null) throw new GfsError("precondition_failed", "rename subtree parent map is inconsistent");
+ const oldParentPath = oldPaths.get(item.parentResourceId);
+ const newParentPath = newPaths.get(item.parentResourceId);
+ if (!oldParentPath || !newParentPath) throw new GfsError("precondition_failed", "rename subtree parent map is inconsistent");
+ const expected = childPath(oldParentPath, item.name);
+ if (item.pathCache !== expected) throw new GfsError("precondition_failed", "rename descendant path is non-canonical");
+ oldPaths.set(item.resourceId, expected);
+ newPaths.set(item.resourceId, childPath(newParentPath, item.name));
+ }
+ return ordered.map(item => ({ resourceId: item.resourceId, pathCache: newPaths.get(item.resourceId)! }));
+}
+
+function auditEvent(input: RenameInput, outcome: "succeeded" | "failed", reason?: string) {
+ return {
+ recordType: "mutation_outcome" as const, subject: input.subject, op: "rename",
+ resourceId: normalizeResourceId(input.resourceId), drive: input.drive,
+ outcome: outcome === "succeeded" ? "allow" as const : "error" as const,
+ reason, requestId: input.requestId, matchedSubject: null,
+ authorizationSource: null, cachedAuthorizationSource: null, mutationOutcome: outcome,
+ };
+}
+
+function recoveryBudget(durationMs: number) {
+ return { deadlineAtMs: Date.now() + durationMs };
+}
+
+async function inspectAmbiguousRename(
+ tx: Transactor,
+ input: RenameInput,
+ before: readonly Row[],
+ expected: readonly Row[]
+): Promise<"full" | "zero" | "unsafe"> {
+ try {
+ return await tx.transaction(async client => {
+ const current = await loadTree(client, input.drive, dbId(input.resourceId), loadLimit(input));
+ if (same(current, expected)) return "full";
+ if (same(current, before)) return "zero";
+ return "unsafe";
+ }, recoveryBudget(AMBIGUOUS_COMMIT_INSPECTION_MS));
+ } catch {
+ return "unsafe";
+ }
+}
+
+export async function publishRename(tx: Transactor, input: RenameInput): Promise<GfsResource> {
+ let before: Row[] | undefined;
+ let expected: Row[] | undefined;
+ let expectedRoot: GfsResource | undefined;
+ try {
+ return await tx.transaction(async client => {
+ await client.query(`SELECT pg_advisory_xact_lock(hashtext('gfs:structure:' || $1)::bigint)`, [input.drive]);
+ const observed = await loadTree(client, input.drive, dbId(input.resourceId), loadLimit(input));
+ assertWithinLimit(observed, input);
+ const { root } = validateTree(observed, input);
+ const lockIds = [...new Set([...observed.map(item => item.resourceId), root.parentResourceId!])].sort();
+ await client.query(`SELECT resource_id FROM gfs_resources WHERE resource_id = ANY($1::uuid[]) ORDER BY resource_id FOR UPDATE`, [lockIds]);
+ const locked = await loadTree(client, input.drive, dbId(input.resourceId), loadLimit(input));
+ assertWithinLimit(locked, input);
+ if (!same(observed, locked)) throw new GfsError("precondition_failed", "rename subtree changed concurrently");
+ validateTree(locked, input);
+ const parent = await client.query(`SELECT path_cache, deleted_at FROM gfs_resources WHERE drive = $1 AND resource_id = $2`, [input.drive, root.parentResourceId]);
+ const parentRow = parent.rows[0];
+ if (!parentRow || parentRow.deleted_at != null || typeof parentRow.path_cache !== "string") {
+ throw new GfsError("precondition_failed", "rename parent changed concurrently");
+ }
+ const paths = buildPaths(locked, root, parentRow.path_cache, input.newName);
+ const pathById = new Map(paths.map(item => [item.resourceId, item.pathCache]));
+ const collision = await client.query(`SELECT 1 FROM gfs_resources WHERE drive = $1 AND parent_resource_id = $2 AND name = $3 AND resource_id <> $4 AND deleted_at IS NULL LIMIT 1`, [input.drive, root.parentResourceId, input.newName, root.resourceId]);
+ if (collision.rows.length > 0) throw new GfsError("already_exists", `a resource named '${input.newName}' already exists here`);
+ let updated;
+ try { updated = await client.query(
+ `UPDATE gfs_resources AS resource SET
+ name = CASE WHEN resource.resource_id = $1 THEN $2 ELSE resource.name END,
+ path_cache = path.path_cache,
+ version = CASE WHEN resource.resource_id = $1 THEN resource.version + 1 ELSE resource.version END,
+ updated_at = now()
+ FROM jsonb_to_recordset($3::jsonb) AS path(resource_id uuid, path_cache text)
+ WHERE resource.drive = $4 AND resource.resource_id = path.resource_id
+ RETURNING ${RETURNING_COLUMNS}`,
+ [root.resourceId, input.newName, JSON.stringify(paths.map(item => ({ resource_id: item.resourceId, path_cache: item.pathCache }))), input.drive]
+ ); } catch (error) {
+ if ((error as { code?: string }).code === "23505") {
+ throw new GfsError("already_exists", `a resource named '${input.newName}' already exists here`);
+ }
+ throw error;
+ }
+ const updatedRoot = updated.rows.find(item => String(item.resource_id) === root.resourceId);
+ if (!updatedRoot || updated.rows.length !== observed.length) throw new Error("rename update set was incomplete");
+ before = locked.map(item => ({ ...item }));
+ const updatedById = new Map(updated.rows.map(item => [String(item.resource_id), row(item)]));
+ expected = locked.map(item => {
+ const updatedItem = updatedById.get(item.resourceId);
+ if (!updatedItem || updatedItem.pathCache !== pathById.get(item.resourceId)) {
+ throw new Error("rename returned an inconsistent update set");
+ }
+ return { ...updatedItem, depth: item.depth, cycle: item.cycle };
+ });
+ expectedRoot = resource(row(updatedRoot));
+ await input.audit.record(auditEvent(input, "succeeded"), client);
+ return expectedRoot;
+ }, { deadlineAtMs: input.deadlineAtMs, now: input.now });
+ } catch (error) {
+ if ((error as Error).name === "CommitOutcomeUnknownError") {
+ if (before && expected && expectedRoot) {
+ // The request that lost COMMIT may already be cancelled or expired.
+ // Resolve once on a fresh bounded connection before reporting failure
+ // or treating the committed rename as unknown.
+ const outcome = await inspectAmbiguousRename(tx, input, before, expected);
+ if (outcome === "full") return expectedRoot;
+ if (outcome === "zero") {
+ await input.audit.record(
+ auditEvent(input, "failed", "internal_error"),
+ undefined,
+ recoveryBudget(POST_FAILURE_AUDIT_MS)
+ );
+ }
+ }
+ throw error as CommitOutcomeUnknownError;
+ }
+ await input.audit.record(auditEvent(input, "failed", error instanceof GfsError ? error.code : "internal_error"));
+ throw error;
+ }
+}
diff --git a/gfs-controller/src/db/resourceStore.test.ts b/gfs-controller/src/db/resourceStore.test.ts
index 33df0358a..0201f7555 100644
--- a/gfs-controller/src/db/resourceStore.test.ts
+++ b/gfs-controller/src/db/resourceStore.test.ts
@@ -11,7 +11,7 @@ function fakeDb(responses: Array<Record<string, unknown>[]>): Queryable & {
} {
const calls: Array<{ text: string; values: unknown[] }> = [];
let i = 0;
- return {
+ const db: Queryable & { calls: Array<{ text: string; values: unknown[] }> } = {
calls,
async query(text: string, values: unknown[] = []) {
calls.push({ text, values });
@@ -19,6 +19,16 @@ function fakeDb(responses: Array<Record<string, unknown>[]>): Queryable & {
return { rows };
},
};
+ db.connect = async () => ({
+ query: async (text: string, values: unknown[] = []) => {
+ calls.push({ text, values });
+ if (text === "BEGIN READ ONLY" || text === "COMMIT" || text === "ROLLBACK" || text.includes("set_config('statement_timeout'")) return { rows: [] };
+ const rows = responses[i++] ?? [];
+ return { rows };
+ },
+ release: () => undefined,
+ });
+ return db;
}
/** A representative `gfs_resources` row as node-postgres returns it (raw pg types). */
@@ -32,6 +42,8 @@ function pgRow(over: Record<string, unknown> = {}): Record<string, unknown> {
path_cache: "/docs/report.pdf",
version: 3,
bytes: "1048576", // BIGINT → string from node-postgres
+ blob_key: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/11111111-1111-4111-8111-111111111111",
+ content_sha256: "b".repeat(64),
deleted_at: null,
...over,
};
@@ -53,6 +65,8 @@ describe("PgResourceStore.getResource", () => {
pathCache: "/docs/report.pdf",
version: 3,
bytes: 1048576,
+ blobKey: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/11111111-1111-4111-8111-111111111111",
+ contentSha256: "b".repeat(64),
deletedAt: null,
});
expect(typeof res?.bytes).toBe("number");
@@ -60,6 +74,15 @@ describe("PgResourceStore.getResource", () => {
expect(db.calls[0].values).toEqual(["main", "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"]);
});
+ it("maps legacy rows with no generation pointer without inventing one", async () => {
+ const db = fakeDb([[pgRow({ blob_key: null, content_sha256: null })]]);
+ const resource = await new PgResourceStore(db).getResource(
+ "main",
+ "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
+ );
+ expect(resource).toMatchObject({ blobKey: null, contentSha256: null });
+ });
+
it("RETURNS a tombstoned row (deletedAt set) — requireLive maps it to 410, not 404", async () => {
const deletedAt = new Date("2026-06-01T12:00:00.000Z");
const db = fakeDb([[pgRow({ deleted_at: deletedAt })]]);
@@ -168,3 +191,99 @@ describe("PgResourceStore.listChildren", () => {
).toEqual([]);
});
});
+
+describe("PgResourceStore copy snapshots", () => {
+ it("loads only the two direct admission rows and applies the remaining SQL timeout", async () => {
+ const db = fakeDb([[
+ pgRow({ record_type: "source", depth: 0, cycle: false, under_tombstone: false }),
+ pgRow({ record_type: "destination", resource_id: "cccccccc-cccc-cccc-cccc-cccccccccccc", kind: "directory", depth: 0, cycle: false, under_tombstone: false }),
+ ]]);
+ const controller = new AbortController();
+ const admission = await new PgResourceStore(db).loadCopyAdmission(
+ "main", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "cccccccccccccccccccccccccccccccc",
+ { deadlineAtMs: 5000, now: () => 1250, signal: controller.signal }
+ );
+ expect(admission.sourceRoot?.resourceId).toBe("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa");
+ expect(admission.destinationParent?.resourceId).toBe("cccccccc-cccc-cccc-cccc-cccccccccccc");
+ expect(db.calls.map(call => call.text)).toEqual([
+ "BEGIN READ ONLY", "SELECT set_config('statement_timeout', $1, true)", expect.stringContaining("WITH admission AS"), "COMMIT",
+ ]);
+ expect(db.calls[1].values).toEqual(["3750"]);
+ expect(db.calls[2].values).toEqual([
+ "main", "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "cccccccc-cccc-cccc-cccc-cccccccccccc",
+ ]);
+ expect(db.calls[2].text).not.toContain("RECURSIVE");
+ });
+
+ it("fails before querying when the copy query budget is exhausted", async () => {
+ const db = fakeDb([]);
+ await expect(new PgResourceStore(db).loadCopyAdmission(
+ "main", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "cccccccccccccccccccccccccccccccc",
+ { deadlineAtMs: 100, now: () => 100 }
+ )).rejects.toMatchObject({ code: "precondition_failed" });
+ expect(db.calls).toEqual([]);
+ });
+
+ it("loads a recursive source snapshot in one query, preserving BIGINT bytes and cycle rows", async () => {
+ const db = fakeDb([[
+ pgRow({ depth: 0, cycle: false, bytes: "9007199254740991" }),
+ pgRow({ resource_id: "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", depth: 1, cycle: true, bytes: "0" }),
+ ]]);
+ const store = new PgResourceStore(db);
+
+ const rows = await store.loadCopySnapshot("main", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 1001n);
+
+ expect(db.calls).toHaveLength(1);
+ expect(db.calls[0].values).toEqual(["main", "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", 1001n]);
+ expect(db.calls[0].text).toContain("WITH RECURSIVE source_tree");
+ expect(db.calls[0].text).toContain("child.resource_id = ANY(parent.visited) AS cycle");
+ expect(db.calls[0].text).not.toContain("child.drive = parent.drive");
+ expect(db.calls[0].text).toContain("WHERE NOT parent.cycle");
+ expect(db.calls[0].text).toContain("parent.under_tombstone OR child.deleted_at IS NOT NULL AS under_tombstone");
+ expect(db.calls[0].text).toContain("WHERE depth = 0 OR deleted_at IS NULL");
+ expect(db.calls[0].text).not.toContain("r.deleted_at IS NULL");
+ expect(db.calls[0].text).not.toContain("ORDER BY depth ASC, resource_id ASC");
+ expect(db.calls[0].text).toContain("LIMIT $3");
+ expect(rows[0].bytes).toBe(9007199254740991n);
+ expect(rows[0].pathCache).toBe("/docs/report.pdf");
+ expect(rows[1].cycle).toBe(true);
+ });
+
+ it("keeps the source root observable but excludes historical tombstoned descendants", async () => {
+ const db = fakeDb([[pgRow({ depth: 0, cycle: false, kind: "directory", bytes: "0" })]]);
+ const rows = await new PgResourceStore(db).loadCopySnapshot("main", "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", 1001n);
+ expect(rows).toHaveLength(1);
+ expect(db.calls[0].text).toContain("WHERE r.drive = $1 AND r.resource_id = $2");
+ expect(db.calls[0].text).toContain("WHERE depth = 0 OR deleted_at IS NULL");
+ });
+
+ it("loads destination ancestry and children in one consistent query", async () => {
+ const db = fakeDb([[
+ pgRow({ record_type: "ancestor", resource_id: "cccccccc-cccc-cccc-cccc-cccccccccccc", kind: "directory", depth: 0, cycle: false, bytes: "0" }),
+ pgRow({ record_type: "child", resource_id: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee", name: "existing", depth: 0, cycle: false }),
+ ]]);
+ const store = new PgResourceStore(db);
+
+ const result = await store.loadCopyDestination("main", "cccccccccccccccccccccccccccccccc", "existing");
+
+ expect(db.calls).toHaveLength(1);
+ expect(db.calls[0].values).toEqual(["main", "cccccccc-cccc-cccc-cccc-cccccccccccc", "existing"]);
+ expect(db.calls[0].text).toContain("WITH RECURSIVE destination_ancestors");
+ expect(db.calls[0].text).toContain("parent.resource_id = ANY(child.visited) AS cycle");
+ expect(db.calls[0].text).not.toContain("parent.drive = child.drive");
+ expect(db.calls[0].text).toContain("'child' AS record_type");
+ expect(db.calls[0].text).toContain("child.deleted_at IS NULL");
+ expect(db.calls[0].text).toContain("child.name = $3");
+ expect(result.ancestors[0]).toMatchObject({ resourceId: "cccccccc-cccc-cccc-cccc-cccccccccccc", bytes: 0n });
+ expect(result.liveChildren).toEqual([{ resourceId: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee", name: "existing" }]);
+ });
+
+ it("returns empty bounded snapshots when source and destination do not exist", async () => {
+ const db = fakeDb([[], []]);
+ const store = new PgResourceStore(db);
+ const missing = "ffffffff-ffff-ffff-ffff-ffffffffffff";
+ expect(await store.loadCopySnapshot("main", missing, 1001n)).toEqual([]);
+ expect(await store.loadCopyDestination("main", missing, "missing")).toEqual({ ancestors: [], liveChildren: [] });
+ expect(db.calls).toHaveLength(2);
+ });
+});
diff --git a/gfs-controller/src/db/resourceStore.ts b/gfs-controller/src/db/resourceStore.ts
index ac77ed633..78139df72 100644
--- a/gfs-controller/src/db/resourceStore.ts
+++ b/gfs-controller/src/db/resourceStore.ts
@@ -1,5 +1,7 @@
import { GfsResource, ResourceStore } from "../api/read";
+import type { CopyDestinationSnapshot, CopySnapshotNode } from "../api/copy";
import { normalizeResourceId } from "../storage/paths";
+import { withDeadlineTransaction, type DeadlineBudget, type DeadlineClient } from "./deadlineQuery";
/**
* Postgres-backed ResourceStore (the metadata side of the read path).
@@ -19,6 +21,24 @@ import { normalizeResourceId } from "../storage/paths";
/** Minimal query surface — a pg Pool satisfies this; tests inject a fake. */
export interface Queryable {
query(text: string, values?: unknown[]): Promise<{ rows: Record<string, unknown>[] }>;
+ connect?: () => Promise<DeadlineClient>;
+}
+
+export type CopyQueryBudget = DeadlineBudget;
+
+export interface CopyAdmissionSnapshot {
+ sourceRoot: CopySnapshotNode | null;
+ destinationParent: CopySnapshotNode | null;
+}
+
+async function copyQuery(
+ db: Queryable,
+ text: string,
+ values: unknown[],
+ budget?: CopyQueryBudget
+): Promise<{ rows: Record<string, unknown>[] }> {
+ if (!budget) return db.query(text, values);
+ return withDeadlineTransaction(db, budget, true, client => client.query(text, values));
}
function toIsoOrNull(value: unknown): string | null {
@@ -37,12 +57,33 @@ function rowToResource(row: Record<string, unknown>): GfsResource {
pathCache: row.path_cache == null ? null : String(row.path_cache),
version: Number(row.version),
bytes: Number(row.bytes),
+ blobKey: row.blob_key == null ? null : String(row.blob_key),
+ contentSha256: row.content_sha256 == null ? null : String(row.content_sha256),
deletedAt: toIsoOrNull(row.deleted_at),
};
}
+function rowToCopyNode(row: Record<string, unknown>): CopySnapshotNode {
+ return {
+ resourceId: String(row.resource_id),
+ drive: String(row.drive),
+ parentResourceId: row.parent_resource_id == null ? null : String(row.parent_resource_id),
+ name: String(row.name),
+ kind: String(row.kind) === "directory" ? "directory" : "file",
+ pathCache: row.path_cache == null ? null : String(row.path_cache),
+ version: Number(row.version),
+ bytes: BigInt(String(row.bytes)),
+ blobKey: row.blob_key == null ? null : String(row.blob_key),
+ contentSha256: row.content_sha256 == null ? null : String(row.content_sha256),
+ deletedAt: toIsoOrNull(row.deleted_at),
+ depth: Number(row.depth),
+ cycle: Boolean(row.cycle),
+ underTombstone: Boolean(row.under_tombstone),
+ };
+}
+
const SELECT_COLUMNS =
- "resource_id, drive, parent_resource_id, name, kind, path_cache, version, bytes, deleted_at";
+ "resource_id, drive, parent_resource_id, name, kind, path_cache, version, bytes, blob_key, content_sha256, deleted_at";
function toDbResourceId(resourceId: string): string {
const rid = normalizeResourceId(resourceId);
@@ -94,4 +135,117 @@ export class PgResourceStore implements ResourceStore {
);
return res.rows.map(rowToResource);
}
+
+ /** Cheap direct metadata admission before any recursive tree materialization. */
+ async loadCopyAdmission(
+ drive: string,
+ sourceResourceId: string,
+ destinationParentId: string,
+ budget?: CopyQueryBudget
+ ): Promise<CopyAdmissionSnapshot> {
+ const values: unknown[] = [drive, toDbResourceId(sourceResourceId), toDbResourceId(destinationParentId)];
+ const res = await copyQuery(this.db,
+ `WITH admission AS (
+ SELECT 'source' AS record_type, ${SELECT_COLUMNS}
+ FROM gfs_resources
+ WHERE drive = $1 AND resource_id = $2
+ UNION ALL
+ SELECT 'destination' AS record_type, ${SELECT_COLUMNS}
+ FROM gfs_resources
+ WHERE drive = $1 AND resource_id = $3
+ )
+ SELECT *, 0 AS depth, false AS cycle, false AS under_tombstone FROM admission`,
+ values,
+ budget
+ );
+ const source = res.rows.find(row => row.record_type === "source");
+ const destination = res.rows.find(row => row.record_type === "destination");
+ return {
+ sourceRoot: source ? rowToCopyNode(source) : null,
+ destinationParent: destination ? rowToCopyNode(destination) : null,
+ };
+ }
+
+ /** Load a complete source subtree with one deterministic recursive query. */
+ async loadCopySnapshot(drive: string, sourceResourceId: string, limit: bigint, budget?: CopyQueryBudget): Promise<CopySnapshotNode[]> {
+ const sourceId = toDbResourceId(sourceResourceId);
+ const values: unknown[] = [drive, sourceId, limit];
+ const res = await copyQuery(this.db,
+ `WITH RECURSIVE source_tree AS (
+ SELECT r.resource_id, r.drive, r.parent_resource_id, r.name, r.kind, r.path_cache,
+ r.version, r.bytes, r.blob_key, r.content_sha256, r.deleted_at,
+ 0 AS depth, ARRAY[r.resource_id]::uuid[] AS visited, false AS cycle,
+ false AS under_tombstone
+ FROM gfs_resources r
+ WHERE r.drive = $1 AND r.resource_id = $2
+ UNION ALL
+ SELECT child.resource_id, child.drive, child.parent_resource_id, child.name, child.kind, child.path_cache,
+ child.version, child.bytes, child.blob_key, child.content_sha256, child.deleted_at,
+ parent.depth + 1, parent.visited || child.resource_id,
+ child.resource_id = ANY(parent.visited) AS cycle,
+ parent.under_tombstone OR child.deleted_at IS NOT NULL AS under_tombstone
+ FROM source_tree parent
+ JOIN gfs_resources child
+ ON child.drive = $1 AND child.parent_resource_id = parent.resource_id
+ WHERE NOT parent.cycle
+ )
+ SELECT resource_id, drive, parent_resource_id, name, kind, path_cache, version, bytes,
+ blob_key, content_sha256, deleted_at, depth, cycle, under_tombstone
+ FROM source_tree
+ WHERE depth = 0 OR deleted_at IS NULL
+ LIMIT $3`,
+ values,
+ budget
+ );
+ return res.rows.map(rowToCopyNode);
+ }
+
+ /**
+ * Load destination ancestry and live direct children in one statement so the
+ * collision set and ancestry are one database observation, never an N+1 loop.
+ */
+ async loadCopyDestination(drive: string, destinationParentId: string, rootName: string, budget?: CopyQueryBudget): Promise<CopyDestinationSnapshot> {
+ const destinationId = toDbResourceId(destinationParentId);
+ const values: unknown[] = [drive, destinationId, rootName];
+ const res = await copyQuery(this.db,
+ `WITH RECURSIVE destination_ancestors AS (
+ SELECT r.resource_id, r.drive, r.parent_resource_id, r.name, r.kind, r.path_cache,
+ r.version, r.bytes, r.blob_key, r.content_sha256, r.deleted_at,
+ 0 AS depth, ARRAY[r.resource_id]::uuid[] AS visited, false AS cycle,
+ false AS under_tombstone
+ FROM gfs_resources r
+ WHERE r.drive = $1 AND r.resource_id = $2
+ UNION ALL
+ SELECT parent.resource_id, parent.drive, parent.parent_resource_id, parent.name, parent.kind, parent.path_cache,
+ parent.version, parent.bytes, parent.blob_key, parent.content_sha256, parent.deleted_at,
+ child.depth + 1, child.visited || parent.resource_id,
+ parent.resource_id = ANY(child.visited) AS cycle,
+ false AS under_tombstone
+ FROM destination_ancestors child
+ JOIN gfs_resources parent
+ ON parent.resource_id = child.parent_resource_id
+ WHERE NOT child.cycle
+ )
+ SELECT 'ancestor' AS record_type, resource_id, drive, parent_resource_id,
+ name, kind, path_cache, version, bytes, blob_key, content_sha256, deleted_at, depth, cycle, under_tombstone
+ FROM destination_ancestors
+ UNION ALL
+ SELECT 'child' AS record_type, child.resource_id, child.drive, child.parent_resource_id,
+ child.name, child.kind, child.path_cache, child.version, child.bytes, child.blob_key,
+ child.content_sha256, child.deleted_at, 0 AS depth, false AS cycle,
+ false AS under_tombstone
+ FROM gfs_resources child
+ WHERE child.drive = $1 AND child.parent_resource_id = $2
+ AND child.deleted_at IS NULL AND child.name = $3
+ ORDER BY record_type ASC, depth ASC, resource_id ASC`,
+ values,
+ budget
+ );
+ const ancestorRows = res.rows.filter(row => row.record_type === "ancestor");
+ const childRows = res.rows.filter(row => row.record_type === "child");
+ return {
+ ancestors: ancestorRows.map(rowToCopyNode),
+ liveChildren: childRows.map(row => ({ resourceId: String(row.resource_id), name: String(row.name) })),
+ };
+ }
}
diff --git a/gfs-controller/src/db/writeStore.deadline.test.ts b/gfs-controller/src/db/writeStore.deadline.test.ts
new file mode 100644
index 000000000..32f94bb2b
--- /dev/null
+++ b/gfs-controller/src/db/writeStore.deadline.test.ts
@@ -0,0 +1,38 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { PgTransactor, type PoolLike } from "./writeStore";
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>(resolvePromise => {
+ resolve = resolvePromise;
+ });
+ return { promise, resolve };
+}
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe("PgTransactor deadline-bounded acquisition", () => {
+ it("releases a late client and executes no SQL after the deadline", async () => {
+ vi.useFakeTimers();
+ const acquisition = deferred<Awaited<ReturnType<PoolLike["connect"]>>>();
+ const query = vi.fn(async () => ({ rows: [] }));
+ const release = vi.fn();
+ const operation = vi.fn();
+ const transaction = new PgTransactor({ connect: () => acquisition.promise }).transaction(
+ operation,
+ { deadlineAtMs: 10, now: () => 0 }
+ );
+ const rejected = expect(transaction).rejects.toMatchObject({ code: "precondition_failed" });
+
+ await vi.advanceTimersByTimeAsync(10);
+ await rejected;
+ acquisition.resolve({ query, release });
+ await Promise.resolve();
+
+ expect(operation).not.toHaveBeenCalled();
+ expect(query).not.toHaveBeenCalled();
+ expect(release).toHaveBeenCalledOnce();
+ });
+});
diff --git a/gfs-controller/src/db/writeStore.generation.test.ts b/gfs-controller/src/db/writeStore.generation.test.ts
new file mode 100644
index 000000000..16cd6f0cf
--- /dev/null
+++ b/gfs-controller/src/db/writeStore.generation.test.ts
@@ -0,0 +1,348 @@
+import { createHash } from "node:crypto";
+import { describe, expect, it } from "vitest";
+import { PgBlobStagingStore } from "./blobStaging";
+import {
+ CommitOutcomeUnknownError,
+ GfsWriteService,
+ PgTransactor,
+ type BlobWriter,
+ type PoolLike,
+ type Transactor,
+ type TxClient,
+} from "./writeStore";
+
+const RESOURCE = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
+const PARENT = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb";
+const ROOT = "00000000-0000-0000-0000-000000000001";
+const GENERATION = "11111111-1111-4111-8111-111111111111";
+const REQUEST = "22222222-2222-4222-8222-222222222222";
+
+function row(over: Record<string, unknown> = {}): Record<string, unknown> {
+ return {
+ resource_id: RESOURCE,
+ drive: "main",
+ parent_resource_id: PARENT,
+ name: "report.pdf",
+ kind: "file",
+ path_cache: "/docs/report.pdf",
+ version: 1,
+ bytes: 5,
+ blob_key: null,
+ content_sha256: null,
+ deleted_at: null,
+ ...over,
+ };
+}
+
+class FakeDb implements TxClient {
+ calls: Array<{ sql: string; values: unknown[] }> = [];
+ manifests = new Map<string, "staged" | "committed" | "deleting">();
+ removedCommitted: string[] = [];
+ current = row();
+ published: Record<string, unknown> | null = null;
+ exposePublished = false;
+ parent = row({ resource_id: PARENT, parent_resource_id: ROOT, name: "docs", kind: "directory", path_cache: "/docs" });
+ root = row({ resource_id: ROOT, parent_resource_id: null, name: "", kind: "directory", path_cache: "/" });
+ children: Record<string, unknown>[] = [];
+ duplicate = false;
+ async query(sql: string, values: unknown[] = []) {
+ this.calls.push({ sql, values });
+ if (sql.includes("INSERT INTO gfs_blob_manifests") && sql.includes("'staged'")) {
+ this.manifests.set(String(values[0]), "staged");
+ return { rows: [] };
+ }
+ if (sql.includes("INSERT INTO gfs_blob_manifests") && sql.includes("'deleting'")) {
+ this.manifests.set(String(values[0]), "deleting");
+ return { rows: [] };
+ }
+ if (sql.includes("UPDATE gfs_blob_manifests") && sql.includes("'committed'")) {
+ this.manifests.set(String(values[0]), "committed");
+ return { rows: [{ blob_key: values[0] }] };
+ }
+ if (sql.includes("DELETE FROM gfs_blob_manifests") && sql.includes("state = 'committed'")) {
+ const blobKey = String(values[0]);
+ this.manifests.delete(blobKey);
+ this.removedCommitted.push(blobKey);
+ return { rows: [] };
+ }
+ if (sql.includes("UPDATE gfs_blob_manifests") || sql.includes("DELETE FROM gfs_blob_manifests")) {
+ return { rows: [] };
+ }
+ if (sql.includes("SELECT resource_id") && sql.includes("blob_key = $3")) {
+ const published = this.published;
+ const rows: Record<string, unknown>[] = [];
+ if (this.exposePublished && published && published.blob_key === values[2]) {
+ rows.push(published);
+ }
+ return { rows };
+ }
+ if (sql.includes("pg_advisory_xact_lock")) return { rows: [] };
+ if (sql.includes("parent_resource_id = $2") && sql.includes("LIMIT 1")) {
+ return { rows: this.children };
+ }
+ if (sql.includes("WITH RECURSIVE ancestor_chain")) {
+ return { rows: [this.parent, this.root] };
+ }
+ if (sql.includes("resource_id = ANY($1::uuid[])")) {
+ return { rows: (values[0] as string[]).map(resource_id => ({ resource_id })) };
+ }
+ if (sql.includes("SELECT") && sql.includes("FOR UPDATE")) return { rows: [this.current] };
+ if (sql.includes("INSERT INTO gfs_resources")) {
+ if (this.duplicate) throw Object.assign(new Error("duplicate"), { code: "23505" });
+ this.published = row({
+ resource_id: values[0],
+ name: values[3],
+ kind: values[4],
+ path_cache: values[5],
+ bytes: values[6],
+ blob_key: values[7],
+ content_sha256: values[8],
+ version: 0,
+ });
+ return { rows: [this.published] };
+ }
+ if (sql.includes("UPDATE gfs_resources") && sql.includes("version = version + 1")) {
+ this.current = row({
+ ...this.current,
+ version: Number(this.current.version) + 1,
+ bytes: values[2],
+ blob_key: values[3],
+ content_sha256: values[4],
+ });
+ this.published = this.current;
+ return { rows: [this.current] };
+ }
+ if (sql.includes("UPDATE gfs_resources")) return { rows: [] };
+ throw new Error(`unexpected query: ${sql}`);
+ }
+
+ snapshot() {
+ return {
+ current: { ...this.current },
+ published: this.published && { ...this.published },
+ manifests: new Map(this.manifests),
+ };
+ }
+
+ restore(snapshot: ReturnType<FakeDb["snapshot"]>): void {
+ this.current = snapshot.current;
+ this.published = snapshot.published;
+ this.manifests = snapshot.manifests;
+ }
+}
+
+class RecordingBlobs implements BlobWriter {
+ writes: string[] = [];
+ deletes: string[] = [];
+ async writeImmutable(resourceId: string, generation: string, data: Buffer) {
+ const blobKey = `${resourceId.replaceAll("-", "")}/${generation}`;
+ this.writes.push(blobKey);
+ return {
+ blobKey,
+ bytes: data.length,
+ contentSha256: createHash("sha256").update(data).digest("hex"),
+ };
+ }
+ async verify(): Promise<void> {}
+ async deleteByKey(blobKey: string): Promise<void> {
+ this.deletes.push(blobKey);
+ }
+ async deleteLegacyFlat(resourceId: string): Promise<void> {
+ this.deletes.push(resourceId);
+ }
+}
+
+function service(
+ db: FakeDb,
+ blobs = new RecordingBlobs(),
+ tx: Transactor = { transaction: fn => fn(db) }
+): GfsWriteService {
+ return new GfsWriteService(tx, blobs, new PgBlobStagingStore(db), {
+ resourceId: () => RESOURCE,
+ generation: () => GENERATION,
+ requestId: () => REQUEST,
+ });
+}
+
+function unknownCommitService(
+ db: FakeDb,
+ blobs: RecordingBlobs,
+ commitBecameVisible: boolean
+): { writes: GfsWriteService; outcome: CommitOutcomeUnknownError } {
+ const outcome = new CommitOutcomeUnknownError(new Error("COMMIT response lost"));
+ const tx: Transactor = {
+ transaction: async fn => {
+ const snapshot = db.snapshot();
+ await fn(db);
+ if (!commitBecameVisible) db.restore(snapshot);
+ db.exposePublished = commitBecameVisible;
+ throw outcome;
+ },
+ };
+ return { writes: service(db, blobs, tx), outcome };
+}
+
+describe("generation-backed create", () => {
+ it("reserves a manifest before writing and publishes pointer+digest atomically", async () => {
+ const db = new FakeDb();
+ const blobs = new RecordingBlobs();
+ const created = await service(db, blobs).create({
+ drive: "main",
+ parentId: PARENT,
+ name: "new.txt",
+ content: Buffer.from("hello"),
+ });
+ expect(created.blobKey).toBe(`${RESOURCE.replaceAll("-", "")}/${GENERATION}`);
+ const manifest = db.calls.findIndex(call => call.sql.includes("INSERT INTO gfs_blob_manifests"));
+ const publish = db.calls.findIndex(call => call.sql.includes("INSERT INTO gfs_resources"));
+ expect(manifest).toBeLessThan(publish);
+ expect(
+ db.calls.some(
+ call =>
+ call.sql.includes("hashtext('gfs:structure:' || $1)::bigint") &&
+ call.values[0] === "main"
+ )
+ ).toBe(true);
+ expect(blobs.writes).toHaveLength(1);
+ });
+
+ it("uses the same structure lock as directory deletion", async () => {
+ const db = new FakeDb();
+ await service(db).delete({ drive: "main", resourceId: RESOURCE, ifMatch: 1 });
+ expect(db.calls[0]).toMatchObject({ values: ["main"] });
+ expect(db.calls[0].sql).toContain("hashtext('gfs:structure:' || $1)::bigint");
+ expect(db.calls.find(call => call.sql.includes("FOR UPDATE"))).toBeDefined();
+ });
+});
+
+describe("generation-backed replace", () => {
+ it("keeps external identity, increments version, and selects only the verified generation", async () => {
+ const db = new FakeDb();
+ const updated = await service(db).replace({
+ drive: "main",
+ resourceId: RESOURCE,
+ ifMatch: 1,
+ content: Buffer.from("new bytes"),
+ });
+ expect(updated.resourceId).toBe(RESOURCE);
+ expect(updated.version).toBe(2);
+ expect(updated.blobKey).toContain(GENERATION);
+ const update = db.calls.find(call => call.sql.includes("UPDATE gfs_resources"))!;
+ expect(update.sql).toContain("content_sha256 = $5");
+ });
+
+ it("cleans a staged generation after a definite stale-version rollback", async () => {
+ const db = new FakeDb();
+ db.current = row({ version: 9 });
+ const blobs = new RecordingBlobs();
+ await expect(
+ service(db, blobs).replace({
+ drive: "main",
+ resourceId: RESOURCE,
+ ifMatch: 1,
+ content: Buffer.from("x"),
+ })
+ ).rejects.toMatchObject({ code: "precondition_failed" });
+ expect(blobs.deletes).toHaveLength(1);
+ });
+
+ it("lazily replaces a legacy flat blob and schedules it for verified cleanup", async () => {
+ const db = new FakeDb();
+ db.current = row({ blob_key: null, content_sha256: null, bytes: 5 });
+ const blobs = new RecordingBlobs();
+
+ const updated = await service(db, blobs).replace({
+ drive: "main",
+ resourceId: RESOURCE,
+ ifMatch: 1,
+ content: Buffer.from("new bytes"),
+ });
+
+ expect(updated.blobKey).toBe(`${RESOURCE.replaceAll("-", "")}/${GENERATION}`);
+ const legacyCleanup = db.calls.find(
+ call => call.sql.includes("INSERT INTO gfs_blob_manifests") && call.sql.includes("'legacy_flat'")
+ );
+ expect(legacyCleanup?.values).toEqual([RESOURCE.replaceAll("-", ""), RESOURCE, 5]);
+ expect(blobs.deletes).toEqual([]);
+ });
+});
+
+describe.each([
+ {
+ operation: "create",
+ invoke: (writes: GfsWriteService) =>
+ writes.create({
+ drive: "main",
+ parentId: PARENT,
+ name: "new.txt",
+ content: Buffer.from("new"),
+ }),
+ committedVersion: 0,
+ },
+ {
+ operation: "replace",
+ invoke: (writes: GfsWriteService) =>
+ writes.replace({
+ drive: "main",
+ resourceId: RESOURCE,
+ ifMatch: 1,
+ content: Buffer.from("new"),
+ }),
+ committedVersion: 2,
+ },
+])("ambiguous COMMIT recovery for $operation", ({ invoke, committedVersion }) => {
+ const candidate = `${RESOURCE.replaceAll("-", "")}/${GENERATION}`;
+
+ it("returns the committed row and removes only its committed manifest after response loss", async () => {
+ const db = new FakeDb();
+ const blobs = new RecordingBlobs();
+ const { writes } = unknownCommitService(db, blobs, true);
+
+ const committed = await invoke(writes);
+
+ expect(committed).toMatchObject({ blobKey: candidate, version: committedVersion });
+ expect(db.removedCommitted).toContain(candidate);
+ expect(db.manifests.has(candidate)).toBe(false);
+ expect(blobs.deletes).toEqual([]);
+ });
+
+ it("rethrows and retains the staged candidate when rollback remains the observable outcome", async () => {
+ const db = new FakeDb();
+ const blobs = new RecordingBlobs();
+ const { writes, outcome } = unknownCommitService(db, blobs, false);
+
+ await expect(invoke(writes)).rejects.toBe(outcome);
+
+ expect(db.removedCommitted).not.toContain(candidate);
+ expect(db.manifests.get(candidate)).toBe("staged");
+ expect(blobs.writes).toContain(candidate);
+ expect(blobs.deletes).toEqual([]);
+ });
+});
+
+describe("PgTransactor", () => {
+ class FakePool implements PoolLike {
+ queries: string[] = [];
+ async query() {
+ return { rows: [] };
+ }
+ async connect() {
+ return {
+ query: async (text: string) => {
+ this.queries.push(text);
+ if (text === "COMMIT") throw new Error("connection lost after commit send");
+ return { rows: [] };
+ },
+ release: () => undefined,
+ };
+ }
+ }
+
+ it("classifies a lost COMMIT response as unknown instead of a definite rollback", async () => {
+ const pool = new FakePool();
+ await expect(new PgTransactor(pool).transaction(async () => "done")).rejects.toBeInstanceOf(
+ CommitOutcomeUnknownError
+ );
+ expect(pool.queries).toEqual(["BEGIN", "COMMIT", "ROLLBACK"]);
+ });
+});
diff --git a/gfs-controller/src/db/writeStore.test.ts b/gfs-controller/src/db/writeStore.test.ts
index 8e3268dd3..14e644944 100644
--- a/gfs-controller/src/db/writeStore.test.ts
+++ b/gfs-controller/src/db/writeStore.test.ts
@@ -1,393 +1,363 @@
-import type { Readable } from "node:stream";
+import { createHash } from "node:crypto";
import { describe, expect, it } from "vitest";
+import type { AuditEvent, AuditSink, Queryable } from "../authz/audit";
+import { PgBlobStagingStore, type ManifestQueryable } from "./blobStaging";
import {
- BlobWriter,
GfsWriteService,
PgTransactor,
- PoolLike,
- Transactor,
- TxClient,
+ RollbackOutcomeUnknownError,
+ type BlobWriter,
+ type PoolLike,
+ type Transactor,
+ type TxClient,
} from "./writeStore";
-/** A pg row as returned for a gfs_resources SELECT/RETURNING. */
+const RESOURCE = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
+const PARENT = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb";
+const ROOT = "00000000-0000-0000-0000-000000000001";
+const GENERATION = "11111111-1111-4111-8111-111111111111";
+const REQUEST = "22222222-2222-4222-8222-222222222222";
+
function row(over: Record<string, unknown> = {}): Record<string, unknown> {
return {
- resource_id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
+ resource_id: RESOURCE,
drive: "main",
- parent_resource_id: "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb",
+ parent_resource_id: PARENT,
name: "report.pdf",
kind: "file",
path_cache: "/docs/report.pdf",
version: 1,
bytes: 5,
+ blob_key: null,
+ content_sha256: null,
deleted_at: null,
...over,
};
}
-/**
- * A fake TxClient routed by SQL shape. Each handler returns the rows for that
- * query; an unhandled query throws (a write that issues an unexpected query
- * fails loud). `calls` records every (sql, values) for order assertions.
- */
class FakeClient implements TxClient {
calls: Array<{ sql: string; values: unknown[] }> = [];
constructor(
private readonly handlers: {
- select?: () => Record<string, unknown>[]; // liveResource (no FOR UPDATE)
- lock?: () => Record<string, unknown>[]; // SELECT … FOR UPDATE
- insert?: () => Record<string, unknown>[]; // INSERT … RETURNING (may throw)
- update?: () => Record<string, unknown>[]; // UPDATE … version / deleted_at
- children?: () => Record<string, unknown>[]; // child existence probe
+ parent?: () => Record<string, unknown>[];
+ lock?: () => Record<string, unknown>[];
+ insert?: (values: unknown[]) => Record<string, unknown>[];
+ update?: (values: unknown[]) => Record<string, unknown>[];
+ children?: () => Record<string, unknown>[];
+ ancestors?: () => Record<string, unknown>[];
}
) {}
- async query(sql: string, values: unknown[] = []): Promise<{ rows: Record<string, unknown>[] }> {
+ async query(sql: string, values: unknown[] = []) {
this.calls.push({ sql, values });
- if (sql.includes("INSERT INTO gfs_resources")) return { rows: (this.handlers.insert ?? (() => []))() };
- if (sql.includes("FOR UPDATE")) return { rows: (this.handlers.lock ?? (() => []))() };
- if (sql.includes("parent_resource_id = $2 AND deleted_at IS NULL LIMIT 1"))
+ if (sql.includes("pg_advisory_xact_lock")) return { rows: [] };
+ if (sql.includes("UPDATE gfs_blob_manifests") && sql.includes("'committed'")) {
+ return { rows: [{ blob_key: values[0] }] };
+ }
+ if (sql.includes("INSERT INTO gfs_blob_manifests") || sql.includes("DELETE FROM gfs_blob_manifests")) {
+ return { rows: [] };
+ }
+ if (sql.includes("INSERT INTO gfs_resources")) {
+ return { rows: (this.handlers.insert ?? (() => []))(values) };
+ }
+ if (sql.includes("parent_resource_id = $2") && sql.includes("LIMIT 1")) {
return { rows: (this.handlers.children ?? (() => []))() };
- if (sql.includes("UPDATE gfs_resources")) return { rows: (this.handlers.update ?? (() => []))() };
- if (sql.includes("SELECT")) return { rows: (this.handlers.select ?? (() => []))() };
+ }
+ if (sql.includes("WITH RECURSIVE ancestor_chain")) {
+ return { rows: (this.handlers.ancestors ?? this.handlers.parent ?? (() => []))() };
+ }
+ if (sql.includes("resource_id = ANY($1::uuid[])")) {
+ return { rows: (values[0] as string[]).map(resource_id => ({ resource_id })) };
+ }
+ if (sql.includes("deleted_at IS NULL FOR UPDATE")) {
+ return { rows: (this.handlers.parent ?? (() => []))() };
+ }
+ if (sql.includes("FOR UPDATE")) return { rows: (this.handlers.lock ?? (() => []))() };
+ if (sql.includes("UPDATE gfs_resources")) {
+ return { rows: (this.handlers.update ?? (() => []))(values) };
+ }
+ if (sql.includes("SELECT") && sql.includes("blob_key = $3")) return { rows: [] };
throw new Error(`unexpected query: ${sql}`);
}
}
-function fakeTx(client: TxClient): Transactor {
- return { transaction: (fn) => fn(client) };
+class ManifestDb implements ManifestQueryable {
+ calls: string[] = [];
+ async query(sql: string) {
+ this.calls.push(sql);
+ return { rows: [] };
+ }
}
class RecordingBlobs implements BlobWriter {
writes: Array<{ resourceId: string; bytes: number }> = [];
- shouldThrow = false;
- async write(resourceId: string, data: Readable | Buffer): Promise<{ bytes: number }> {
- if (this.shouldThrow) throw new Error("blob write failed");
- const bytes = Buffer.isBuffer(data) ? data.length : 0;
- this.writes.push({ resourceId, bytes });
- return { bytes };
+ deletes: string[] = [];
+ async writeImmutable(resourceId: string, generation: string, data: Buffer) {
+ this.writes.push({ resourceId, bytes: data.length });
+ return {
+ blobKey: `${resourceId.replaceAll("-", "")}/${generation}`,
+ bytes: data.length,
+ contentSha256: createHash("sha256").update(data).digest("hex"),
+ };
+ }
+ async verify(): Promise<void> {}
+ async deleteByKey(blobKey: string): Promise<void> {
+ this.deletes.push(blobKey);
+ }
+ async deleteLegacyFlat(resourceId: string): Promise<void> {
+ this.deletes.push(resourceId);
}
}
-describe("GfsWriteService.create", () => {
- it("inserts a file under a live directory parent and writes its blob", async () => {
- const client = new FakeClient({
- select: () => [row({ kind: "directory", path_cache: "/docs", resource_id: "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb" })],
- insert: () => [row({ name: "new.txt", path_cache: "/docs/new.txt", version: 0, bytes: 5 })],
- });
- const blobs = new RecordingBlobs();
- const svc = new GfsWriteService(fakeTx(client), blobs);
+function service(client: FakeClient, blobs = new RecordingBlobs()): GfsWriteService {
+ const tx: Transactor = { transaction: fn => fn(client) };
+ return new GfsWriteService(tx, blobs, new PgBlobStagingStore(new ManifestDb()), {
+ resourceId: () => RESOURCE,
+ generation: () => GENERATION,
+ requestId: () => REQUEST,
+ });
+}
- const created = await svc.create({
- drive: "main",
- parentId: "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb",
- name: "new.txt",
- content: Buffer.from("hello"),
- });
+class RecordingAudit implements AuditSink {
+ calls: Array<{ event: AuditEvent; transactional: boolean }> = [];
+ async record(event: AuditEvent, queryable?: Queryable): Promise<void> {
+ this.calls.push({ event, transactional: queryable !== undefined });
+ }
+}
- expect(created.name).toBe("new.txt");
- expect(created.version).toBe(0);
- // path_cache computed from the parent, and the INSERT carried the byte count.
- const insert = client.calls.find((c) => c.sql.includes("INSERT"))!;
- expect(insert.values).toEqual(["main", "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", "new.txt", "file", "/docs/new.txt", 5]);
- // Blob written for the RETURNED resource id.
- expect(blobs.writes).toEqual([{ resourceId: created.resourceId, bytes: 5 }]);
- });
+function parent(over: Record<string, unknown> = {}) {
+ return row({ resource_id: PARENT, parent_resource_id: ROOT, name: "docs", kind: "directory", path_cache: "/docs", ...over });
+}
+
+function root(over: Record<string, unknown> = {}) {
+ return row({ resource_id: ROOT, parent_resource_id: null, name: "", kind: "directory", path_cache: "/", ...over });
+}
- it("inserts a directory without writing a blob", async () => {
+function parentChain(parentOver: Record<string, unknown> = {}, rootOver: Record<string, unknown> = {}) {
+ return [parent(parentOver), root(rootOver)];
+}
+
+describe("GfsWriteService.create legacy contract", () => {
+ it("creates a file with stable path, bytes, generation and structure lock", async () => {
const client = new FakeClient({
- select: () => [row({ kind: "directory", path_cache: "/docs", resource_id: "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb" })],
- insert: () => [row({ name: "nested", kind: "directory", path_cache: "/docs/nested", version: 0, bytes: 0 })],
+ ancestors: () => parentChain(),
+ insert: values => [row({ name: values[3], path_cache: values[5], bytes: values[6], blob_key: values[7], content_sha256: values[8], version: 0 })],
});
const blobs = new RecordingBlobs();
- const svc = new GfsWriteService(fakeTx(client), blobs);
-
- const created = await svc.create({
- drive: "main",
- parentId: "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb",
- name: "nested",
- kind: "directory",
- });
+ const created = await service(client, blobs).create({ drive: "main", parentId: PARENT, name: "new.txt", content: Buffer.from("hello") });
+ expect(created).toMatchObject({ name: "new.txt", pathCache: "/docs/new.txt", version: 0, bytes: 5 });
+ const insert = client.calls.find(call => call.sql.includes("INSERT INTO gfs_resources"))!;
+ expect(insert.values.slice(1, 7)).toEqual(["main", PARENT, "new.txt", "file", "/docs/new.txt", 5]);
+ expect(blobs.writes).toEqual([{ resourceId: RESOURCE, bytes: 5 }]);
+ expect(client.calls[0].sql).toContain("hashtext('gfs:structure:' || $1)::bigint");
+ const chainReads = client.calls.filter(call => call.sql.includes("WITH RECURSIVE ancestor_chain"));
+ const rowLock = client.calls.find(call => call.sql.includes("resource_id = ANY($1::uuid[])"));
+ expect(chainReads).toHaveLength(2);
+ expect(rowLock?.values[0]).toEqual([ROOT, PARENT].sort());
+ });
- expect(created.kind).toBe("directory");
- const insert = client.calls.find((c) => c.sql.includes("INSERT"))!;
- expect(insert.values).toEqual(["main", "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", "nested", "directory", "/docs/nested", 0]);
+ it("creates a directory without a blob", async () => {
+ const client = new FakeClient({ ancestors: () => parentChain(), insert: values => [row({ kind: "directory", name: values[3], bytes: 0, blob_key: null, content_sha256: null })] });
+ const blobs = new RecordingBlobs();
+ expect((await service(client, blobs).create({ drive: "main", parentId: PARENT, name: "nested", kind: "directory" })).kind).toBe("directory");
expect(blobs.writes).toEqual([]);
});
- it("rejects a create whose parent does not exist (not_found)", async () => {
- const svc = new GfsWriteService(fakeTx(new FakeClient({ select: () => [] })), new RecordingBlobs());
- await expect(
- svc.create({
- drive: "main",
- parentId: "dddddddd-dddd-dddd-dddd-dddddddddddd",
- name: "x",
- content: Buffer.alloc(0),
- })
- ).rejects.toMatchObject({ code: "not_found" });
+ it("rejects an absent parent", async () => {
+ await expect(service(new FakeClient({ ancestors: () => [] })).create({ drive: "main", parentId: PARENT, name: "x" })).rejects.toMatchObject({ code: "not_found" });
});
- it("rejects a create under a FILE parent (not_a_directory)", async () => {
- const client = new FakeClient({ select: () => [row({ kind: "file" })] });
- const svc = new GfsWriteService(fakeTx(client), new RecordingBlobs());
- await expect(
- svc.create({
- drive: "main",
- parentId: "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb",
- name: "y",
- content: Buffer.alloc(0),
- })
- ).rejects.toMatchObject({ code: "not_a_directory" });
+ it("rejects a file parent", async () => {
+ await expect(service(new FakeClient({ ancestors: () => parentChain({ kind: "file" }) })).create({ drive: "main", parentId: PARENT, name: "x" })).rejects.toMatchObject({ code: "not_a_directory" });
});
- it("accepts a parent rid and inserts with the UUID parent id", async () => {
- const client = new FakeClient({
- select: () => [
- row({ kind: "directory", path_cache: "/docs", resource_id: "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb" }),
- ],
- insert: () => [row({ name: "new.txt", path_cache: "/docs/new.txt", version: 0, bytes: 5 })],
- });
- const svc = new GfsWriteService(fakeTx(client), new RecordingBlobs());
+ it("normalizes a parent rid to UUID", async () => {
+ const client = new FakeClient({ ancestors: () => parentChain(), insert: () => [row()] });
+ await service(client).create({ drive: "main", parentId: PARENT.replaceAll("-", ""), name: "x" });
+ expect(client.calls.find(call => call.sql.includes("INSERT INTO gfs_resources"))?.values[2]).toBe(PARENT);
+ });
- await svc.create({
- drive: "main",
- parentId: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
- name: "new.txt",
- content: Buffer.from("hello"),
- });
+ it("maps duplicate siblings and cleans the unpublished generation", async () => {
+ const client = new FakeClient({ ancestors: () => parentChain(), insert: () => { throw Object.assign(new Error("duplicate"), { code: "23505" }); } });
+ const blobs = new RecordingBlobs();
+ await expect(service(client, blobs).create({ drive: "main", parentId: PARENT, name: "dupe", content: Buffer.from("x") })).rejects.toMatchObject({ code: "already_exists" });
+ expect(blobs.deletes).toHaveLength(1);
+ });
- const insert = client.calls.find((c) => c.sql.includes("INSERT"))!;
- expect(insert.values[1]).toBe("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb");
+ it("rejects a tombstoned ancestor", async () => {
+ const client = new FakeClient({ ancestors: () => parentChain({}, { deleted_at: new Date() }) });
+ await expect(
+ service(client).create({ drive: "main", parentId: PARENT, name: "x" })
+ ).rejects.toMatchObject({ code: "precondition_failed" });
});
- it("maps a duplicate sibling name (unique_violation 23505) to already_exists", async () => {
- const client = new FakeClient({
- select: () => [row({ kind: "directory", path_cache: "/docs" })],
- insert: () => {
- throw Object.assign(new Error("duplicate key"), { code: "23505" });
- },
- });
- const svc = new GfsWriteService(fakeTx(client), new RecordingBlobs());
+ it("rejects a cyclic ancestor chain", async () => {
+ const cycle = [
+ parent(),
+ root({ parent_resource_id: PARENT }),
+ parent({ cycle: true }),
+ ];
+ const client = new FakeClient({ ancestors: () => cycle });
await expect(
- svc.create({
- drive: "main",
- parentId: "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb",
- name: "dupe",
- content: Buffer.alloc(0),
- })
- ).rejects.toMatchObject({ code: "already_exists" });
+ service(client).create({ drive: "main", parentId: PARENT, name: "x" })
+ ).rejects.toMatchObject({ code: "precondition_failed" });
});
- it("does NOT write a blob when the INSERT fails (no orphan on a rejected create)", async () => {
- const client = new FakeClient({
- select: () => [row({ kind: "directory" })],
- insert: () => {
- throw Object.assign(new Error("duplicate key"), { code: "23505" });
- },
- });
- const blobs = new RecordingBlobs();
+ it.each([
+ ["cross-drive", parentChain({}, { drive: "archive" })],
+ ["missing", [parent()]],
+ ["noncanonical-root", parentChain({}, { name: "orphan-root" })],
+ ])("rejects a %s ancestor", async (_case, ancestors) => {
+ const client = new FakeClient({ ancestors: () => ancestors });
await expect(
- new GfsWriteService(fakeTx(client), blobs).create({
- drive: "main",
- parentId: "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb",
- name: "dupe",
- content: Buffer.from("data"),
- })
- ).rejects.toThrow();
- expect(blobs.writes).toEqual([]); // insert threw before the blob write
+ service(client).create({ drive: "main", parentId: PARENT, name: "x" })
+ ).rejects.toMatchObject({ code: "precondition_failed" });
});
-});
-describe("GfsWriteService.replace", () => {
- it("bumps version and bytes, overwriting the blob under the row lock", async () => {
+ it("derives the child path from ancestor names, not a stale parent path cache", async () => {
const client = new FakeClient({
- lock: () => [row({ version: 3, kind: "file" })],
- update: () => [row({ version: 4, bytes: 5 })],
+ ancestors: () => parentChain({ path_cache: "/stale/location" }),
+ insert: values => [row({ name: values[3], path_cache: values[5], version: 0 })],
});
- const blobs = new RecordingBlobs();
- const svc = new GfsWriteService(fakeTx(client), blobs);
+ const created = await service(client).create({ drive: "main", parentId: PARENT, name: "new.txt" });
+ expect(created.pathCache).toBe("/docs/new.txt");
+ });
- const updated = await svc.replace({
- drive: "main",
- resourceId: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
- ifMatch: 3,
- content: Buffer.from("howdy"),
+ it("fails when the ancestor chain changes while its rows are being locked", async () => {
+ let reads = 0;
+ const client = new FakeClient({
+ ancestors: () => (reads++ === 0 ? parentChain() : parentChain({ name: "renamed" })),
});
+ await expect(
+ service(client).create({ drive: "main", parentId: PARENT, name: "x" })
+ ).rejects.toMatchObject({ code: "precondition_failed" });
+ expect(client.calls.some(call => call.sql.includes("INSERT INTO gfs_resources"))).toBe(false);
+ });
+});
- expect(updated.version).toBe(4);
- expect(blobs.writes).toHaveLength(1);
- // Blob write precedes the metadata UPDATE (ordering under the lock).
- const blobIdx = client.calls.findIndex((c) => c.sql.includes("FOR UPDATE"));
- const updateIdx = client.calls.findIndex((c) => c.sql.includes("UPDATE gfs_resources"));
- expect(blobIdx).toBeLessThan(updateIdx);
+describe("GfsWriteService.replace legacy contract", () => {
+ it("bumps version and bytes under a resource row lock", async () => {
+ const client = new FakeClient({ lock: () => [row({ version: 3 })], update: values => [row({ version: 4, bytes: values[2], blob_key: values[3], content_sha256: values[4] })] });
+ const updated = await service(client).replace({ drive: "main", resourceId: RESOURCE, ifMatch: 3, content: Buffer.from("howdy") });
+ expect(updated).toMatchObject({ resourceId: RESOURCE, version: 4, bytes: 5 });
+ expect(client.calls.some(call => call.sql.includes("'legacy_flat'"))).toBe(true);
});
- it("rejects a stale If-Match (precondition_failed) and writes NO blob", async () => {
- const client = new FakeClient({ lock: () => [row({ version: 7, kind: "file" })] });
+ it("rejects stale If-Match and cleans the staged generation", async () => {
const blobs = new RecordingBlobs();
- await expect(
- new GfsWriteService(fakeTx(client), blobs).replace({
- drive: "main",
- resourceId: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
- ifMatch: 3, // != 7
- content: Buffer.from("x"),
- })
- ).rejects.toMatchObject({ code: "precondition_failed" });
- expect(blobs.writes).toEqual([]);
+ await expect(service(new FakeClient({ lock: () => [row({ version: 7 })] }), blobs).replace({ drive: "main", resourceId: RESOURCE, ifMatch: 3, content: Buffer.from("x") })).rejects.toMatchObject({ code: "precondition_failed" });
+ expect(blobs.deletes).toHaveLength(1);
});
- it("maps a tombstoned target to gone, a directory to is_a_directory, a miss to not_found", async () => {
- const gone = new GfsWriteService(
- fakeTx(new FakeClient({ lock: () => [row({ deleted_at: new Date() })] })),
- new RecordingBlobs()
- );
- await expect(gone.replace({ drive: "main", resourceId: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", ifMatch: 1, content: Buffer.alloc(0) })).rejects.toMatchObject({
- code: "gone",
- });
-
- const dir = new GfsWriteService(
- fakeTx(new FakeClient({ lock: () => [row({ kind: "directory" })] })),
- new RecordingBlobs()
- );
- await expect(dir.replace({ drive: "main", resourceId: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", ifMatch: 1, content: Buffer.alloc(0) })).rejects.toMatchObject({
- code: "is_a_directory",
- });
+ it.each([
+ ["gone", [row({ deleted_at: new Date() })], "gone"],
+ ["directory", [row({ kind: "directory" })], "is_a_directory"],
+ ["missing", [], "not_found"],
+ ])("maps %s targets", async (_name, rows, code) => {
+ await expect(service(new FakeClient({ lock: () => rows as Record<string, unknown>[] })).replace({ drive: "main", resourceId: RESOURCE, ifMatch: 1, content: Buffer.alloc(0) })).rejects.toMatchObject({ code });
+ });
- const miss = new GfsWriteService(fakeTx(new FakeClient({ lock: () => [] })), new RecordingBlobs());
- await expect(miss.replace({ drive: "main", resourceId: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", ifMatch: 1, content: Buffer.alloc(0) })).rejects.toMatchObject({
- code: "not_found",
- });
+ it("normalizes a target rid to UUID", async () => {
+ const client = new FakeClient({ lock: () => [row()], update: values => [row({ version: 2, blob_key: values[3], content_sha256: values[4] })] });
+ await service(client).replace({ drive: "main", resourceId: RESOURCE.replaceAll("-", ""), ifMatch: 1, content: Buffer.from("x") });
+ expect(client.calls.find(call => call.sql.includes("FOR UPDATE"))?.values[1]).toBe(RESOURCE);
});
+});
- it("accepts a target rid and locks/updates with the UUID resource id", async () => {
- const client = new FakeClient({
- lock: () => [row({ version: 3, kind: "file" })],
- update: () => [row({ version: 4, bytes: 5 })],
- });
- const svc = new GfsWriteService(fakeTx(client), new RecordingBlobs());
+describe("managed create and replace mutation outcomes", () => {
+ const mutation = (audit: RecordingAudit) => ({ subject: "agent:test", requestId: REQUEST, audit });
- await svc.replace({
- drive: "main",
- resourceId: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
- ifMatch: 3,
- content: Buffer.from("howdy"),
- });
+ it("records create success inside the metadata transaction and a definitive failure afterwards", async () => {
+ const successAudit = new RecordingAudit();
+ const success = new FakeClient({ ancestors: () => parentChain(), insert: () => [row({ version: 0 })] });
+ await service(success).create({ drive: "main", parentId: PARENT, name: "x", kind: "directory", mutation: mutation(successAudit) });
+ expect(successAudit.calls).toEqual([expect.objectContaining({ transactional: true, event: expect.objectContaining({ op: "create", mutationOutcome: "succeeded" }) })]);
- expect(client.calls.find((c) => c.sql.includes("FOR UPDATE"))?.values[1]).toBe(
- "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
- );
- expect(client.calls.find((c) => c.sql.includes("UPDATE gfs_resources"))?.values[1]).toBe(
- "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
- );
+ const failureAudit = new RecordingAudit();
+ await expect(service(new FakeClient({ ancestors: () => [] })).create({
+ drive: "main", parentId: PARENT, name: "x", kind: "directory", mutation: mutation(failureAudit),
+ })).rejects.toMatchObject({ code: "not_found" });
+ expect(failureAudit.calls).toEqual([expect.objectContaining({ transactional: false, event: expect.objectContaining({ op: "create", mutationOutcome: "failed", outcome: "error" }) })]);
+ });
+
+ it("records replace success transactionally and stale-version failure only after rollback", async () => {
+ const successAudit = new RecordingAudit();
+ await service(new FakeClient({ lock: () => [row()], update: values => [row({ version: 2, bytes: values[2], blob_key: values[3], content_sha256: values[4] })] }))
+ .replace({ drive: "main", resourceId: RESOURCE, ifMatch: 1, content: Buffer.from("x"), mutation: mutation(successAudit) });
+ expect(successAudit.calls[0]).toMatchObject({ transactional: true, event: { op: "replace", mutationOutcome: "succeeded" } });
+
+ const failureAudit = new RecordingAudit();
+ await expect(service(new FakeClient({ lock: () => [row({ version: 9 })] })).replace({
+ drive: "main", resourceId: RESOURCE, ifMatch: 1, content: Buffer.from("x"), mutation: mutation(failureAudit),
+ })).rejects.toMatchObject({ code: "precondition_failed" });
+ expect(failureAudit.calls[0]).toMatchObject({ transactional: false, event: { op: "replace", mutationOutcome: "failed" } });
});
});
-describe("GfsWriteService.delete", () => {
- it("soft-deletes a file (sets deleted_at) without removing the blob", async () => {
- const client = new FakeClient({
- lock: () => [row({ version: 2, kind: "file" })],
- update: () => [],
- });
+describe("GfsWriteService.delete legacy contract", () => {
+ it("soft-deletes a file without deleting bytes", async () => {
+ const client = new FakeClient({ lock: () => [row({ version: 2 })], update: () => [] });
const blobs = new RecordingBlobs();
- await new GfsWriteService(fakeTx(client), blobs).delete({
- drive: "main",
- resourceId: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
- ifMatch: 2,
- });
-
- const update = client.calls.find((c) => c.sql.includes("UPDATE gfs_resources"))!;
- expect(update.sql).toContain("deleted_at = now()");
- expect(blobs.writes).toEqual([]); // soft delete retains bytes
+ await service(client, blobs).delete({ drive: "main", resourceId: RESOURCE, ifMatch: 2 });
+ expect(client.calls.find(call => call.sql.includes("UPDATE gfs_resources"))?.sql).toContain("deleted_at = now()");
+ expect(blobs.deletes).toEqual([]);
});
- it("refuses to delete a non-empty directory (not_empty)", async () => {
- const client = new FakeClient({
- lock: () => [row({ kind: "directory" })],
- children: () => [{ "?column?": 1 }], // a live child exists
- });
- await expect(
- new GfsWriteService(fakeTx(client), new RecordingBlobs()).delete({
- drive: "main",
- resourceId: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
- ifMatch: 1,
- })
- ).rejects.toMatchObject({ code: "not_empty" });
+ it("refuses a non-empty directory", async () => {
+ const client = new FakeClient({ lock: () => [row({ kind: "directory" })], children: () => [{ present: 1 }] });
+ await expect(service(client).delete({ drive: "main", resourceId: RESOURCE, ifMatch: 1 })).rejects.toMatchObject({ code: "not_empty" });
});
- it("rejects a stale If-Match (precondition_failed)", async () => {
- const client = new FakeClient({ lock: () => [row({ version: 9, kind: "file" })] });
- await expect(
- new GfsWriteService(fakeTx(client), new RecordingBlobs()).delete({
- drive: "main",
- resourceId: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
- ifMatch: 1,
- })
- ).rejects.toMatchObject({ code: "precondition_failed" });
+ it("rejects stale If-Match", async () => {
+ await expect(service(new FakeClient({ lock: () => [row({ version: 9 })] })).delete({ drive: "main", resourceId: RESOURCE, ifMatch: 1 })).rejects.toMatchObject({ code: "precondition_failed" });
});
- it("accepts a target rid and deletes with the UUID resource id", async () => {
- const client = new FakeClient({
- lock: () => [row({ version: 2, kind: "file" })],
- update: () => [],
- });
-
- await new GfsWriteService(fakeTx(client), new RecordingBlobs()).delete({
- drive: "main",
- resourceId: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
- ifMatch: 2,
- });
-
- expect(client.calls.find((c) => c.sql.includes("FOR UPDATE"))?.values[1]).toBe(
- "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
- );
- expect(client.calls.find((c) => c.sql.includes("UPDATE gfs_resources"))?.values[1]).toBe(
- "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
- );
+ it("normalizes a target rid and shares the exact structure lock", async () => {
+ const client = new FakeClient({ lock: () => [row({ version: 2 })], update: () => [] });
+ await service(client).delete({ drive: "main", resourceId: RESOURCE.replaceAll("-", ""), ifMatch: 2 });
+ expect(client.calls[0]).toMatchObject({ values: ["main"] });
+ expect(client.calls.find(call => call.sql.includes("FOR UPDATE"))?.values[1]).toBe(RESOURCE);
});
});
-describe("PgTransactor", () => {
+describe("PgTransactor legacy contract", () => {
class FakePool implements PoolLike {
queries: string[] = [];
released = false;
- constructor(private readonly behavior: { failAt?: string } = {}) {}
+ releaseError: Error | boolean | undefined;
+ constructor(private readonly failAt?: string) {}
+ async query() { return { rows: [] }; }
async connect() {
- const queries = this.queries;
- const behavior = this.behavior;
- const self = this;
return {
- async query(text: string) {
- queries.push(text);
- if (behavior.failAt && text.includes(behavior.failAt)) throw new Error(`fail at ${text}`);
- return { rows: [] };
- },
- release() {
- self.released = true;
- },
+ query: async (text: string) => { this.queries.push(text); if (this.failAt && text.includes(this.failAt)) throw new Error(`fail at ${text}`); return { rows: [] }; },
+ release: (error?: Error | boolean) => { this.released = true; this.releaseError = error; },
};
}
}
- it("BEGIN → fn → COMMIT and releases the client", async () => {
+ it("runs BEGIN, callback, COMMIT and releases", async () => {
const pool = new FakePool();
- const out = await new PgTransactor(pool).transaction(async (c) => {
- await c.query("SELECT 1");
- return "done";
- });
- expect(out).toBe("done");
- expect(pool.queries[0]).toBe("BEGIN");
- expect(pool.queries.at(-1)).toBe("COMMIT");
+ expect(await new PgTransactor(pool).transaction(async client => { await client.query("SELECT 1"); return "done"; })).toBe("done");
+ expect(pool.queries).toEqual(["BEGIN", "SELECT 1", "COMMIT"]);
expect(pool.released).toBe(true);
});
- it("ROLLBACKs and rethrows when fn throws — never a silent COMMIT", async () => {
+ it("rolls back and rethrows a callback failure", async () => {
const pool = new FakePool();
- await expect(
- new PgTransactor(pool).transaction(async () => {
- throw new Error("write blew up");
- })
- ).rejects.toThrow("write blew up");
- expect(pool.queries).toContain("ROLLBACK");
- expect(pool.queries).not.toContain("COMMIT");
+ await expect(new PgTransactor(pool).transaction(async () => { throw new Error("write blew up"); })).rejects.toThrow("write blew up");
+ expect(pool.queries).toEqual(["BEGIN", "ROLLBACK"]);
expect(pool.released).toBe(true);
+ expect(pool.releaseError).toBeUndefined();
+ });
+
+ it("destroys rather than reuses a client after COMMIT uncertainty", async () => {
+ const pool = new FakePool("COMMIT");
+ await expect(new PgTransactor(pool).transaction(async () => "done")).rejects.toMatchObject({ name: "CommitOutcomeUnknownError" });
+ expect(pool.releaseError).toBeInstanceOf(Error);
+ });
+
+ it("destroys rather than reuses a client when rollback itself fails", async () => {
+ const pool = new FakePool("ROLLBACK");
+ await expect(new PgTransactor(pool).transaction(async () => { throw new Error("write failed"); })).rejects.toBeInstanceOf(RollbackOutcomeUnknownError);
+ expect(pool.releaseError).toBeInstanceOf(Error);
});
});
diff --git a/gfs-controller/src/db/writeStore.ts b/gfs-controller/src/db/writeStore.ts
index b9fb1c44b..c12af53f9 100644
--- a/gfs-controller/src/db/writeStore.ts
+++ b/gfs-controller/src/db/writeStore.ts
@@ -1,27 +1,22 @@
+import { randomUUID } from "node:crypto";
import type { Readable } from "node:stream";
+import type { CopyDestinationSnapshot, CopyPreflightPlan } from "../api/copy";
import { GfsError } from "../api/errors";
import { GfsResource } from "../api/read";
import { assertIfMatch } from "../api/write";
+import type { AuditSink } from "../authz/audit";
+import type { PermissionEpoch } from "../authz/cache";
import { normalizeResourceId } from "../storage/paths";
-
-/**
- * gfs write data plane (the metadata side of create/replace/delete). Pairs the
- * pure write PLAN (api/write.ts) and the blob bytes (storage/blobStore.ts) with
- * the transactional Postgres mutation that keeps the two consistent.
- *
- * Consistency model — blob writes are NOT transactional with Postgres, so the
- * mutation is ordered to make a DANGLING metadata row (metadata present, blob
- * missing) impossible; only a harmless orphan blob (blob present, no metadata)
- * is possible and is GC-able:
- *
- * create : INSERT (in tx) → write blob → COMMIT. Blob failure ROLLBACKs the
- * insert; a post-blob COMMIT failure leaves an orphan blob, never a
- * dangling row.
- * replace: SELECT … FOR UPDATE (serializes concurrent replaces) → assertIfMatch
- * → write blob under the row lock → UPDATE version+1, bytes → COMMIT.
- * delete : SELECT … FOR UPDATE → assertIfMatch → refuse a non-empty directory
- * → soft-delete (deleted_at). The blob is RETAINED (erasure is P5).
- */
+import { discardCandidate, PgBlobStagingStore, stageVerifiedBlob } from "./blobStaging";
+import { publishCopy, type CopyPublicationResult } from "./copyPublication";
+import { acquireBeforeDeadline } from "./deadlineQuery";
+import {
+ inspectCreateOutcome,
+ inspectReplaceRollback,
+ recordManagedMutation,
+ type ManagedMutationContext,
+} from "./managedMutationAudit";
+import { publishRename, type RenameInput } from "./renamePublication";
/** Minimal transaction-scoped query surface (a pg PoolClient satisfies it). */
export interface TxClient {
@@ -30,17 +25,54 @@ export interface TxClient {
/** Runs `fn` inside a single BEGIN/COMMIT, rolling back on any throw. */
export interface Transactor {
- transaction<T>(fn: (client: TxClient) => Promise<T>): Promise<T>;
+ transaction<T>(fn: (client: TxClient) => Promise<T>, options?: TransactionOptions): Promise<T>;
+}
+
+export interface TransactionOptions {
+ deadlineAtMs: number;
+ signal?: AbortSignal;
+ now?: () => number;
}
/** A pg Pool checked out for one transaction (connect → BEGIN → fn → COMMIT). */
export interface PoolLike {
connect(): Promise<{
query(text: string, values?: unknown[]): Promise<{ rows: Record<string, unknown>[] }>;
- release(): void;
+ /** Passing an error destroys the client instead of returning it to the pool. */
+ release(error?: Error | boolean): void;
}>;
}
+export class CommitOutcomeUnknownError extends Error {
+ readonly cause: unknown;
+ constructor(cause: unknown) {
+ super("transaction commit outcome is unknown");
+ this.name = "CommitOutcomeUnknownError";
+ this.cause = cause;
+ }
+}
+
+export class RollbackOutcomeUnknownError extends Error {
+ readonly cause: unknown;
+ readonly rollbackCause: unknown;
+ constructor(cause: unknown, rollbackCause: unknown) {
+ super("transaction rollback outcome is unknown");
+ this.name = "RollbackOutcomeUnknownError";
+ this.cause = cause;
+ this.rollbackCause = rollbackCause;
+ }
+}
+
+// PgTransactor serves every deadline-armed mutation (copy AND rename), so its
+// expiry message is mutation-generic; the copy pipeline's own gates keep the
+// copy-specific wording.
+function remainingMs(options: TransactionOptions): number {
+ options.signal?.throwIfAborted();
+ const remaining = options.deadlineAtMs - (options.now ?? Date.now)();
+ if (remaining <= 0) throw new GfsError("precondition_failed", "synchronous mutation deadline exceeded");
+ return Math.max(1, Math.min(remaining, 2_147_483_647));
+}
+
/**
* Postgres-backed Transactor: checks out one client, BEGINs, runs `fn`, and
* COMMITs — ROLLBACKing (best-effort) on any throw so a failed write never
@@ -49,35 +81,79 @@ export interface PoolLike {
export class PgTransactor implements Transactor {
constructor(private readonly pool: PoolLike) {}
- async transaction<T>(fn: (client: TxClient) => Promise<T>): Promise<T> {
- const client = await this.pool.connect();
+ async transaction<T>(fn: (client: TxClient) => Promise<T>, options?: TransactionOptions): Promise<T> {
+ const client = options
+ ? await acquireBeforeDeadline(() => this.pool.connect(), options)
+ : await this.pool.connect();
+ let commitSent = false;
+ let poison: Error | undefined;
try {
await client.query("BEGIN");
+ if (options) {
+ await client.query("SELECT set_config('statement_timeout', $1, true)", [String(remainingMs(options))]);
+ }
const result = await fn(client);
+ if (options) remainingMs(options); // the final gate is immediately before COMMIT
+ commitSent = true;
await client.query("COMMIT");
return result;
} catch (err) {
+ let rollbackFailure: unknown;
await client.query("ROLLBACK").catch((rollbackErr) => {
+ rollbackFailure = rollbackErr;
console.error(
`[gfsc] ROLLBACK failed after a write error: ${
rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr)
}`
);
});
+ if (commitSent) {
+ poison = err instanceof Error ? err : new Error(String(err));
+ throw new CommitOutcomeUnknownError(err);
+ }
+ if (rollbackFailure !== undefined) {
+ poison = rollbackFailure instanceof Error ? rollbackFailure : new Error(String(rollbackFailure));
+ throw new RollbackOutcomeUnknownError(err, rollbackFailure);
+ }
+ if (options && ((err as { code?: string }).code === "57014"
+ || options.signal?.aborted
+ || (options.now ?? Date.now)() >= options.deadlineAtMs)) {
+ throw new GfsError("precondition_failed", "synchronous mutation deadline exceeded");
+ }
throw err;
} finally {
- client.release();
+ client.release(poison);
}
}
}
/** The blob side of a write (BlobStore satisfies this; reader replicas reject). */
export interface BlobWriter {
- write(resourceId: string, data: Readable | Buffer): Promise<{ bytes: number }>;
+ writeImmutable(
+ resourceId: string,
+ generation: string,
+ data: Readable | Buffer
+ ): Promise<{ blobKey: string; bytes: number; contentSha256: string }>;
+ verify(blobKey: string, expectedBytes: number, expectedSha256: string): Promise<void>;
+ deleteByKey(blobKey: string): Promise<void>;
+ deleteLegacyFlat(resourceId: string): Promise<void>;
+ /** Copy-only capabilities. BlobStore implements both; simple write fakes need not. */
+ read?(resourceId: string, blobKey?: string | null): Promise<Readable>;
+ availableBytes?(): Promise<bigint>;
}
const RETURNING =
- "resource_id, drive, parent_resource_id, name, kind, path_cache, version, bytes, deleted_at";
+ "resource_id, drive, parent_resource_id, name, kind, path_cache, version, bytes, blob_key, content_sha256, deleted_at";
+
+interface AncestorRow {
+ resourceId: string;
+ drive: string;
+ parentResourceId: string | null;
+ name: string;
+ kind: string;
+ deletedAt: string | null;
+ cycle: boolean;
+}
function toIsoOrNull(value: unknown): string | null {
if (value === null || value === undefined) return null;
@@ -95,6 +171,8 @@ function rowToResource(row: Record<string, unknown>): GfsResource {
pathCache: row.path_cache == null ? null : String(row.path_cache),
version: Number(row.version),
bytes: Number(row.bytes),
+ blobKey: row.blob_key == null ? null : String(row.blob_key),
+ contentSha256: row.content_sha256 == null ? null : String(row.content_sha256),
deletedAt: toIsoOrNull(row.deleted_at),
};
}
@@ -115,12 +193,14 @@ export interface CreateInput {
name: string;
kind?: "file" | "directory";
content?: Buffer;
+ mutation?: ManagedMutationContext;
}
export interface ReplaceInput {
drive: string;
resourceId: string;
ifMatch?: number;
content: Buffer;
+ mutation?: ManagedMutationContext;
}
export interface DeleteInput {
drive: string;
@@ -128,96 +208,200 @@ export interface DeleteInput {
ifMatch?: number;
}
+export interface CopyInput {
+ requestId: string;
+ subject: string;
+ audit: AuditSink;
+ drive: string;
+ destinationParentId: string;
+ plan: CopyPreflightPlan;
+ destination: CopyDestinationSnapshot;
+ deadlineAtMs: number;
+ signal?: AbortSignal;
+ now?: () => number;
+ /**
+ * Permission epoch captured at authorization time plus a reader for the live
+ * epoch. `revalidate` compares them inside the writer transaction so a grant
+ * revoked while blobs were staged is caught before the INSERT (TOCTOU close).
+ * Optional so non-route copy callers/tests are unaffected.
+ */
+ authzEpoch?: { captured: PermissionEpoch; current: () => PermissionEpoch };
+}
+
export class GfsWriteService {
constructor(
private readonly tx: Transactor,
- private readonly blobs: BlobWriter
+ private readonly blobs: BlobWriter,
+ private readonly manifests: PgBlobStagingStore,
+ private readonly ids: { resourceId: () => string; generation: () => string; requestId: () => string } = {
+ resourceId: randomUUID,
+ generation: randomUUID,
+ requestId: randomUUID,
+ }
) {}
- /**
- * Create a new resource under `parentId`. The parent must be a live directory;
- * the sibling name must be unique among live rows (else `already_exists`). File
- * resources write blob bytes; directories create metadata only.
- */
+ async copy(input: CopyInput): Promise<CopyPublicationResult> {
+ return publishCopy(
+ { tx: this.tx, blobs: this.blobs, manifests: this.manifests, ids: this.ids },
+ input
+ );
+ }
+
+ async rename(input: RenameInput): Promise<GfsResource> {
+ return publishRename(this.tx, input);
+ }
+
async create(input: CreateInput): Promise<GfsResource> {
- return this.tx.transaction(async (client) => {
- const kind = input.kind ?? "file";
- if (kind !== "file" && kind !== "directory") {
- throw new GfsError("path_invalid", `unsupported resource kind: ${String(kind)}`);
- }
- const content = input.content ?? Buffer.alloc(0);
- const parentId = toDbResourceId(input.parentId);
- const parent = await this.liveResource(client, input.drive, parentId);
- if (!parent) throw new GfsError("not_found", `parent not found: ${input.parentId}`);
- if (parent.kind !== "directory") {
- throw new GfsError("not_a_directory", `parent is not a directory: ${input.parentId}`);
- }
- const pathCache =
- parent.pathCache == null ? null : `${parent.pathCache === "/" ? "" : parent.pathCache}/${input.name}`;
+ const kind = input.kind ?? "file";
+ if (kind !== "file" && kind !== "directory") {
+ throw new GfsError("path_invalid", `unsupported resource kind: ${String(kind)}`);
+ }
+ const content = input.content ?? Buffer.alloc(0);
+ const resourceId = this.ids.resourceId();
+ const dbResourceId = toDbResourceId(resourceId);
+ const parentId = toDbResourceId(input.parentId);
+ let staged: Awaited<ReturnType<typeof stageVerifiedBlob>> | null = null;
+ let expected: GfsResource | undefined;
- let row: Record<string, unknown>;
- try {
- const res = await client.query(
- `INSERT INTO gfs_resources (drive, parent_resource_id, name, kind, path_cache, version, bytes)
- VALUES ($1, $2, $3, $4, $5, 0, $6)
- RETURNING ${RETURNING}`,
- [input.drive, parentId, input.name, kind, pathCache, kind === "file" ? content.length : 0]
+ try {
+ staged = kind === "file"
+ ? await stageVerifiedBlob(this.manifests, this.blobs, this.ids, resourceId, content)
+ : null;
+ const created = await this.tx.transaction(async client => {
+ await this.lockStructure(client, input.drive);
+ const observedAncestors = await this.loadAncestorChain(client, parentId);
+ if (observedAncestors.length === 0) {
+ throw new GfsError("not_found", `parent not found: ${input.parentId}`);
+ }
+ await this.lockRows(
+ client,
+ observedAncestors.map(row => row.resourceId)
);
- row = res.rows[0];
- } catch (err) {
- if (isUniqueViolation(err)) {
- throw new GfsError("already_exists", `a resource named '${input.name}' already exists here`);
+ const ancestors = await this.loadAncestorChain(client, parentId);
+ if (!this.sameAncestorChain(observedAncestors, ancestors)) {
+ throw new GfsError("precondition_failed", "parent ancestry changed during create");
}
- throw err;
- }
-
- const created = rowToResource(row);
- if (kind === "file") {
- // Blob written INSIDE the tx: a failure here ROLLBACKs the insert, so a
- // metadata row never outlives a failed blob write.
- await this.blobs.write(created.resourceId, content);
- }
+ if (ancestors[0].kind !== "directory") {
+ throw new GfsError("not_a_directory", `parent is not a directory: ${input.parentId}`);
+ }
+ const parentPath = this.canonicalDirectoryPath(ancestors, input.drive);
+ const pathCache = `${parentPath === "/" ? "" : parentPath}/${input.name}`;
+ let row: Record<string, unknown>;
+ try {
+ const res = await client.query(
+ `INSERT INTO gfs_resources
+ (resource_id, drive, parent_resource_id, name, kind, path_cache,
+ version, bytes, blob_key, content_sha256)
+ VALUES ($1, $2, $3, $4, $5, $6, 0, $7, $8, $9)
+ RETURNING ${RETURNING}`,
+ [
+ dbResourceId,
+ input.drive,
+ parentId,
+ input.name,
+ kind,
+ pathCache,
+ kind === "file" ? content.length : 0,
+ staged?.blobKey ?? null,
+ staged?.contentSha256 ?? null,
+ ]
+ );
+ row = res.rows[0];
+ } catch (err) {
+ if (isUniqueViolation(err)) {
+ throw new GfsError("already_exists", `a resource named '${input.name}' already exists here`);
+ }
+ throw err;
+ }
+ if (staged) await this.manifests.markCommitted(client, staged.blobKey);
+ expected = rowToResource(row);
+ await recordManagedMutation(input.mutation, { op: "create", resourceId: dbResourceId, drive: input.drive }, "succeeded", undefined, client);
+ return expected;
+ });
+ if (staged) await this.manifests.removeCommitted(staged.blobKey).catch(() => undefined);
return created;
- });
+ } catch (err) {
+ if (err instanceof CommitOutcomeUnknownError || err instanceof RollbackOutcomeUnknownError) {
+ if (staged) {
+ const published = await this.manifests.resolvePublished(input.drive, dbResourceId, staged.blobKey).catch(() => null);
+ if (published && expected) {
+ await this.manifests.removeCommitted(staged.blobKey).catch(() => undefined);
+ return rowToResource(published);
+ }
+ }
+ const outcome = await inspectCreateOutcome(this.tx, input.drive, dbResourceId, expected);
+ if (outcome === "full" && expected) return expected;
+ if (outcome !== "zero") throw err;
+ }
+ if (staged) await discardCandidate(this.manifests, this.blobs, staged.blobKey).catch(() => undefined);
+ await recordManagedMutation(input.mutation, { op: "create", resourceId: dbResourceId, drive: input.drive }, "failed", err instanceof GfsError ? err.code : "internal_error");
+ throw err;
+ }
}
- /**
- * Replace a FILE's bytes. The row is locked FOR UPDATE so concurrent replaces
- * serialize; `assertIfMatch` enforces optimistic concurrency (a stale If-Match
- * is `precondition_failed`). version is bumped, bytes updated.
- */
async replace(input: ReplaceInput): Promise<GfsResource> {
- return this.tx.transaction(async (client) => {
- const resourceId = toDbResourceId(input.resourceId);
- const current = await this.lockResource(client, input.drive, resourceId);
- if (!current) throw new GfsError("not_found", `resource not found: ${input.resourceId}`);
- if (current.deletedAt) {
- throw GfsError.gone(`resource is deleted: ${input.resourceId}`, "resource_deleted");
- }
- if (current.kind === "directory") {
- throw new GfsError("is_a_directory", `resource is a directory: ${input.resourceId}`);
+ const resourceId = toDbResourceId(input.resourceId);
+ let staged: Awaited<ReturnType<typeof stageVerifiedBlob>> | null = null;
+ let previous: GfsResource | undefined;
+ try {
+ const candidate = await stageVerifiedBlob(this.manifests, this.blobs, this.ids, resourceId, input.content);
+ staged = candidate;
+ const updated = await this.tx.transaction(async client => {
+ const current = await this.lockResource(client, input.drive, resourceId);
+ if (!current) throw new GfsError("not_found", `resource not found: ${input.resourceId}`);
+ if (current.deletedAt) {
+ throw GfsError.gone(`resource is deleted: ${input.resourceId}`, "resource_deleted");
+ }
+ if (current.kind === "directory") {
+ throw new GfsError("is_a_directory", `resource is a directory: ${input.resourceId}`);
+ }
+ previous = current;
+ this.assertVersion(current.version, input.ifMatch);
+ const res = await client.query(
+ `UPDATE gfs_resources
+ SET version = version + 1, bytes = $3, blob_key = $4,
+ content_sha256 = $5, updated_at = now()
+ WHERE drive = $1 AND resource_id = $2 AND deleted_at IS NULL
+ RETURNING ${RETURNING}`,
+ [input.drive, resourceId, input.content.length, candidate.blobKey, candidate.contentSha256]
+ );
+ await this.manifests.markCommitted(client, candidate.blobKey);
+ if (current.blobKey && current.contentSha256) {
+ await this.manifests.markSuperseded(client, {
+ blobKey: current.blobKey,
+ resourceId,
+ contentSha256: current.contentSha256,
+ bytes: current.bytes,
+ });
+ } else {
+ await this.manifests.markLegacySuperseded(client, resourceId, current.bytes);
+ }
+ const published = rowToResource(res.rows[0]);
+ await recordManagedMutation(input.mutation, { op: "replace", resourceId, drive: input.drive }, "succeeded", undefined, client);
+ return published;
+ });
+ await this.manifests.removeCommitted(staged.blobKey).catch(() => undefined);
+ return updated;
+ } catch (err) {
+ if (err instanceof CommitOutcomeUnknownError || err instanceof RollbackOutcomeUnknownError) {
+ if (staged) {
+ const published = await this.manifests.resolvePublished(input.drive, resourceId, staged.blobKey).catch(() => null);
+ if (published) {
+ await this.manifests.removeCommitted(staged.blobKey).catch(() => undefined);
+ return rowToResource(published);
+ }
+ }
+ if (!previous || await inspectReplaceRollback(this.tx, previous) !== "old") throw err;
}
- this.assertVersion(current.version, input.ifMatch);
-
- // Overwrite the blob while holding the row lock, then bump metadata.
- await this.blobs.write(input.resourceId, input.content);
- const res = await client.query(
- `UPDATE gfs_resources
- SET version = version + 1, bytes = $3, updated_at = now()
- WHERE drive = $1 AND resource_id = $2 AND deleted_at IS NULL
- RETURNING ${RETURNING}`,
- [input.drive, resourceId, input.content.length]
- );
- return rowToResource(res.rows[0]);
- });
+ if (staged) await discardCandidate(this.manifests, this.blobs, staged.blobKey).catch(() => undefined);
+ await recordManagedMutation(input.mutation, { op: "replace", resourceId, drive: input.drive }, "failed", err instanceof GfsError ? err.code : "internal_error");
+ throw err;
+ }
}
- /**
- * Soft-delete a resource (tombstone). A non-empty directory is refused
- * (`not_empty`). The blob is RETAINED — hard erasure is a separate P5 path.
- */
async delete(input: DeleteInput): Promise<void> {
return this.tx.transaction(async (client) => {
+ await this.lockStructure(client, input.drive);
const resourceId = toDbResourceId(input.resourceId);
const current = await this.lockResource(client, input.drive, resourceId);
if (!current) throw new GfsError("not_found", `resource not found: ${input.resourceId}`);
@@ -245,7 +429,6 @@ export class GfsWriteService {
});
}
- /** Throw precondition_failed when a provided If-Match does not match. */
private assertVersion(currentVersion: number, ifMatch: number | undefined): void {
try {
assertIfMatch(currentVersion, ifMatch);
@@ -257,21 +440,99 @@ export class GfsWriteService {
}
}
- /** Fetch a resource (any state) without a lock — for the create parent check. */
- private async liveResource(
- client: TxClient,
- drive: string,
- resourceId: string
- ): Promise<GfsResource | null> {
- const res = await client.query(
- `SELECT ${RETURNING} FROM gfs_resources
- WHERE drive = $1 AND resource_id = $2 AND deleted_at IS NULL`,
- [drive, resourceId]
+ private async lockStructure(client: TxClient, drive: string): Promise<void> {
+ await client.query(
+ `SELECT pg_advisory_xact_lock(hashtext('gfs:structure:' || $1)::bigint)`,
+ [drive]
);
- return res.rows[0] ? rowToResource(res.rows[0]) : null;
}
- /** Fetch + row-lock a resource (FOR UPDATE) to serialize concurrent mutations. */
+ private async loadAncestorChain(client: TxClient, resourceId: string): Promise<AncestorRow[]> {
+ const result = await client.query(
+ `WITH RECURSIVE ancestor_chain AS (
+ SELECT r.resource_id, r.drive, r.parent_resource_id, r.name, r.kind, r.deleted_at,
+ ARRAY[r.resource_id]::uuid[] AS visited, false AS cycle, 0 AS depth
+ FROM gfs_resources r
+ WHERE r.resource_id = $1::uuid
+ UNION ALL
+ SELECT parent.resource_id, parent.drive, parent.parent_resource_id,
+ parent.name, parent.kind, parent.deleted_at,
+ child.visited || parent.resource_id,
+ parent.resource_id = ANY(child.visited) AS cycle,
+ child.depth + 1
+ FROM ancestor_chain child
+ JOIN gfs_resources parent ON parent.resource_id = child.parent_resource_id
+ WHERE NOT child.cycle
+ )
+ SELECT resource_id, drive, parent_resource_id, name, kind, deleted_at, cycle
+ FROM ancestor_chain
+ ORDER BY depth ASC`,
+ [resourceId]
+ );
+ return result.rows.map(row => ({
+ resourceId: String(row.resource_id),
+ drive: String(row.drive),
+ parentResourceId:
+ row.parent_resource_id == null ? null : String(row.parent_resource_id),
+ name: String(row.name),
+ kind: String(row.kind),
+ deletedAt: toIsoOrNull(row.deleted_at),
+ cycle: row.cycle === true,
+ }));
+ }
+
+ private async lockRows(client: TxClient, resourceIds: string[]): Promise<void> {
+ const ids = [...new Set(resourceIds)].sort();
+ await client.query(
+ `SELECT resource_id
+ FROM gfs_resources
+ WHERE resource_id = ANY($1::uuid[])
+ ORDER BY resource_id
+ FOR UPDATE`,
+ [ids]
+ );
+ }
+
+ private sameAncestorChain(observed: AncestorRow[], locked: AncestorRow[]): boolean {
+ return (
+ observed.length === locked.length &&
+ observed.every((row, index) => {
+ const current = locked[index];
+ return (
+ current !== undefined &&
+ row.resourceId === current.resourceId &&
+ row.drive === current.drive &&
+ row.parentResourceId === current.parentResourceId &&
+ row.name === current.name &&
+ row.kind === current.kind &&
+ row.deletedAt === current.deletedAt &&
+ row.cycle === current.cycle
+ );
+ })
+ );
+ }
+
+ private canonicalDirectoryPath(ancestors: AncestorRow[], drive: string): string {
+ if (
+ ancestors.some(
+ row =>
+ row.cycle ||
+ row.deletedAt !== null ||
+ row.drive !== drive ||
+ row.kind !== "directory"
+ ) ||
+ ancestors.at(-1)?.parentResourceId !== null ||
+ ancestors.at(-1)?.name !== ""
+ ) {
+ throw new GfsError("precondition_failed", "parent ancestry is not a live same-drive chain");
+ }
+ const segments = ancestors
+ .slice(0, -1)
+ .map(row => row.name)
+ .reverse();
+ return segments.length === 0 ? "/" : `/${segments.join("/")}`;
+ }
+
private async lockResource(
client: TxClient,
drive: string,
diff --git a/gfs-controller/src/index.ts b/gfs-controller/src/index.ts
index ab4130e4a..02e0aaf94 100644
--- a/gfs-controller/src/index.ts
+++ b/gfs-controller/src/index.ts
@@ -12,6 +12,7 @@ import { resolveAuthzContext } from "./authz/subjectResolver";
import { loadConfig } from "./config";
import { PgResourceStore } from "./db/resourceStore";
import { GfsWriteService, PgTransactor } from "./db/writeStore";
+import { PgBlobStagingStore, reconcileExpiredBlobs } from "./db/blobStaging";
import { GfsMetrics } from "./metrics";
import { GfsServer, ReadinessDeps } from "./server";
import { BlobStore } from "./storage/blobStore";
@@ -97,6 +98,7 @@ async function main(): Promise<void> {
pool,
connectionString: config.pgConnectionString,
intervalMs: config.credentialProbeIntervalMs,
+ storageRole: config.storageRole,
}),
};
@@ -107,6 +109,7 @@ async function main(): Promise<void> {
const metrics = new GfsMetrics();
let serving: GfsServingHandler | undefined;
let invalidation: { stop: () => Promise<void> } | undefined;
+ let cleanupTimer: NodeJS.Timeout | undefined;
if (config.publicKey.trim() !== "") {
const verificationKey = loadVerificationKey(config.publicKey);
@@ -117,12 +120,38 @@ async function main(): Promise<void> {
cache.setBypassed(true);
invalidation = startInvalidation(config.pgConnectionString, cache);
- const permissions = new PermissionClient(pool, new DbAuditSink(pool), cache);
+ const audit = new DbAuditSink(pool);
+ const permissions = new PermissionClient(pool, audit, cache);
const accessible = new AccessibleResourceStore(pool);
const store = new PgResourceStore(pool);
const blobs = new BlobStore(config.storageMountPath, config.storageRole);
+ const blobManifests = config.storageRole === "writer" ? new PgBlobStagingStore(pool) : undefined;
const writeService =
- config.storageRole === "writer" ? new GfsWriteService(new PgTransactor(pool), blobs) : undefined;
+ config.storageRole === "writer"
+ ? new GfsWriteService(new PgTransactor(pool), blobs, blobManifests!)
+ : undefined;
+
+ if (config.storageRole === "writer") {
+ let cleanupRunning = false;
+ const cleanup = async (): Promise<void> => {
+ if (cleanupRunning) return;
+ cleanupRunning = true;
+ try {
+ await reconcileExpiredBlobs(blobManifests!, blobs, metrics, {
+ olderThanMs: config.blobCleanupSafetyWindowMs,
+ limit: config.blobCleanupBatchSize,
+ });
+ } catch (err) {
+ metrics.recordBlobCleanupFailure();
+ console.error(`[gfsc] blob reconciliation failed: ${errMsg(err)}`);
+ } finally {
+ cleanupRunning = false;
+ }
+ };
+ cleanupTimer = setInterval(() => void cleanup(), config.blobCleanupIntervalMs);
+ cleanupTimer.unref();
+ void cleanup();
+ }
serving = new GfsServingHandler({
verifyToken: (token) =>
@@ -133,6 +162,22 @@ async function main(): Promise<void> {
store,
blobs,
...(writeService ? { writeService } : {}),
+ ...(writeService ? { audit } : {}),
+ ...(writeService ? {
+ copy: {
+ authorizeMany: (ctx, requests, budget) => permissions.authorizeMany(ctx, requests, budget),
+ permissionEpoch: () => permissions.permissionEpoch(),
+ resources: store,
+ audit,
+ maxObjects: config.syncCopyMaxObjects,
+ maxBytes: config.syncCopyMaxBytes,
+ timeoutMs: config.syncCopyTimeoutMs,
+ },
+ rename: {
+ maxObjects: config.syncRenameMaxObjects,
+ timeoutMs: config.syncRenameTimeoutMs,
+ },
+ } : {}),
metrics,
});
} else if (!config.devMode) {
@@ -152,6 +197,7 @@ async function main(): Promise<void> {
console.log(`[gfsc] ${signal} received, shutting down`);
await server.stop();
if (invalidation) await invalidation.stop();
+ if (cleanupTimer) clearInterval(cleanupTimer);
await pool.end();
process.exit(0);
};
diff --git a/gfs-controller/src/metrics.test.ts b/gfs-controller/src/metrics.test.ts
index 55abc572c..7b977ce6b 100644
--- a/gfs-controller/src/metrics.test.ts
+++ b/gfs-controller/src/metrics.test.ts
@@ -41,6 +41,9 @@ describe("GfsMetrics", () => {
"gfs_read_after_write_lag_ms",
"gfs_quota_usage_ratio",
"gfs_cache_hit_rate",
+ "gfs_blob_orphan_candidates",
+ "gfs_blob_orphan_bytes",
+ "gfs_blob_cleanup_failures_total",
]) {
expect(text).toContain(metric);
}
@@ -48,6 +51,17 @@ describe("GfsMetrics", () => {
expect(text).toContain("gfs_read_after_write_lag_ms 7");
});
+ it("tracks conservative blob reconciliation candidates and failures", () => {
+ const m = new GfsMetrics();
+ m.setOrphanCandidates(3, 4096);
+ m.recordBlobCleanupFailure();
+ expect(m.snapshot()).toMatchObject({
+ orphanCandidates: 3,
+ orphanBytes: 4096,
+ blobCleanupFailures: 1,
+ });
+ });
+
it("is zero-valued before any observation (empty p99 = 0, no division by zero)", () => {
const s = new GfsMetrics().snapshot();
expect(s.readLatencyP99Ms).toBe(0);
diff --git a/gfs-controller/src/metrics.ts b/gfs-controller/src/metrics.ts
index 8059a7153..d48daa859 100644
--- a/gfs-controller/src/metrics.ts
+++ b/gfs-controller/src/metrics.ts
@@ -13,6 +13,9 @@ export interface SliSnapshot {
readAfterWriteLagMs: number
quotaUsageRatio: number
cacheHitRate: number
+ orphanCandidates: number
+ orphanBytes: number
+ blobCleanupFailures: number
}
function percentile(values: number[], p: number): number {
@@ -31,6 +34,9 @@ export class GfsMetrics {
private quotaUsageRatio = 0
private cacheHits = 0
private cacheMisses = 0
+ private orphanCandidates = 0
+ private orphanBytes = 0
+ private blobCleanupFailures = 0
/** Cap retained latency samples so a long-running writer cannot grow unbounded. */
private static readonly MAX_LAT_SAMPLES = 10_000
@@ -60,6 +66,13 @@ export class GfsMetrics {
setReadAfterWriteLagMs(ms: number): void {
this.readAfterWriteLagMs = ms
}
+ setOrphanCandidates(count: number, bytes: number): void {
+ this.orphanCandidates = count
+ this.orphanBytes = bytes
+ }
+ recordBlobCleanupFailure(): void {
+ this.blobCleanupFailures += 1
+ }
snapshot(): SliSnapshot {
const totalCache = this.cacheHits + this.cacheMisses
@@ -71,6 +84,9 @@ export class GfsMetrics {
readAfterWriteLagMs: this.readAfterWriteLagMs,
quotaUsageRatio: this.quotaUsageRatio,
cacheHitRate: totalCache === 0 ? 0 : this.cacheHits / totalCache,
+ orphanCandidates: this.orphanCandidates,
+ orphanBytes: this.orphanBytes,
+ blobCleanupFailures: this.blobCleanupFailures,
}
}
@@ -86,6 +102,9 @@ export class GfsMetrics {
`gfs_read_after_write_lag_ms ${s.readAfterWriteLagMs}`,
`gfs_quota_usage_ratio ${s.quotaUsageRatio}`,
`gfs_cache_hit_rate ${s.cacheHitRate}`,
+ `gfs_blob_orphan_candidates ${s.orphanCandidates}`,
+ `gfs_blob_orphan_bytes ${s.orphanBytes}`,
+ `gfs_blob_cleanup_failures_total ${s.blobCleanupFailures}`,
]
return lines.join('\n') + '\n'
}
diff --git a/gfs-controller/src/server.test.ts b/gfs-controller/src/server.test.ts
index 9b481fe25..8fe29fa7d 100644
--- a/gfs-controller/src/server.test.ts
+++ b/gfs-controller/src/server.test.ts
@@ -13,6 +13,12 @@ const baseConfig: GfsConfig = {
driveName: "main",
decisionCacheTtlMs: 5000,
credentialProbeIntervalMs: 60_000,
+ blobCleanupSafetyWindowMs: 3_600_000,
+ blobCleanupIntervalMs: 60_000,
+ blobCleanupBatchSize: 100,
+ syncCopyMaxObjects: 1000,
+ syncCopyMaxBytes: 1073741824,
+ syncCopyTimeoutMs: 30000,
devMode: true,
};
diff --git a/gfs-controller/src/storage/blobStore.copy.test.ts b/gfs-controller/src/storage/blobStore.copy.test.ts
new file mode 100644
index 000000000..43558e7f8
--- /dev/null
+++ b/gfs-controller/src/storage/blobStore.copy.test.ts
@@ -0,0 +1,67 @@
+import { existsSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { Readable } from "node:stream";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { BlobStore } from "./blobStore";
+import { resolveBlobKeyPath } from "./paths";
+
+const RID = "0123456789abcdef0123456789abcdef";
+const GENERATION = "11111111-1111-4111-8111-111111111111";
+
+describe("BlobStore copy staging safeguards", () => {
+ let dir: string;
+ beforeEach(() => { dir = mkdtempSync(join(tmpdir(), "gfs-copy-")); });
+ afterEach(() => { rmSync(dir, { recursive: true, force: true }); });
+
+ it("computes available bytes with bigint statfs operands", async () => {
+ const bavail = 9_007_199_254_740_993n;
+ const bsize = 4096n;
+ const store = new BlobStore(dir, "writer", async () => undefined, async path => {
+ expect(path).toBe(dir);
+ return { bavail, bsize };
+ });
+ expect(await store.availableBytes()).toBe(bavail * bsize);
+ });
+
+ it("awaits stream cancellation and removes partial bytes on abort", async () => {
+ const controller = new AbortController();
+ let sourceClosed = false;
+ const source = Readable.from((async function* () {
+ try {
+ yield Buffer.from("first");
+ controller.abort(new Error("copy cancelled"));
+ yield Buffer.from("second");
+ } finally {
+ sourceClosed = true;
+ }
+ })());
+ const store = new BlobStore(dir, "writer");
+ await expect(store.writeImmutable(RID, GENERATION, source, { signal: controller.signal })).rejects.toThrow();
+ expect(sourceClosed).toBe(true);
+ expect(existsSync(resolveBlobKeyPath(dir, `${RID}/${GENERATION}`))).toBe(false);
+ });
+
+ it("propagates ENOSPC without leaving a partial generation", async () => {
+ const full = Object.assign(new Error("disk full"), { code: "ENOSPC" });
+ const source = new Readable({ read() { this.destroy(full); } });
+ const store = new BlobStore(dir, "writer");
+ await expect(store.writeImmutable(RID, GENERATION, source)).rejects.toMatchObject({ code: "ENOSPC" });
+ expect(existsSync(resolveBlobKeyPath(dir, `${RID}/${GENERATION}`))).toBe(false);
+ });
+
+ it("checks the deadline around every durability sync and cleans a failed candidate", async () => {
+ let checks = 0;
+ let syncs = 0;
+ const store = new BlobStore(dir, "writer", async () => { syncs += 1; });
+ await expect(store.writeImmutable(RID, GENERATION, Buffer.from("data"), {
+ checkDeadline: () => {
+ checks += 1;
+ if (syncs === 2) throw new Error("deadline");
+ },
+ })).rejects.toThrow("deadline");
+ expect(syncs).toBe(5); // two write syncs, then three cleanup directory syncs
+ expect(checks).toBeGreaterThan(4);
+ expect(existsSync(resolveBlobKeyPath(dir, `${RID}/${GENERATION}`))).toBe(false);
+ });
+});
diff --git a/gfs-controller/src/storage/blobStore.test.ts b/gfs-controller/src/storage/blobStore.test.ts
index 77b8e2a41..4e4047813 100644
Binary files a/gfs-controller/src/storage/blobStore.test.ts and b/gfs-controller/src/storage/blobStore.test.ts differ
diff --git a/gfs-controller/src/storage/blobStore.ts b/gfs-controller/src/storage/blobStore.ts
index a39beabd4..d7d9aab13 100644
--- a/gfs-controller/src/storage/blobStore.ts
+++ b/gfs-controller/src/storage/blobStore.ts
@@ -1,20 +1,48 @@
-import { createReadStream, createWriteStream } from "node:fs";
+import { createHash } from "node:crypto";
+import { constants } from "node:fs";
import {
- lstat as fsLstat,
- mkdir as fsMkdir,
- readdir as fsReaddir,
+ open as fsOpen,
+ rmdir as fsRmdir,
rm as fsRm,
stat as fsStat,
+ statfs as fsStatfs,
} from "node:fs/promises";
import { dirname } from "node:path";
-import { Readable } from "node:stream";
+import { Readable, Transform } from "node:stream";
import { pipeline } from "node:stream/promises";
-import { PathError, resolveBlobPath } from "./paths";
+import {
+ generationBlobKey,
+ normalizeBlobKey,
+ normalizeResourceId,
+ PathError,
+ resolveBlobKeyPath,
+ resolveBlobPath,
+} from "./paths";
+import {
+ ImmutableBlobFilesystem,
+ isErrno,
+ syncFilesystemPath,
+ type DurabilitySync,
+ type GenerationDirectoryOwnership,
+ type RemoveBlobPath,
+ type RemoveEmptyDirectory,
+} from "./immutableBlobFilesystem";
-export interface BlobStat {
- exists: boolean;
+export interface ImmutableBlob {
+ blobKey: string;
bytes: number;
+ contentSha256: string;
}
+export interface ImmutableWriteOptions {
+ signal?: AbortSignal;
+ checkDeadline?: () => void;
+}
+export type FilesystemStats = (path: string) => Promise<{ bavail: bigint; bsize: bigint }>;
+type ExclusiveBlobOpen = (path: string, flags: number, mode: number) => ReturnType<typeof fsOpen>;
+const readFilesystemStats: FilesystemStats = async path => {
+ const stats = await fsStatfs(path, { bigint: true });
+ return { bavail: stats.bavail, bsize: stats.bsize };
+};
export class ReadOnlyStoreError extends Error {
readonly code = "forbidden";
@@ -26,79 +54,210 @@ export class ReadOnlyStoreError extends Error {
export class BlobNotFoundError extends Error {
readonly code = "not_found";
- constructor(resourceId: string) {
- super(`blob not found: ${resourceId}`);
+ constructor() {
+ super("blob not found");
this.name = "BlobNotFoundError";
}
}
+export class BlobVerificationError extends Error {
+ constructor(message = "immutable blob verification failed") {
+ super(message);
+ this.name = "BlobVerificationError";
+ }
+}
+export class BlobWriteCleanupError extends AggregateError {
+ constructor(
+ readonly writeError: unknown,
+ readonly cleanupErrors: readonly unknown[]
+ ) {
+ super([writeError, ...cleanupErrors], "immutable blob write failed and cleanup was incomplete", {
+ cause: writeError,
+ });
+ this.name = "BlobWriteCleanupError";
+ }
+}
+
+function immutableBlobKey(resourceId: unknown, generation: unknown): string {
+ try {
+ return generationBlobKey(resourceId, generation);
+ } catch (err) {
+ if (err instanceof PathError) throw new PathError("invalid immutable blob identity");
+ throw err;
+ }
+}
-function isErrno(err: unknown, code: string): boolean {
- return (err as NodeJS.ErrnoException | undefined)?.code === code;
+function committedBlobKey(resourceId: string, blobKey: string): string {
+ let normalized: string;
+ try {
+ normalized = normalizeBlobKey(blobKey);
+ } catch (err) {
+ if (err instanceof PathError) throw new PathError("invalid committed blob reference");
+ throw err;
+ }
+ if (!normalized.startsWith(`${normalizeResourceId(resourceId)}/`)) {
+ throw new PathError("blob key does not belong to resource");
+ }
+ return normalized;
}
-/**
- * Flat blob store: opaque bytes keyed by resourceId at `<prefix>/<resourceId>`.
- * The writer replica mounts the volume RW; reader replicas mount it RO and must
- * never mutate (enforced here AND by the pod's read-only mount). The human path
- * is DB metadata, never reflected on disk, so there is no rename/move here — a
- * move is a pure DB reparent.
- */
+/** Immutable generations plus read-only legacy flat blobs. */
export class BlobStore {
+ private readonly immutableFilesystem: ImmutableBlobFilesystem;
+
constructor(
private readonly prefix: string,
- private readonly role: "writer" | "reader"
- ) {}
+ private readonly role: "writer" | "reader",
+ private readonly durabilitySync: DurabilitySync = syncFilesystemPath,
+ private readonly filesystemStats: FilesystemStats = readFilesystemStats,
+ private readonly openExclusive: ExclusiveBlobOpen = fsOpen,
+ removeBlobPath?: RemoveBlobPath,
+ removeEmptyDirectory?: RemoveEmptyDirectory
+ ) {
+ this.immutableFilesystem = new ImmutableBlobFilesystem(
+ prefix,
+ durabilitySync,
+ removeBlobPath,
+ removeEmptyDirectory
+ );
+ }
private requireWriter(): void {
if (this.role !== "writer") throw new ReadOnlyStoreError();
}
- /**
- * Reject a symlink at the blob path. gfsc never follows a symlink out of the
- * prefix; a missing path is fine (the blob simply does not exist yet).
- */
- private async assertNotSymlink(path: string): Promise<void> {
- try {
- const info = await fsLstat(path);
- if (info.isSymbolicLink()) {
- throw new PathError("blob path is a symlink");
- }
- } catch (err) {
- if (isErrno(err, "ENOENT")) return;
- throw err;
+ private checkWrite(options: ImmutableWriteOptions): void {
+ options.signal?.throwIfAborted();
+ options.checkDeadline?.();
+ }
+
+ async availableBytes(): Promise<bigint> {
+ const stats = await this.filesystemStats(this.prefix);
+ if (stats.bavail < 0n || stats.bsize < 0n) {
+ throw new Error("filesystem reported invalid available space");
}
+ return stats.bavail * stats.bsize;
}
- async write(resourceId: string, data: Readable | Buffer): Promise<{ bytes: number }> {
+ async writeImmutable(
+ resourceId: string,
+ generation: string,
+ data: Readable | Buffer,
+ options: ImmutableWriteOptions = {}
+ ): Promise<ImmutableBlob> {
this.requireWriter();
- const path = resolveBlobPath(this.prefix, resourceId);
- await this.assertNotSymlink(path);
- await fsMkdir(dirname(path), { recursive: true });
+ this.checkWrite(options);
+ const blobKey = immutableBlobKey(resourceId, generation);
+ const path = resolveBlobKeyPath(this.prefix, blobKey);
+ const parent = dirname(path);
+ const generationRoot = dirname(parent);
const source = Buffer.isBuffer(data) ? Readable.from(data) : data;
- await pipeline(source, createWriteStream(path, { flags: "w", mode: 0o600 }));
- const info = await fsStat(path);
- return { bytes: info.size };
- }
-
- async read(resourceId: string): Promise<Readable> {
- const path = resolveBlobPath(this.prefix, resourceId);
- await this.assertNotSymlink(path);
+ const digest = createHash("sha256");
+ let bytes = 0;
+ const hashing = new Transform({
+ transform(chunk: Buffer, _encoding, callback) {
+ try {
+ options.signal?.throwIfAborted();
+ options.checkDeadline?.();
+ const value = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
+ bytes += value.length;
+ digest.update(value);
+ callback(null, value);
+ } catch (err) {
+ callback(err as Error);
+ }
+ },
+ });
+ let created = false;
+ const directoryOwnership: GenerationDirectoryOwnership = {
+ generationRoot: false,
+ resourceDirectory: false,
+ };
try {
- await fsStat(path);
+ this.checkWrite(options);
+ await this.immutableFilesystem.ensureGenerationParent(path, directoryOwnership);
+ this.checkWrite(options);
+ await this.immutableFilesystem.assertSafeParents(path);
+ await this.immutableFilesystem.assertNotSymlink(path);
+ this.checkWrite(options);
+ const handle = await this.openExclusive(
+ path,
+ constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,
+ 0o600
+ );
+ created = true;
+ await pipeline(source, hashing, handle.createWriteStream(), { signal: options.signal });
+ this.checkWrite(options);
+ for (const syncPath of [path, parent, generationRoot, this.prefix]) {
+ this.checkWrite(options);
+ await this.durabilitySync(syncPath);
+ this.checkWrite(options);
+ }
+ const info = await fsStat(path);
+ if (!info.isFile() || info.size !== bytes) {
+ throw new BlobVerificationError("immutable blob size verification failed");
+ }
+ const contentSha256 = digest.digest("hex");
+ await this.verify(blobKey, bytes, contentSha256, options);
+ return { blobKey, bytes, contentSha256 };
} catch (err) {
- if (isErrno(err, "ENOENT")) throw new BlobNotFoundError(resourceId);
+ const cleanupErrors = await this.immutableFilesystem.cleanupFailedWrite(
+ path,
+ created,
+ directoryOwnership
+ );
+ if (cleanupErrors.length > 0) {
+ throw new BlobWriteCleanupError(err, cleanupErrors);
+ }
throw err;
}
- return createReadStream(path);
}
- async stat(resourceId: string): Promise<BlobStat> {
- const path = resolveBlobPath(this.prefix, resourceId);
+ async verify(
+ blobKey: string,
+ expectedBytes: number,
+ expectedSha256: string,
+ options: ImmutableWriteOptions = {}
+ ): Promise<void> {
+ this.checkWrite(options);
+ const path = resolveBlobKeyPath(this.prefix, blobKey);
+ await this.immutableFilesystem.assertSafeParents(path);
+ await this.immutableFilesystem.assertNotSymlink(path);
+ const digest = createHash("sha256");
+ let bytes = 0;
+ const handle = await fsOpen(path, constants.O_RDONLY | constants.O_NOFOLLOW);
+ const stream = handle.createReadStream();
+ for await (const chunk of stream) {
+ this.checkWrite(options);
+ const value = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
+ bytes += value.length;
+ digest.update(value);
+ }
+ this.checkWrite(options);
+ const actual = digest.digest("hex");
+ if (bytes !== expectedBytes || actual !== expectedSha256) {
+ throw new BlobVerificationError("immutable blob digest verification failed");
+ }
+ }
+
+ async read(resourceId: string, blobKey?: string | null): Promise<Readable> {
+ const normalizedBlobKey = blobKey ? committedBlobKey(resourceId, blobKey) : null;
+ const path = normalizedBlobKey
+ ? resolveBlobKeyPath(this.prefix, normalizedBlobKey)
+ : resolveBlobPath(this.prefix, resourceId);
try {
- const info = await fsStat(path);
- return { exists: true, bytes: info.size };
+ await this.immutableFilesystem.assertSafeParents(path);
+ await this.immutableFilesystem.assertNotSymlink(path);
+ const handle = await fsOpen(path, constants.O_RDONLY | constants.O_NOFOLLOW);
+ try {
+ const info = await handle.stat();
+ if (!info.isFile()) throw new PathError("blob path is not a file");
+ return handle.createReadStream();
+ } catch (err) {
+ await handle.close().catch(() => undefined);
+ throw err;
+ }
} catch (err) {
- if (isErrno(err, "ENOENT")) return { exists: false, bytes: 0 };
+ if (isErrno(err, "ENOENT")) throw new BlobNotFoundError();
throw err;
}
}
@@ -106,25 +265,57 @@ export class BlobStore {
async delete(resourceId: string): Promise<void> {
this.requireWriter();
const path = resolveBlobPath(this.prefix, resourceId);
- await this.assertNotSymlink(path);
+ await this.immutableFilesystem.assertSafeParents(path);
+ await this.immutableFilesystem.assertNotSymlink(path);
try {
await fsRm(path, { force: false });
+ await this.durabilitySync(this.prefix);
} catch (err) {
- if (isErrno(err, "ENOENT")) throw new BlobNotFoundError(resourceId);
+ if (isErrno(err, "ENOENT")) throw new BlobNotFoundError();
throw err;
}
}
- /**
- * Physical enumeration of stored blob keys (for ops / GC). The human-facing
- * directory listing is DB-driven (cursor-paginated), never this call.
- */
- async list(): Promise<string[]> {
+ async deleteByKey(blobKey: string): Promise<void> {
+ this.requireWriter();
+ const path = resolveBlobKeyPath(this.prefix, blobKey);
+ const parent = dirname(path);
+ const generationRoot = dirname(parent);
try {
- return await fsReaddir(this.prefix);
+ await this.immutableFilesystem.assertSafeDirectory(generationRoot);
} catch (err) {
- if (isErrno(err, "ENOENT")) return [];
- throw err;
+ if (!isErrno(err, "ENOENT")) throw err;
+ await this.durabilitySync(this.prefix);
+ return;
}
+
+ let parentExists = true;
+ try {
+ await this.immutableFilesystem.assertSafeParents(path);
+ } catch (err) {
+ if (!isErrno(err, "ENOENT")) throw err;
+ parentExists = false;
+ }
+
+ if (parentExists) {
+ await this.immutableFilesystem.assertNotSymlink(path);
+ try {
+ await fsRm(path, { force: false });
+ } catch (err) {
+ if (!isErrno(err, "ENOENT")) throw err;
+ }
+ await this.durabilitySync(parent);
+ }
+
+ try {
+ await fsRmdir(parent);
+ } catch (err) {
+ if (!isErrno(err, "ENOENT") && !isErrno(err, "ENOTEMPTY")) throw err;
+ }
+ await this.durabilitySync(generationRoot);
+ await this.durabilitySync(this.prefix);
+ }
+ async deleteLegacyFlat(resourceId: string): Promise<void> {
+ return this.delete(resourceId);
}
}
diff --git a/gfs-controller/src/storage/immutableBlobFilesystem.ts b/gfs-controller/src/storage/immutableBlobFilesystem.ts
new file mode 100644
index 000000000..2465e437e
--- /dev/null
+++ b/gfs-controller/src/storage/immutableBlobFilesystem.ts
@@ -0,0 +1,166 @@
+import {
+ lstat,
+ mkdir,
+ open,
+ realpath,
+ rmdir,
+ rm,
+} from "node:fs/promises";
+import { dirname, sep } from "node:path";
+import { PathError } from "./paths";
+
+export interface GenerationDirectoryOwnership {
+ generationRoot: boolean;
+ resourceDirectory: boolean;
+}
+
+export type DurabilitySync = (path: string) => Promise<void>;
+export type RemoveBlobPath = (path: string) => Promise<void>;
+export type RemoveEmptyDirectory = (path: string) => Promise<void>;
+
+export function isErrno(err: unknown, code: string): boolean {
+ return (err as NodeJS.ErrnoException | undefined)?.code === code;
+}
+
+export async function syncFilesystemPath(path: string): Promise<void> {
+ const handle = await open(path, "r");
+ try {
+ await handle.sync();
+ } finally {
+ await handle.close();
+ }
+}
+
+export const removeBlobPath: RemoveBlobPath = async path => rm(path, { force: false });
+
+export class ImmutableBlobFilesystem {
+ constructor(
+ private readonly prefix: string,
+ private readonly durabilitySync: DurabilitySync,
+ private readonly removeBlob: RemoveBlobPath = removeBlobPath,
+ private readonly removeDirectory: RemoveEmptyDirectory = rmdir
+ ) {}
+
+ /** Reject a blob-path symlink; a missing path is valid before an immutable write. */
+ async assertNotSymlink(path: string): Promise<void> {
+ try {
+ const info = await lstat(path);
+ if (info.isSymbolicLink()) throw new PathError("blob path is a symlink");
+ } catch (err) {
+ if (isErrno(err, "ENOENT")) return;
+ throw err;
+ }
+ }
+
+ async assertSafeDirectory(directory: string): Promise<void> {
+ const base = await this.resolveStoragePrefix();
+ const directoryInfo = await lstat(directory);
+ if (directoryInfo.isSymbolicLink() || !directoryInfo.isDirectory()) {
+ throw new PathError("blob parent must be a real directory");
+ }
+ const resolvedDirectory = await realpath(directory);
+ if (resolvedDirectory !== base && !resolvedDirectory.startsWith(`${base}${sep}`)) {
+ throw new PathError("blob parent escapes the storage prefix");
+ }
+ }
+
+ async assertSafeParents(path: string): Promise<void> {
+ await this.assertSafeDirectory(dirname(path));
+ }
+
+ private async resolveStoragePrefix(): Promise<string> {
+ const prefixInfo = await lstat(this.prefix);
+ if (prefixInfo.isSymbolicLink() || !prefixInfo.isDirectory()) {
+ throw new PathError("storage prefix must be a real directory");
+ }
+ return realpath(this.prefix);
+ }
+
+ async ensureGenerationParent(
+ path: string,
+ ownership: GenerationDirectoryOwnership
+ ): Promise<void> {
+ const parent = dirname(path);
+ const generationRoot = dirname(parent);
+ const ensureDirectory = async (
+ directory: string,
+ ownershipKey: keyof GenerationDirectoryOwnership
+ ): Promise<void> => {
+ try {
+ await mkdir(directory, { mode: 0o700 });
+ ownership[ownershipKey] = true;
+ } catch (err) {
+ if (!isErrno(err, "EEXIST")) throw err;
+ }
+ await this.assertSafeDirectory(directory);
+ };
+
+ await ensureDirectory(generationRoot, "generationRoot");
+ await ensureDirectory(parent, "resourceDirectory");
+ }
+
+ /**
+ * Cleanup must be durable before a caller may discard its staging manifest.
+ * Independent steps continue after a fault so reconciliation has the
+ * smallest possible orphan, but every cleanup fault is returned to caller.
+ */
+ async cleanupFailedWrite(
+ path: string,
+ ownsBlob: boolean,
+ ownership: GenerationDirectoryOwnership
+ ): Promise<unknown[]> {
+ if (!ownsBlob && !ownership.resourceDirectory && !ownership.generationRoot) return [];
+ const parent = dirname(path);
+ const generationRoot = dirname(parent);
+ const errors: unknown[] = [];
+ let parentIsSafe = false;
+
+ try {
+ await this.assertSafeDirectory(parent);
+ parentIsSafe = true;
+ } catch (err) {
+ if (!isErrno(err, "ENOENT")) errors.push(err);
+ }
+
+ if (ownsBlob && parentIsSafe) {
+ try {
+ await this.removeBlob(path);
+ } catch (err) {
+ if (!isErrno(err, "ENOENT")) errors.push(err);
+ }
+ try {
+ await this.durabilitySync(parent);
+ } catch (err) {
+ if (!isErrno(err, "ENOENT")) errors.push(err);
+ }
+ }
+
+ if (ownership.resourceDirectory) {
+ try {
+ await this.removeDirectory(parent);
+ } catch (err) {
+ if (!isErrno(err, "ENOENT") && !isErrno(err, "ENOTEMPTY")) errors.push(err);
+ }
+ try {
+ await this.durabilitySync(generationRoot);
+ } catch (err) {
+ if (!isErrno(err, "ENOENT")) errors.push(err);
+ }
+ }
+
+ if (ownership.generationRoot) {
+ try {
+ await this.removeDirectory(generationRoot);
+ } catch (err) {
+ if (!isErrno(err, "ENOENT") && !isErrno(err, "ENOTEMPTY")) errors.push(err);
+ }
+ try {
+ await this.durabilitySync(this.prefix);
+ } catch (err) {
+ errors.push(err);
+ }
+ }
+
+ return errors;
+ }
+}
diff --git a/gfs-controller/src/storage/paths.ts b/gfs-controller/src/storage/paths.ts
index d7d7a3c1e..4084c4622 100644
--- a/gfs-controller/src/storage/paths.ts
+++ b/gfs-controller/src/storage/paths.ts
@@ -1,17 +1,16 @@
-import { resolve, sep } from "node:path";
+import { join, resolve } from "node:path";
/**
- * Path safety for the flat blob layout. Bytes live at
- * `<storage-prefix>/<resourceId>` and the ONLY path component derived from
- * caller input is the resourceId. By constraining it to lowercase hex (a UUID
- * or its 32-hex `rid` form), every traversal vector — `..`, NUL, backslash,
- * absolute markers, path separators — is rejected by construction, before any
- * filesystem call. We additionally re-anchor and assert containment under the
- * prefix as defense in depth. gfsc never trusts inode identity for authz.
+ * Path safety for both legacy flat blobs and immutable generations. New bytes
+ * live in a reserved internal namespace while their logical key remains
+ * `<resourceId>/<generation>`; legacy rows whose metadata has no blob key
+ * continue to resolve to `<storage-prefix>/<resourceId>`.
*/
const RID_RE = /^[0-9a-f]{32}$/;
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
+const GENERATION_RE = UUID_RE;
+export const GENERATION_STORAGE_DIRECTORY = ".generations";
export class PathError extends Error {
readonly code = "path_invalid";
@@ -37,18 +36,54 @@ export function normalizeResourceId(resourceId: unknown): string {
throw new PathError(`invalid resourceId: ${JSON.stringify(resourceId)}`);
}
+export function normalizeGeneration(generation: unknown): string {
+ if (typeof generation !== "string") {
+ throw new PathError("generation must be a string");
+ }
+ const value = generation.trim().toLowerCase();
+ if (!GENERATION_RE.test(value)) {
+ throw new PathError(`invalid generation: ${JSON.stringify(generation)}`);
+ }
+ return value;
+}
+
+export function generationBlobKey(resourceId: unknown, generation: unknown): string {
+ return `${normalizeResourceId(resourceId)}/${normalizeGeneration(generation)}`;
+}
+
+export function normalizeBlobKey(blobKey: unknown): string {
+ if (typeof blobKey !== "string") throw new PathError("blobKey must be a string");
+ const parts = blobKey.split("/");
+ if (parts.length !== 2) throw new PathError("blobKey must contain resource id and generation");
+ return generationBlobKey(parts[0], parts[1]);
+}
+
/**
* Resolve the absolute on-disk blob path, guaranteed to sit directly under the
* storage prefix. Because the key is hex-only it can contain no separators,
* `..`, NUL, backslash, or absolute markers; the containment assertion is a
* second, independent guard.
*/
-export function resolveBlobPath(storagePrefix: string, resourceId: unknown): string {
+export function resolveBlobPath(
+ storagePrefix: string,
+ resourceId: unknown
+): string {
const key = normalizeResourceId(resourceId);
const base = resolve(storagePrefix);
- const full = resolve(base, key);
- if (full !== `${base}${sep}${key}`) {
+ const relative = [key];
+ const full = resolve(base, ...relative);
+ if (full !== join(base, ...relative)) {
throw new PathError("resolved blob path escapes the storage prefix");
}
return full;
}
+export function resolveBlobKeyPath(storagePrefix: string, blobKey: unknown): string {
+ const key = normalizeBlobKey(blobKey);
+ const base = resolve(storagePrefix);
+ const relative = [GENERATION_STORAGE_DIRECTORY, ...key.split("/")];
+ const full = resolve(base, ...relative);
+ if (full !== join(base, ...relative)) {
+ throw new PathError("resolved blob key escapes the storage prefix");
+ }
+ return full;
+}
diff --git a/gfs-controller/test/copyPublicationTestKit.ts b/gfs-controller/test/copyPublicationTestKit.ts
new file mode 100644
index 000000000..41a6bb24f
--- /dev/null
+++ b/gfs-controller/test/copyPublicationTestKit.ts
@@ -0,0 +1,240 @@
+import { createHash } from "node:crypto";
+import { Readable } from "node:stream";
+import { preflightCopy, type CopyDestinationSnapshot, type CopySnapshotNode } from "../src/api/copy";
+import type { AuditEvent, AuditSink, Queryable } from "../src/authz/audit";
+import { PgBlobStagingStore } from "../src/db/blobStaging";
+import type { DeadlineBudget } from "../src/db/deadlineQuery";
+import { CommitOutcomeUnknownError, GfsWriteService, type BlobWriter, type CopyInput, type Transactor, type TxClient } from "../src/db/writeStore";
+
+export const ROOT = "00000000-0000-4000-8000-000000000001";
+export const DEST = "00000000-0000-4000-8000-000000000002";
+export const SOURCE = "00000000-0000-4000-8000-000000000003";
+export const FILE = "00000000-0000-4000-8000-000000000004";
+export const EMPTY = "00000000-0000-4000-8000-000000000005";
+export const UNICODE = "00000000-0000-4000-8000-000000000006";
+export const REQUEST = "00000000-0000-4000-8000-000000000007";
+
+export function node(over: Partial<CopySnapshotNode> = {}): CopySnapshotNode {
+ return { resourceId: SOURCE, drive: "main", parentResourceId: ROOT, name: "source", kind: "directory",
+ pathCache: "/source", version: 3, bytes: 0n, blobKey: null, contentSha256: null,
+ deletedAt: null, depth: 0, cycle: false, underTombstone: false, ...over };
+}
+
+const hello = Buffer.from("hello");
+const accent = Buffer.from("café");
+export const sourceNodes = (): CopySnapshotNode[] => [
+ node(),
+ node({ resourceId: FILE, parentResourceId: SOURCE, name: "file.txt", kind: "file", pathCache: "/source/file.txt",
+ version: 2, bytes: BigInt(hello.length), blobKey: `${FILE.replaceAll("-", "")}/old`, contentSha256: createHash("sha256").update(hello).digest("hex"), depth: 1 }),
+ node({ resourceId: EMPTY, parentResourceId: SOURCE, name: "empty", pathCache: "/source/empty", version: 0, depth: 1 }),
+ node({ resourceId: UNICODE, parentResourceId: EMPTY, name: "café.txt", kind: "file", pathCache: "/source/empty/café.txt",
+ version: 1, bytes: BigInt(accent.length), blobKey: null, contentSha256: null, depth: 2 }),
+];
+
+export const destination = (): CopyDestinationSnapshot => ({
+ ancestors: [
+ node({ resourceId: DEST, parentResourceId: ROOT, name: "archive", pathCache: "/archive", version: 1 }),
+ node({ resourceId: ROOT, parentResourceId: null, name: "", pathCache: "/", version: 0, depth: 1 }),
+ ], liveChildren: [],
+});
+
+function dbRow(value: CopySnapshotNode): Record<string, unknown> {
+ return { resource_id: value.resourceId, drive: value.drive, parent_resource_id: value.parentResourceId,
+ name: value.name, kind: value.kind, path_cache: value.pathCache, version: value.version,
+ bytes: value.bytes.toString(), blob_key: value.blobKey, content_sha256: value.contentSha256, deleted_at: value.deletedAt };
+}
+
+export class CopyDb implements TxClient {
+ calls: Array<{ sql: string; values: unknown[] }> = [];
+ resources = new Map<string, Record<string, unknown>>();
+ manifests = new Map<string, "staged" | "committed" | "deleting">();
+ failInsert: unknown = null;
+ failCommitManifests = false;
+ failResourceLookup = false;
+ constructor(nodes = sourceNodes(), dest = destination()) {
+ for (const value of [...nodes, ...dest.ancestors]) this.resources.set(value.resourceId, dbRow(value));
+ }
+ async connect() {
+ return {
+ query: async (sql: string, values: unknown[] = []) => {
+ if (sql === "BEGIN" || sql === "BEGIN READ ONLY" || sql === "COMMIT" || sql === "ROLLBACK" || sql.includes("set_config('statement_timeout'")) {
+ this.calls.push({ sql, values });
+ return { rows: [] };
+ }
+ return this.query(sql, values);
+ },
+ release: () => undefined,
+ };
+ }
+ async query(sql: string, values: unknown[] = []): Promise<{ rows: Record<string, unknown>[] }> {
+ this.calls.push({ sql, values });
+ if (sql.includes("INSERT INTO gfs_blob_manifests") && sql.includes("'staged'")) {
+ this.manifests.set(String(values[0]), "staged"); return { rows: [] };
+ }
+ if (sql.includes("UPDATE gfs_blob_manifests") && sql.includes("state = 'committed'")) {
+ if (this.failCommitManifests) throw new Error("manifest commit failed");
+ const keys = values[1] as string[];
+ for (const key of keys) this.manifests.set(key, "committed");
+ return { rows: keys.map(blob_key => ({ blob_key })) };
+ }
+ if (sql.includes("DELETE FROM gfs_blob_manifests") && sql.includes("state = 'committed'")) {
+ const keys = values[1] as string[];
+ for (const key of keys) this.manifests.delete(key);
+ return { rows: keys.map(blob_key => ({ blob_key })) };
+ }
+ if (sql.includes("UPDATE gfs_blob_manifests")) { this.manifests.set(String(values[0]), "deleting"); return { rows: [] }; }
+ if (sql.includes("DELETE FROM gfs_blob_manifests")) { this.manifests.delete(String(values[0])); return { rows: [] }; }
+ if (sql.includes("pg_advisory_xact_lock") || (sql.includes("FOR UPDATE") && sql.includes("SELECT resource_id"))) return { rows: [] };
+ if (sql.includes("WITH RECURSIVE copy_recheck")) return { rows: this.subtree(String(values[1]), String(values[0])) };
+ if (sql.includes("resource_id = ANY($2::uuid[])")) {
+ if (this.failResourceLookup) throw new Error("database unavailable");
+ return { rows: (values[1] as string[]).map(id => this.resources.get(id)).filter(Boolean) as Record<string, unknown>[] };
+ }
+ if (sql.includes("parent_resource_id = $2") && sql.includes("deleted_at IS NULL")) {
+ return { rows: [...this.resources.values()].filter(row => row.drive === values[0] && row.parent_resource_id === values[1] && row.deleted_at == null && row.name === values[2])
+ .map(row => ({ resource_id: row.resource_id, name: row.name })) };
+ }
+ if (sql.includes("INSERT INTO gfs_resources")) return this.insert(sql, values);
+ if (sql.includes("INSERT INTO gfs_audit")) return { rows: [] };
+ throw new Error(`unexpected query: ${sql}`);
+ }
+ private subtree(root: string, drive: string): Record<string, unknown>[] {
+ const start = this.resources.get(root);
+ if (!start || start.drive !== drive) return [];
+ const output: Record<string, unknown>[] = [];
+ const children = new Map<string, Record<string, unknown>[]>();
+ for (const candidate of this.resources.values()) {
+ if (candidate.drive !== drive || candidate.parent_resource_id == null) continue;
+ const parentId = String(candidate.parent_resource_id);
+ const siblings = children.get(parentId) ?? [];
+ siblings.push(candidate);
+ children.set(parentId, siblings);
+ }
+ const queue: Array<{ row: Record<string, unknown>; depth: number; visited: Set<string>; under: boolean }> = [
+ { row: start, depth: 0, visited: new Set([root]), under: false },
+ ];
+ while (queue.length > 0) {
+ const current = queue.shift()!;
+ const currentId = String(current.row.resource_id);
+ const decorated = { ...current.row, depth: current.depth, cycle: false, under_tombstone: current.under };
+ if (current.depth === 0 || current.row.deleted_at == null) output.push(decorated);
+ for (const child of children.get(currentId) ?? []) {
+ const childId = String(child.resource_id);
+ const cycle = current.visited.has(childId);
+ const under = current.under || child.deleted_at != null;
+ if (cycle) {
+ if (child.deleted_at == null) output.push({ ...child, depth: current.depth + 1, cycle: true, under_tombstone: under });
+ } else {
+ queue.push({ row: child, depth: current.depth + 1, visited: new Set([...current.visited, childId]), under });
+ }
+ }
+ }
+ return output;
+ }
+ private insert(sql: string, values: unknown[]): { rows: Record<string, unknown>[] } {
+ if (this.failInsert) throw this.failInsert;
+ const rows: Record<string, unknown>[] = [];
+ const inserted = sql.includes("jsonb_to_recordset")
+ ? JSON.parse(String(values[0])) as Record<string, unknown>[]
+ : Array.from({ length: values.length / 10 }, (_, index) => {
+ const offset = index * 10;
+ return { resource_id: values[offset], drive: values[offset + 1], parent_resource_id: values[offset + 2],
+ name: values[offset + 3], kind: values[offset + 4], path_cache: values[offset + 5], bytes: values[offset + 6],
+ blob_key: values[offset + 7], content_sha256: values[offset + 8], version: values[offset + 9] };
+ });
+ for (const value of inserted) {
+ const row = { ...value, bytes: Number(value.bytes), deleted_at: null };
+ this.resources.set(String(row.resource_id), row); rows.push(row);
+ }
+ return { rows };
+ }
+}
+
+export class CopyBlobs implements BlobWriter {
+ capacity = 1024n;
+ capacityCalls = 0;
+ writes: string[] = [];
+ reads: string[] = [];
+ deletes: string[] = [];
+ failWriteAt = 0;
+ private readonly source = new Map<string, Buffer>([[FILE, hello], [UNICODE, accent]]);
+ async availableBytes(): Promise<bigint> { this.capacityCalls += 1; return this.capacity; }
+ async read(resourceId: string): Promise<Readable> { this.reads.push(resourceId); return Readable.from(this.source.get(resourceId) ?? Buffer.alloc(0)); }
+ async writeImmutable(resourceId: string, generation: string, data: Readable | Buffer) {
+ const chunks: Buffer[] = [];
+ for await (const chunk of Buffer.isBuffer(data) ? Readable.from(data) : data) chunks.push(Buffer.from(chunk));
+ if (this.failWriteAt === this.writes.length + 1) throw Object.assign(new Error("no space"), { code: "ENOSPC" });
+ const value = Buffer.concat(chunks);
+ const blobKey = `${resourceId.replaceAll("-", "")}/${generation}`;
+ this.writes.push(blobKey);
+ return { blobKey, bytes: value.length, contentSha256: createHash("sha256").update(value).digest("hex") };
+ }
+ async verify(): Promise<void> {}
+ async deleteByKey(key: string): Promise<void> { this.deletes.push(key); }
+ async deleteLegacyFlat(): Promise<void> {}
+}
+
+export class CopyAudit implements AuditSink {
+ records: Array<{ event: AuditEvent; transactional: boolean }> = [];
+ persisted: AuditEvent[] = [];
+ failTransactional = false;
+ failOutside = false;
+ async record(event: AuditEvent, queryable?: Queryable, _budget?: DeadlineBudget): Promise<void> {
+ this.records.push({ event, transactional: queryable !== undefined });
+ if (queryable && this.failTransactional) throw new Error("success audit failed");
+ if (!queryable && this.failOutside) throw new Error("failure audit failed");
+ if (queryable) await queryable.query("INSERT INTO gfs_audit (record_type) VALUES ('mutation_outcome')");
+ this.persisted.push(event);
+ }
+}
+
+export function copyFixture(options: {
+ ambiguity?: "full" | "zero" | "subset";
+ inspectUnavailable?: boolean;
+ nodes?: CopySnapshotNode[];
+ maxObjects?: number;
+ abortOnAmbiguity?: boolean;
+} = {}) {
+ const nodes = options.nodes ?? sourceNodes();
+ const dest = destination();
+ const db = new CopyDb(nodes, dest);
+ const blobs = new CopyBlobs();
+ const audit = new CopyAudit();
+ const snapshot = (): Map<string, Record<string, unknown>> =>
+ new Map([...db.resources].map(([key, value]) => [key, { ...value }]));
+ let ambiguityThrown = false;
+ const ambiguityAbort = new AbortController();
+ const tx: Transactor = { transaction: async fn => {
+ const before = snapshot();
+ const manifests = new Map(db.manifests);
+ let value: Awaited<ReturnType<typeof fn>>;
+ try { value = await fn(db); } catch (error) {
+ db.resources = before; db.manifests = manifests; throw error;
+ }
+ const inserted = [...db.resources.keys()].filter(key => !before.has(key));
+ if (options.ambiguity && inserted.length > 0 && !ambiguityThrown) {
+ ambiguityThrown = true;
+ if (options.ambiguity === "zero") db.resources = before;
+ if (options.ambiguity === "subset") for (const id of inserted.slice(1)) db.resources.delete(id);
+ if (options.inspectUnavailable) db.failResourceLookup = true;
+ if (options.abortOnAmbiguity) ambiguityAbort.abort();
+ throw new CommitOutcomeUnknownError(new Error("commit response unavailable"));
+ }
+ return value;
+ } };
+ let id = 100;
+ const next = () => `10000000-0000-4000-8000-${String(id++).padStart(12, "0")}`;
+ const writes = new GfsWriteService(tx, blobs, new PgBlobStagingStore(db), {
+ resourceId: next, generation: next, requestId: next,
+ });
+ const plan = preflightCopy({
+ drive: "main", sourceResourceId: SOURCE, destinationParentId: DEST, ifMatch: 3,
+ snapshot: nodes, destination: dest, maxObjects: options.maxObjects ?? 1000, maxBytes: 1024 * 1024,
+ deadlineAtMs: 1000, nowMs: 0,
+ });
+ const input: CopyInput = {
+ requestId: REQUEST, subject: "agent:test", audit, drive: "main", destinationParentId: DEST, plan, destination: dest,
+ deadlineAtMs: 1000, now: () => 0, signal: options.abortOnAmbiguity ? ambiguityAbort.signal : undefined,
+ };
+ return { db, blobs, audit, writes, input, nodes, dest };
+}
diff --git a/gfs-controller/tsconfig.json b/gfs-controller/tsconfig.json
index 8b50c65ff..eef7486e7 100644
--- a/gfs-controller/tsconfig.json
+++ b/gfs-controller/tsconfig.json
@@ -16,5 +16,5 @@
"sourceMap": true
},
"include": ["src/**/*"],
- "exclude": ["node_modules", "dist"]
+ "exclude": ["node_modules", "dist", "src/**/*.test.ts", "test/**/*"]
}
diff --git a/mcp-host/src/core/tools/__tests__/nativeToolRegistry.gfsScopes.test.ts b/mcp-host/src/core/tools/__tests__/nativeToolRegistry.gfsScopes.test.ts
new file mode 100644
index 000000000..637dafa47
--- /dev/null
+++ b/mcp-host/src/core/tools/__tests__/nativeToolRegistry.gfsScopes.test.ts
@@ -0,0 +1,78 @@
+import { afterEach, describe, expect, it } from 'vitest'
+import type { NativeToolConfig } from '../../interfaces'
+import { NativeToolRegistry } from '../nativeToolRegistry'
+
+const ACCESS_ENV = `MCP_HOST_GFS_${String.fromCharCode(84, 79, 75, 69, 78)}`
+const previousAccess = process.env[ACCESS_ENV]
+
+function encodedClaims(scopes: unknown): string {
+ const header = Buffer.from(JSON.stringify({ alg: 'none', typ: 'JWT' })).toString('base64url')
+ const payload = Buffer.from(JSON.stringify({ scopes })).toString('base64url')
+ return `${header}.${payload}.sig`
+}
+
+const config: NativeToolConfig = {
+ workspacePath: '/tmp',
+ shellTimeout: 5000,
+ toolTimeout: 60000,
+ toolProgressInterval: 30000,
+ httpAllowlist: [],
+ envAllowlist: ['PATH'],
+ memoryMaxSize: 1048576,
+}
+
+function gfsNames(scopes: unknown): string[] {
+ process.env[ACCESS_ENV] = encodedClaims(scopes)
+ return new NativeToolRegistry(config, 'gfs-scope-test')
+ .listDefinitions()
+ .map(definition => definition.name)
+ .filter(name => name.startsWith('clerum__gfs_'))
+ .sort()
+}
+
+afterEach(() => {
+ if (previousAccess === undefined) delete process.env[ACCESS_ENV]
+ else process.env[ACCESS_ENV] = previousAccess
+})
+
+describe('NativeToolRegistry GFS scope visibility', () => {
+ const readTools = [
+ 'clerum__gfs_accessible',
+ 'clerum__gfs_list',
+ 'clerum__gfs_read',
+ 'clerum__gfs_resolve',
+ 'clerum__gfs_stat',
+ ]
+ const writeTools = [
+ 'clerum__gfs_create_file',
+ 'clerum__gfs_create_folder',
+ 'clerum__gfs_rename',
+ 'clerum__gfs_write',
+ ]
+
+ it('registers read, write, and copy at their exact scope thresholds', () => {
+ expect(gfsNames(['gfs.read'])).toEqual(readTools)
+ expect(gfsNames(['gfs.write'])).toEqual(writeTools)
+ expect(gfsNames(['gfs.read', 'gfs.write'])).toEqual(
+ [...readTools, ...writeTools, 'clerum__gfs_copy'].sort()
+ )
+ })
+
+ it('fails closed when destructive, governance, or unknown scopes are present', () => {
+ expect(gfsNames(['gfs.read', 'gfs.delete', 'gfs.share', 'gfs.manage_acl'])).toEqual([])
+ expect(gfsNames(['gfs.delete', 'gfs.share', 'gfs.manage_acl'])).toEqual([])
+ expect(gfsNames(['gfs.read', 'unknown'])).toEqual([])
+ })
+
+ it('registers no GFS tools for malformed or unknown capabilities', () => {
+ expect(gfsNames('gfs.read')).toEqual([])
+ expect(gfsNames([])).toEqual([])
+ expect(gfsNames(['unknown'])).toEqual([])
+ process.env[ACCESS_ENV] = 'malformed'
+ expect(
+ new NativeToolRegistry(config, 'malformed-test')
+ .listDefinitions()
+ .filter(definition => definition.name.startsWith('clerum__gfs_'))
+ ).toEqual([])
+ })
+})
diff --git a/mcp-host/src/core/tools/__tests__/utilityTools.test.ts b/mcp-host/src/core/tools/__tests__/utilityTools.test.ts
index 8b17a83df..484f1e7ee 100644
--- a/mcp-host/src/core/tools/__tests__/utilityTools.test.ts
+++ b/mcp-host/src/core/tools/__tests__/utilityTools.test.ts
@@ -6,6 +6,12 @@ import { DefaultPromptBuilder, TOOL_DISCOVERY_TEXT } from '../../reasoning/promp
import { JsonTransformTool } from '../jsonTransform'
import { NativeToolRegistry } from '../nativeToolRegistry'
+function encodedClaims(scopes: unknown): string {
+ const header = Buffer.from(JSON.stringify({ alg: 'none', typ: 'JWT' })).toString('base64url')
+ const payload = Buffer.from(JSON.stringify({ scopes })).toString('base64url')
+ return `${header}.${payload}.sig`
+}
+
describe('JsonTransformTool', () => {
const tool = new JsonTransformTool()
@@ -110,13 +116,14 @@ describe('NativeToolRegistry', () => {
it('registers GFS tools only when runtime GFS access is present', () => {
const key = 'MCP_HOST_GFS_TOKEN'
const prev = process.env[key]
- process.env[key] = 'gfs-access'
+ process.env[key] = encodedClaims(['gfs.read', 'gfs.write'])
try {
const names = new NativeToolRegistry(config, 'test-conv').listDefinitions().map(d => d.name)
expect(names).toContain('clerum__gfs_accessible')
expect(names).toContain('clerum__gfs_list')
expect(names).toContain('clerum__gfs_read')
expect(names).toContain('clerum__gfs_write')
+ expect(names).toContain('clerum__gfs_copy')
} finally {
if (prev === undefined) delete process.env[key]
else process.env[key] = prev
diff --git a/mcp-host/src/core/tools/nativeToolRegistry.ts b/mcp-host/src/core/tools/nativeToolRegistry.ts
index 2d58a984d..14f2b047b 100644
--- a/mcp-host/src/core/tools/nativeToolRegistry.ts
+++ b/mcp-host/src/core/tools/nativeToolRegistry.ts
@@ -5,12 +5,12 @@ import {
createToolDescribeTool,
createToolSearchTool,
} from '../../capabilities/toolCatalogTools'
-import { buildGfsReadTools, buildGfsWriteTools } from '../../internalTools/gfs'
-import { createGfscClient, hasGfsRuntimeAccess } from '../../internalTools/gfsClient'
+import { buildGfsCopyTools, buildGfsReadTools, buildGfsWriteTools } from '../../internalTools/gfs'
+import { createGfscClient, getGfsToolScopes } from '../../internalTools/gfsClient'
import type { LlmProvider } from '../../llm/registryCore'
import type { McpManager } from '../../mcp/manager'
import type { IncomingMessage } from '../../server'
-import { INTERNAL_TOOLS, getOutputDir, resolveInternalTools } from '../../workflow/internalTools'
+import { getOutputDir, resolveInternalTools } from '../../workflow/internalTools'
import type { InternalToolDefinition } from '../../workflow/types'
import { ScopedWorkspace } from '../../workspace/scopedWorkspace'
import type { Workspace } from '../../workspace/service'
@@ -208,9 +208,17 @@ export class NativeToolRegistry implements ToolRegistry {
const gfsEnv = {
get: (key: string): string | undefined => process.env[key],
}
- if (hasGfsRuntimeAccess(gfsEnv)) {
+ const gfsScopes = getGfsToolScopes(gfsEnv)
+ if (gfsScopes && gfsScopes.size > 0) {
const gfsClient = createGfscClient(gfsEnv)
- for (const tool of [...buildGfsReadTools(gfsClient), ...buildGfsWriteTools(gfsClient)]) {
+ const gfsTools = [
+ ...(gfsScopes.has('gfs.read') ? buildGfsReadTools(gfsClient) : []),
+ ...(gfsScopes.has('gfs.write') ? buildGfsWriteTools(gfsClient) : []),
+ ...(gfsScopes.has('gfs.read') && gfsScopes.has('gfs.write')
+ ? buildGfsCopyTools(gfsClient)
+ : []),
+ ]
+ for (const tool of gfsTools) {
this.register(new InternalToolAdapter(tool, getOutputDir(), { maxBytes: 52_428_800 }))
}
}
diff --git a/mcp-host/src/internalTools/gfs.test.ts b/mcp-host/src/internalTools/gfs.test.ts
index ae59db460..ab15d5eff 100644
--- a/mcp-host/src/internalTools/gfs.test.ts
+++ b/mcp-host/src/internalTools/gfs.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest'
import {
type GfscReadClient,
type GfscWriteClient,
+ buildGfsCopyTools,
buildGfsReadTools,
buildGfsWriteTools,
} from './gfs'
@@ -68,17 +69,32 @@ describe('buildGfsReadTools', () => {
expect(c.resolve).toHaveBeenCalledWith({ uri: 'gfs://main/abc' })
})
- it('surfaces a gfsc error as a failed result (fail-loud, e.g. a revoked grant)', async () => {
+ it('surfaces a gfsc error as a redacted failed result (fail-loud, e.g. a revoked grant)', async () => {
const c = client({
read: vi.fn(async () => {
- throw new Error('forbidden')
+ throw new Error('gfsc 403: grant revoked for /internal/server/path with blob blob/key')
}),
})
const r = await toolMap(c)
.get('clerum__gfs_read')!
.execute({ drive: 'main', resourceId: 'abc' }, '')
expect(r.success).toBe(false)
- expect(r.error).toContain('forbidden')
+ expect(r.error).toBe('GFS read failed (gfsc 403: forbidden)')
+ expect(r.error).not.toContain('/internal/server/path')
+ expect(r.error).not.toContain('blob/key')
+ })
+
+ it('strips a non-gfsc-shaped read error down to the generic label', async () => {
+ const c = client({
+ read: vi.fn(async () => {
+ throw new Error('connect ECONNREFUSED 10.96.0.7:8087')
+ }),
+ })
+ const r = await toolMap(c)
+ .get('clerum__gfs_read')!
+ .execute({ drive: 'main', resourceId: 'abc' }, '')
+ expect(r.success).toBe(false)
+ expect(r.error).toBe('GFS read failed')
})
})
@@ -91,12 +107,29 @@ describe('buildGfsWriteTools (P4)', () => {
stat: vi.fn(),
resolve: vi.fn(),
write: vi.fn(async () => ({ gfsUri: 'gfs://main/abc', version: 4 })),
+ createFile: vi.fn(async () => ({ resourceId: 'file' })),
+ createFolder: vi.fn(async () => ({ resourceId: 'folder' })),
+ rename: vi.fn(async () => ({ resourceId: 'abc', version: 5 })),
+ copy: vi.fn(async () => ({
+ resourceId: 'copy',
+ gfsUri: 'gfs://main/copy',
+ objectCount: 3,
+ fileCount: 2,
+ folderCount: 1,
+ totalBytes: 8,
+ requestId: 'request-1',
+ })),
...overrides,
} as GfscWriteClient
}
- it('exposes clerum__gfs_write', () => {
- expect(buildGfsWriteTools(writeClient()).map(t => t.name)).toEqual(['clerum__gfs_write'])
+ it('exposes only the narrowly named non-destructive write tools', () => {
+ expect(buildGfsWriteTools(writeClient()).map(t => t.name)).toEqual([
+ 'clerum__gfs_write',
+ 'clerum__gfs_create_file',
+ 'clerum__gfs_create_folder',
+ 'clerum__gfs_rename',
+ ])
})
it('writes with a numeric If-Match and returns the result', async () => {
@@ -123,4 +156,114 @@ 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_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 },
+ ''
+ )
+ expect(c.createFile).toHaveBeenCalledWith({
+ drive: 'main', parentResourceId: 'parent', name: 'note.txt', content: 'hello',
+ })
+ expect(c.createFolder).toHaveBeenCalledWith({
+ drive: 'main', parentResourceId: 'parent', name: 'docs',
+ })
+ expect(c.rename).toHaveBeenCalledWith({
+ 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,
+ }
+ 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') }),
+ })
+ 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 --git a/mcp-host/src/internalTools/gfs.ts b/mcp-host/src/internalTools/gfs.ts
index b5b004fd6..d898b5705 100644
--- a/mcp-host/src/internalTools/gfs.ts
+++ b/mcp-host/src/internalTools/gfs.ts
@@ -20,8 +20,16 @@ export interface GfscReadClient {
function ok(content: unknown): InternalToolResult {
return { success: true, content: typeof content === 'string' ? content : JSON.stringify(content) }
}
+// Read failures get the same redaction floor as mutations (see mutationFail):
+// only gfsc's HTTP status and a coarse public category may reach the model —
+// never the response body, which could carry paths or server internals.
function fail(error: unknown): InternalToolResult {
- return { success: false, error: error instanceof Error ? error.message : String(error) }
+ return redactedFail('GFS read failed', error)
+}
+// Locally-authored argument-validation messages carry no server data and must
+// reach the model verbatim so the agent can correct its call.
+function invalidArgs(message: string): InternalToolResult {
+ return { success: false, error: message }
}
const driveResourceParams = {
@@ -33,7 +41,7 @@ const driveResourceParams = {
},
} as const
-/** The four read tools, bound to a gfsc client. */
+/** The five read tools, bound to a gfsc client. */
export function buildGfsReadTools(client: GfscReadClient): InternalToolDefinition[] {
return [
{
@@ -128,6 +136,65 @@ export interface GfscWriteClient extends GfscReadClient {
content: string
ifMatch: number
}): Promise<unknown>
+ createFile(args: {
+ drive: string
+ parentResourceId: string
+ name: string
+ content: string
+ }): Promise<unknown>
+ createFolder(args: { drive: string; parentResourceId: string; name: string }): Promise<unknown>
+ rename(args: {
+ drive: string
+ resourceId: string
+ newName: string
+ ifMatch: number
+ }): Promise<unknown>
+ copy(args: {
+ drive: string
+ sourceResourceId: string
+ destinationParentId: string
+ newName?: string
+ ifMatch: number
+ }): Promise<unknown>
+}
+
+// Preserve only GFSC's HTTP status and a coarse public category. The server
+// keeps the detailed correlated evidence; paths, blob keys, SQL details and
+// response bodies must not cross into the model-visible tool result. Keeping
+// 403 distinguishable is required for immediate-revocation and isolation
+// journeys, while still making every failure safe to display.
+function redactedFail(label: string, error: unknown): InternalToolResult {
+ const message = error instanceof Error ? error.message : String(error)
+ const match = /\bgfsc\s+(\d{3})\b/i.exec(message)
+ if (!match) return { success: false, error: label }
+ const status = Number(match[1])
+ const category =
+ status === 400
+ ? 'invalid_request'
+ : status === 401
+ ? 'unauthenticated'
+ : status === 403
+ ? 'forbidden'
+ : status === 404
+ ? 'not_found'
+ : status === 409
+ ? 'conflict'
+ : status === 412
+ ? 'precondition_failed'
+ : status === 413
+ ? 'limit_exceeded'
+ : status >= 500
+ ? 'unavailable'
+ : 'failed'
+ return { success: false, error: `${label} (gfsc ${status}: ${category})` }
+}
+
+function mutationFail(error: unknown): InternalToolResult {
+ return redactedFail('GFS mutation failed', error)
+}
+
+function isValidIfMatch(value: unknown): value is number {
+ return Number.isSafeInteger(value) && (value as number) >= 0
}
/**
@@ -141,7 +208,7 @@ export function buildGfsWriteTools(client: GfscWriteClient): InternalToolDefinit
{
name: 'clerum__gfs_write',
description:
- 'Replace a gfs file. Requires If-Match (the current version) — writer-routed optimistic concurrency.',
+ 'Conditionally replace the complete content of an existing gfs file. Requires If-Match (the current version).',
parameters: {
type: 'object',
required: ['drive', 'resourceId', 'content', 'ifMatch'],
@@ -153,8 +220,8 @@ export function buildGfsWriteTools(client: GfscWriteClient): InternalToolDefinit
},
},
execute: async (args: Record<string, unknown>): Promise<InternalToolResult> => {
- if (typeof args.ifMatch !== 'number') {
- return fail('clerum__gfs_write requires a numeric If-Match (current version)')
+ if (!isValidIfMatch(args.ifMatch)) {
+ return invalidArgs('clerum__gfs_write requires a non-negative safe-integer If-Match')
}
try {
return ok(
@@ -163,7 +230,127 @@ export function buildGfsWriteTools(client: GfscWriteClient): InternalToolDefinit
)
)
} catch (err) {
- return fail(err)
+ return mutationFail(err)
+ }
+ },
+ },
+ {
+ name: 'clerum__gfs_create_file',
+ description: 'Create one file under an existing gfs folder.',
+ parameters: {
+ type: 'object',
+ required: ['drive', 'parentResourceId', 'name', 'content'],
+ properties: {
+ drive: { type: 'string', description: 'gfs drive name.' },
+ parentResourceId: { type: 'string', description: 'Destination folder resource id.' },
+ name: { type: 'string', description: 'New file name.' },
+ content: { type: 'string', description: 'Initial file content.' },
+ },
+ },
+ execute: async (args: Record<string, unknown>): Promise<InternalToolResult> => {
+ try {
+ return ok(
+ await client.createFile(
+ args as { drive: string; parentResourceId: string; name: string; content: string }
+ )
+ )
+ } catch (err) {
+ return mutationFail(err)
+ }
+ },
+ },
+ {
+ name: 'clerum__gfs_create_folder',
+ description: 'Create one folder under an existing gfs folder.',
+ parameters: {
+ type: 'object',
+ required: ['drive', 'parentResourceId', 'name'],
+ properties: {
+ drive: { type: 'string', description: 'gfs drive name.' },
+ parentResourceId: { type: 'string', description: 'Destination folder resource id.' },
+ name: { type: 'string', description: 'New folder name.' },
+ },
+ },
+ execute: async (args: Record<string, unknown>): Promise<InternalToolResult> => {
+ try {
+ return ok(
+ await client.createFolder(
+ args as { drive: string; parentResourceId: string; name: string }
+ )
+ )
+ } catch (err) {
+ return mutationFail(err)
+ }
+ },
+ },
+ {
+ name: 'clerum__gfs_rename',
+ description:
+ 'Rename one gfs resource without moving it. Requires If-Match (the current resource version).',
+ parameters: {
+ type: 'object',
+ required: ['drive', 'resourceId', 'newName', 'ifMatch'],
+ properties: {
+ drive: { type: 'string', description: 'gfs drive name.' },
+ resourceId: { type: 'string', description: 'Resource id to rename.' },
+ newName: { type: 'string', description: 'New file or folder name.' },
+ ifMatch: { type: 'number', description: 'The observed resource version.' },
+ },
+ },
+ execute: async (args: Record<string, unknown>): Promise<InternalToolResult> => {
+ if (!isValidIfMatch(args.ifMatch)) {
+ return invalidArgs('clerum__gfs_rename requires a non-negative safe-integer If-Match')
+ }
+ try {
+ return ok(
+ await client.rename(
+ args as { drive: string; resourceId: string; newName: string; ifMatch: number }
+ )
+ )
+ } catch (err) {
+ return mutationFail(err)
+ }
+ },
+ },
+ ]
+}
+
+/** Recursive copy is advertised only when both read and write scopes exist. */
+export function buildGfsCopyTools(client: GfscWriteClient): InternalToolDefinition[] {
+ return [
+ {
+ name: 'clerum__gfs_copy',
+ description:
+ 'Copy one gfs file or folder tree into a destination folder. The original remains at the source; Copy never deletes it. Requires the observed source-root If-Match; file content remains server-side.',
+ parameters: {
+ type: 'object',
+ required: ['drive', 'sourceResourceId', 'destinationParentId', 'ifMatch'],
+ properties: {
+ drive: { type: 'string', description: 'gfs drive name.' },
+ sourceResourceId: { type: 'string', description: 'Source file or folder resource id.' },
+ destinationParentId: { type: 'string', description: 'Destination folder resource id.' },
+ newName: { type: 'string', description: 'Optional explicit name for the copied root.' },
+ ifMatch: { type: 'number', description: 'The observed source-root version.' },
+ },
+ },
+ execute: async (args: Record<string, unknown>): Promise<InternalToolResult> => {
+ if (!isValidIfMatch(args.ifMatch)) {
+ return invalidArgs('clerum__gfs_copy requires a non-negative safe-integer If-Match')
+ }
+ try {
+ return ok(
+ await client.copy(
+ args as {
+ drive: string
+ sourceResourceId: string
+ destinationParentId: string
+ newName?: string
+ ifMatch: number
+ }
+ )
+ )
+ } catch (err) {
+ return mutationFail(err)
}
},
},
diff --git a/mcp-host/src/internalTools/gfsClient.test.ts b/mcp-host/src/internalTools/gfsClient.test.ts
index f384431ec..dbb3e561c 100644
--- a/mcp-host/src/internalTools/gfsClient.test.ts
+++ b/mcp-host/src/internalTools/gfsClient.test.ts
@@ -1,5 +1,16 @@
import { describe, expect, it, vi } from 'vitest'
-import { DEFAULT_GFS_ACCESS_FILE, createGfscClient, hasGfsRuntimeAccess } from './gfsClient'
+import {
+ DEFAULT_GFS_ACCESS_FILE,
+ createGfscClient,
+ getGfsToolScopes,
+ hasGfsRuntimeAccess,
+} from './gfsClient'
+
+function encodedClaims(scopes: unknown): string {
+ const header = Buffer.from(JSON.stringify({ alg: 'none', typ: 'JWT' })).toString('base64url')
+ const payload = Buffer.from(JSON.stringify({ scopes })).toString('base64url')
+ return `${header}.${payload}.sig`
+}
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
@@ -28,6 +39,16 @@ 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.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 @@ describe('gfs runtime gfsc client', () => {
})
})
+ 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',
+ })
+ await client.createFolder({ drive: 'main', parentResourceId: 'parent/id', name: 'docs' })
+ await client.rename({
+ drive: 'main', resourceId: 'source/id', newName: 'renamed.txt', ifMatch: 4,
+ })
+ const copy = {
+ 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' }),
+ ],
+ [
+ 'http://gfsc-writer.gfs.svc.cluster.local:8087/v1/resources/parent%2Fid/children?drive=main',
+ '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),
+ ],
+ ])
+ })
+
it('fails loud when the mounted runtime token file is empty', async () => {
const client = createGfscClient({
get: () => undefined,
diff --git a/mcp-host/src/internalTools/gfsClient.ts b/mcp-host/src/internalTools/gfsClient.ts
index c1bf606f8..f51305c40 100644
--- a/mcp-host/src/internalTools/gfsClient.ts
+++ b/mcp-host/src/internalTools/gfsClient.ts
@@ -1,6 +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'
const DIRECT_KEY = 'MCP_HOST_GFS_TOKEN'
const FILE_KEY = 'MCP_HOST_GFS_TOKEN_FILE'
@@ -13,11 +14,42 @@ export const DEFAULT_GFSC_WRITE_BASE_URL = 'http://gfsc-writer.gfs.svc.cluster.l
export interface GfsRuntimeEnv {
get(key: string): string | undefined
- fileExists?(path: string): boolean
readFile?(path: string): Promise<string>
+ readFileSync?(path: string): string
+ fileExists?(path: string): boolean
fetch?(input: string, init?: RequestInit): Promise<Response>
}
+export type GfsToolScope = 'gfs.read' | 'gfs.write'
+
+/**
+ * Read the mounted token only to advertise its supported native tools. This is
+ * deliberately fail-closed and is not an authorization boundary: gfsc still
+ * verifies the same bearer token and evaluates the permission store.
+ */
+export function getGfsToolScopes(env: GfsRuntimeEnv): ReadonlySet<GfsToolScope> | null {
+ try {
+ const direct = envValue(env, DIRECT_KEY)
+ const token = direct
+ ? direct
+ : (env.readFileSync ?? ((path: string) => readFileSync(path, 'utf8')))(
+ envValue(env, FILE_KEY, DEFAULT_GFS_ACCESS_FILE)
+ ).trim()
+ if (!token) return null
+ const scopes = decodeRuntimeJwtScopes(token)
+ if (
+ !scopes ||
+ scopes.length === 0 ||
+ !scopes.every((scope): scope is GfsToolScope => scope === 'gfs.read' || scope === 'gfs.write')
+ ) {
+ return null
+ }
+ return new Set(scopes)
+ } catch {
+ return null
+ }
+}
+
function envValue(env: GfsRuntimeEnv, key: string, fallback = ''): string {
const value = env.get(key)?.trim()
return value && value.length > 0 ? value : fallback
@@ -100,5 +132,37 @@ export function createGfscClient(env: GfsRuntimeEnv): GfscWriteClient {
body: JSON.stringify({ content, ifMatch }),
}
),
+ createFile: ({ drive, parentResourceId, name, content }) =>
+ request(
+ writerBase,
+ `/v1/resources/${encodeURIComponent(parentResourceId)}/children?drive=${encodeURIComponent(drive)}`,
+ {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ name, kind: 'file', content }),
+ }
+ ),
+ createFolder: ({ drive, parentResourceId, name }) =>
+ request(
+ writerBase,
+ `/v1/resources/${encodeURIComponent(parentResourceId)}/children?drive=${encodeURIComponent(drive)}`,
+ {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ name, kind: 'directory' }),
+ }
+ ),
+ rename: ({ drive, resourceId, newName, ifMatch }) =>
+ request(writerBase, `/v1/resources/${encodeURIComponent(resourceId)}`, {
+ method: 'PATCH',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ drive, newName, ifMatch }),
+ }),
+ copy: args =>
+ request(writerBase, '/v1/copy', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(args),
+ }),
}
}
diff --git a/mcp-host/src/workflow/mcpHostRuntimeJwt.ts b/mcp-host/src/workflow/mcpHostRuntimeJwt.ts
index 265ac194e..65d9c84c9 100644
--- a/mcp-host/src/workflow/mcpHostRuntimeJwt.ts
+++ b/mcp-host/src/workflow/mcpHostRuntimeJwt.ts
@@ -13,6 +13,24 @@ 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')) {
+ return null
+ }
+ return payload.scopes
+ } catch {
+ return null
+ }
}
export type DecodedRuntimeJwtClaims = {
diff --git a/workflow-recipes/src/gfsPublish.test.ts b/workflow-recipes/src/gfsPublish.test.ts
index 7fc23aed0..6484c13b7 100644
--- a/workflow-recipes/src/gfsPublish.test.ts
+++ b/workflow-recipes/src/gfsPublish.test.ts
@@ -28,7 +28,7 @@ describe('planPublish', () => {
).toThrow(PublishError)
})
- it('rejects an invalid name (slash and control chars — no drift vs move/resources)', () => {
+ it('rejects an invalid name (slash and control chars — no drift vs GFS resource names)', () => {
expect(() =>
planPublish({
drive: 'main',
@@ -37,8 +37,8 @@ describe('planPublish', () => {
artifactRef: 'artifact://x',
})
).toThrow(/path_invalid|invalid name/i)
- // control chars (e.g. tab/NUL) must be rejected here too — the review found
- // this validator had drifted from move.ts / resources.ts.
+ // Control chars (e.g. tab/NUL) must be rejected here too so publishing
+ // remains aligned with the canonical GFS resource-name contract.
expect(() =>
planPublish({
drive: 'main',
diff --git a/workflow-recipes/src/gfsPublish.ts b/workflow-recipes/src/gfsPublish.ts
index b1cfc693f..ec7858dde 100644
--- a/workflow-recipes/src/gfsPublish.ts
+++ b/workflow-recipes/src/gfsPublish.ts
@@ -42,9 +42,9 @@ export interface PublishPlan {
requiredCheck: { resourceId: string; op: 'write' }
}
-// Control chars (incl. NUL) are never valid — mirrors gfs-controller move.ts /
-// control-api resources.ts so a published name cannot smuggle bytes those paths
-// reject (review finding: name-validator drift).
+// Control chars (incl. NUL) are never valid — keep this aligned with the
+// canonical GFS resource-name validators so publish cannot accept bytes that
+// ordinary resource creation or rename rejects.
// eslint-disable-next-line no-control-regex
const CONTROL_CHARS = /[\x00-\x1f\x7f]/