feat: import prepared Catalog bindings through authenticated services

This commit is contained in:
Codex
2026-10-06 18:04:07 +02:00
parent d720da721b
commit af4c7b5df9
29 changed files with 835 additions and 35 deletions
+4
View File
@@ -48,6 +48,8 @@ import { createCatalogRepository } from "./catalog/repository.js";
import type { CatalogRepository } from "./catalog/types.js";
import { CatalogService } from "./catalog/service.js";
import { catalogDatabaseRoutes } from "./routes/catalog-databases.js";
import { installationRoutes } from "./routes/installation.js";
import { InstallationBindings } from "./catalog/installation-bindings.js";
import { CatalogOperationCoordinator } from "./catalog/operation-coordinator.js";
import { ConcreteCatalogPostgresAccess, type CatalogPostgresAccess } from "./catalog/postgres-access.js";
import { CatalogTableService } from "./catalog/table-service.js";
@@ -530,6 +532,8 @@ export function buildApp(config: AppConfig, deps?: BuildAppDeps): FastifyInstanc
}).readLatestJob(),
});
catalogDatabaseRoutes(app, { repository: catalogRepository, service: catalogService, operations: catalogOperationCoordinator });
installationRoutes(app, new InstallationBindings(catalogRepository, catalogService, workspaceRegistry,
workspaceSecretStore, catalogOperationCoordinator, config.workspaceRegistry.installationId), workspaceRegistry);
catalogTableRoutes(app, {
repository: catalogRepository,
service: catalogTableService,
+4 -1
View File
@@ -11,7 +11,9 @@ const database = databaseConfigurationSchema.extend({
secretFiles: z.object({ password: reference.optional(), apiKey: reference.optional(), sshPrivateKey: reference.optional(), sshPrivateKeyPassphrase: reference.optional(), sshKnownHosts: reference.optional(), tlsCa: reference.optional() }).strict(),
evidenceSecretFiles: z.object({ "evidence.signed_urls": reference.optional(), "evidence.access_key": reference.optional(), "evidence.secret_key": reference.optional(), "evidence.session_token": reference.optional() }).strict().optional(),
});
const bootstrap = z.object({ schemaVersion: z.literal(1), databases: z.array(database).min(1).max(1000) }).strict();
const bootstrap = z.object({ schemaVersion: z.literal(1),
authentication: z.object({ username: z.string().min(1).max(128), passwordFile: reference }).strict().optional(),
databases: z.array(database).min(1).max(1000) }).strict();
export const parseDatabaseBootstrap = (value: unknown) => bootstrap.parse(value);
@@ -24,6 +26,7 @@ export function validateDatabaseBootstrap(value: unknown, workspaceRoot: string)
const expected = new Set(catalog.workspaces.map((entry) => entry.id));
const seen = new Set<string>();
const secretFiles: BootstrapReference[] = [];
if (document.authentication) secretFiles.push({ field: "authentication.passwordFile", path: document.authentication.passwordFile });
const warnings: string[] = [];
const issue = (path: (string | number)[], message: string): never => { throw new z.ZodError([{ code: "custom", path, message }]); };
document.databases.forEach((entry, index) => {
@@ -0,0 +1,77 @@
import { createHash } from "node:crypto";
import { isDeepStrictEqual } from "node:util";
import { z } from "zod";
import { databaseConfigurationSchema } from "./configuration-schema.js";
import { CATALOG_SECRET_IDS } from "./secrets.js";
import type { CatalogRepository } from "./types.js";
import type { CatalogService } from "./service.js";
import type { CatalogOperationCoordinator } from "./operation-coordinator.js";
import type { WorkspaceRegistry } from "../workspaces/registry.js";
import type { WorkspaceSecretStore } from "../workspaces/secret-store.js";
import { discoverWorkspaceSecretRequirements } from "../workspaces/secret-requirements.js";
const secret = z.string().min(1).refine(value => Buffer.byteLength(value, "utf8") <= 65536);
export const installationBindingSchema = z.object({
schemaVersion: z.literal(1), revision: z.string().regex(/^[a-f0-9]{40}$/),
configuration: databaseConfigurationSchema,
secrets: z.object({ password: secret.optional(), apiKey: secret.optional(), sshPrivateKey: secret.optional(),
sshPrivateKeyPassphrase: secret.optional(), sshKnownHosts: secret.optional(), tlsCa: secret.optional() }).strict(),
evidenceSecrets: z.object({ "evidence.signed_urls": secret.optional(), "evidence.access_key": secret.optional(),
"evidence.secret_key": secret.optional(), "evidence.session_token": secret.optional() }).strict(),
}).strict();
export class InstallationReconciliationRequired extends Error {}
const conflict = () => { throw new InstallationReconciliationRequired("Reconcile the prepared documents with current administrative state."); };
/** Only called behind the ordinary authenticated administration permission boundary. */
export class InstallationBindings {
constructor(private readonly repository: CatalogRepository, private readonly catalog: CatalogService,
private readonly registry: WorkspaceRegistry, private readonly secrets: WorkspaceSecretStore,
private readonly operations: CatalogOperationCoordinator, private readonly installationId: string) {}
async apply(raw: unknown) {
const request = installationBindingSchema.parse(raw);
const workspaceId = request.configuration.workspaceId;
const { workspace, revision } = await this.registry.read(workspaceId);
if (revision.commit !== request.revision) return conflict();
const input = await this.catalog.normalizeInput(request.configuration);
const required = input.binding.transport === "rest_api" ? (input.binding.restAuth === "none" ? [] : ["apiKey"])
: input.binding.transport === "ssh_tunnel" ? ["password", "sshPrivateKey", "sshKnownHosts"] : ["password"];
if (required.some(name => !request.secrets[name as keyof typeof request.secrets])) return conflict();
const evidenceRequirements = discoverWorkspaceSecretRequirements(workspace, {}).filter(item => item.connector === "evidence" && item.required);
if (evidenceRequirements.some(item => !(request.evidenceSecrets as Record<string, string>)[item.id])) return conflict();
const values: Record<string, string> = { ...request.evidenceSecrets };
for (const [name, value] of Object.entries(request.secrets)) values[CATALOG_SECRET_IDS[name as keyof typeof CATALOG_SECRET_IDS]] = value;
// Stable installation-local identity is persisted atomically with the initial binding.
// A crash before any host journal update is recoverable without adopting a manually created row.
const hex = createHash("sha256").update(`thothii-installation-binding-v1\0${this.installationId}\0${workspaceId}`).digest("hex");
const id = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-5${hex.slice(13, 16)}-a${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
const applied = await this.operations.run(id, async () => {
let current = await this.repository.getByWorkspace(workspaceId);
let changed = false;
if (!current) { current = await this.repository.create(input, id); changed = true; }
if (current.id !== id || !isDeepStrictEqual(input, {
workspaceId: current.workspaceId, engine: current.engine, databaseName: current.databaseName,
schema: current.schema, binding: Object.fromEntries(Object.entries(current.binding).filter(([, value]) => value !== undefined)),
})) return conflict();
const configured = this.secrets.configured(workspaceId).filter(name => name.startsWith("catalog.") || name.startsWith("evidence."));
if (configured.some(name => values[name] === undefined || !this.secrets.matches(workspaceId, name, values[name]))) return conflict();
const missing = Object.fromEntries(Object.entries(values).filter(([name]) => !configured.includes(name)));
if (Object.keys(missing).length) {
if (current.version !== 1) return conflict();
// Synchronous atomic vault update cannot interleave with another mutation in this core.
this.secrets.putMany(workspaceId, missing); changed = true;
}
if (current.version === 1) {
const touched = await this.repository.touch(id, current.version);
if (!touched) return conflict();
current = touched; changed = true;
}
return { current, changed };
});
const tested = await this.catalog.test(applied.current);
if (!tested || tested.version !== applied.current.version || (await this.registry.read(workspaceId)).revision.commit !== request.revision) return conflict();
return { schemaVersion: 1, workspaceId, databaseId: tested.id, version: tested.version,
status: applied.changed ? "applied" : "unchanged", connectionStatus: tested.connectionStatus };
}
}
+5 -3
View File
@@ -52,6 +52,7 @@ function clone(value: WorkspaceDatabase): WorkspaceDatabase {
/** Deterministic repository used by route tests and local contract consumers. */
export class MemoryCatalogRepository implements CatalogRepository {
private readonly records = new Map<string, WorkspaceDatabase>();
private readonly installationImports = new Set<string>();
private readonly tables = new Map<string, CatalogTable>();
private readonly columns = new Map<string, CatalogColumn>();
private readonly relationships = new Map<string, CatalogPhysicalRelationship>();
@@ -175,13 +176,13 @@ export class MemoryCatalogRepository implements CatalogRepository {
...relationships.map((relationship) => relationship.updatedAt),
]));
}
async create(input: DatabaseConfigurationInput): Promise<WorkspaceDatabase> {
if ([...this.records.values()].some((record) => record.workspaceId === input.workspaceId)) {
async create(input: DatabaseConfigurationInput, creationId?: string): Promise<WorkspaceDatabase> {
if ((creationId && this.installationImports.has(input.workspaceId)) || [...this.records.values()].some((record) => record.workspaceId === input.workspaceId)) {
throw new CatalogConflictError("Workspace database already exists");
}
const now = new Date().toISOString();
const record: WorkspaceDatabase = {
id: randomUUID(),
id: creationId ?? randomUUID(),
...structuredClone(input),
version: 1,
createdAt: now,
@@ -191,6 +192,7 @@ export class MemoryCatalogRepository implements CatalogRepository {
preprocessingStatus: "failed",
};
this.records.set(record.id, record);
if (creationId) this.installationImports.add(input.workspaceId);
return clone(record);
}
async update(id: string, expectedVersion: number, input: DatabaseConfigurationInput): Promise<WorkspaceDatabase | undefined> {
+2
View File
@@ -16,6 +16,7 @@ import * as canonicalModelIdsMigration from "./migrations/010_canonical_model_id
import * as localSensitivityAnalysisMigration from "./migrations/011_local_sensitivity_analysis.js";
import * as sensitivityReasonMigration from "./migrations/012_sensitivity_reason.js";
import * as catalogPreprocessingStateMigration from "./migrations/013_catalog_preprocessing_state.js";
import * as installationBindingImportsMigration from "./migrations/014_installation_binding_imports.js";
const connectionString = process.env.THT_CATALOG_MIGRATOR_DATABASE_URL;
const host = process.env.THT_CATALOG_DB_HOST;
@@ -54,6 +55,7 @@ const provider: MigrationProvider = {
"011_local_sensitivity_analysis": localSensitivityAnalysisMigration,
"012_sensitivity_reason": sensitivityReasonMigration,
"013_catalog_preprocessing_state": catalogPreprocessingStateMigration,
"014_installation_binding_imports": installationBindingImportsMigration,
};
},
};
@@ -0,0 +1,16 @@
import { type Kysely, sql } from "kysely";
import type { CatalogDatabase } from "../repository.js";
/** Import receipts survive administrative deletion; they contain no credentials or configuration. */
export async function up(db: Kysely<CatalogDatabase>): Promise<void> {
await db.schema.createTable("installation_binding_imports")
.addColumn("workspace_id", "text", column => column.primaryKey())
// Deliberately no cascading FK: absence of a previously imported database requires reconciliation.
.addColumn("database_id", "uuid", column => column.notNull().unique())
.addColumn("created_at", "timestamptz", column => column.notNull().defaultTo(sql`now()`))
.execute();
}
export async function down(db: Kysely<CatalogDatabase>): Promise<void> {
await db.schema.dropTable("installation_binding_imports").execute();
}
+4 -2
View File
@@ -273,6 +273,7 @@ interface CatalogSyncEventTable {
}
export interface CatalogDatabase {
installationBindingImports: { workspaceId: string; databaseId: string; createdAt: Generated<Date> };
workspaceDatabases: WorkspaceDatabaseTable;
databaseBindings: DatabaseBindingTable;
catalogTables: CatalogTableTable;
@@ -681,10 +682,11 @@ export class KyselyCatalogRepository implements CatalogRepository {
}, row.updatedAt === null ? null : new Date(row.updatedAt).toISOString());
}
async create(input: DatabaseConfigurationInput): Promise<WorkspaceDatabase> {
async create(input: DatabaseConfigurationInput, creationId?: string): Promise<WorkspaceDatabase> {
try {
return await this.db.transaction().execute(async (trx) => {
const id = randomUUID();
const id = creationId ?? randomUUID();
if (creationId) await trx.insertInto("installationBindingImports").values({ workspaceId: input.workspaceId, databaseId: id }).execute();
await trx.insertInto("workspaceDatabases").values({
id,
workspaceId: input.workspaceId,
+1 -1
View File
@@ -462,7 +462,7 @@ export interface CatalogRepository {
): Promise<WorkspaceDatabase | undefined>;
clearPreprocessing(workspaceId: string): Promise<CatalogPreprocessingClearResult>;
getCatalogMetrics(databaseId?: string): Promise<CatalogMetrics | undefined>;
create(input: DatabaseConfigurationInput): Promise<WorkspaceDatabase>;
create(input: DatabaseConfigurationInput, creationId?: string): Promise<WorkspaceDatabase>;
update(id: string, expectedVersion: number, input: DatabaseConfigurationInput): Promise<WorkspaceDatabase | undefined>;
recordTest(id: string, expectedVersion: number, result: DatabaseTestResult): Promise<WorkspaceDatabase | undefined>;
touch(id: string, expectedVersion: number): Promise<WorkspaceDatabase | undefined>;
+37
View File
@@ -0,0 +1,37 @@
import type { FastifyInstance } from "fastify";
import { z } from "zod";
import { isPrincipalContext, requirePermission } from "../auth/authorization.js";
import { InstallationBindings, InstallationReconciliationRequired } from "../catalog/installation-bindings.js";
import { CatalogConflictError, CatalogOperationInProgressError } from "../catalog/types.js";
import type { WorkspaceRegistry } from "../workspaces/registry.js";
const sourceSchema = z.object({ remote: z.string().min(1).max(4096), branch: z.string().min(1).max(256),
revision: z.string().regex(/^(?:[a-f0-9]{40}|content-snapshot)$/),
files: z.record(z.string().min(1).max(4096), z.string().regex(/^[a-f0-9]{64}$/))
.refine(files => Object.keys(files).length > 0 && Object.keys(files).length <= 10000),
}).strict();
export function installationRoutes(app: FastifyInstance, bindings: InstallationBindings, registry: WorkspaceRegistry): void {
app.post("/installation/workspace-source", { bodyLimit: 2 * 1024 * 1024 }, async (request, reply) => {
if (!isPrincipalContext(requirePermission(request, reply, "workspace.manage"))) return reply;
try { return await registry.prepareInstallation(sourceSchema.parse(request.body)); }
catch (error) {
return reply.code(error instanceof z.ZodError ? 400 : 409).send({ code: "installation_workspace_reconciliation_required" });
}
});
app.post("/installation/bindings", { bodyLimit: 1024 * 1024 }, async (request, reply) => {
for (const permission of ["workspace.manage", "database.manage", "workspace.secrets.manage"] as const) {
if (!isPrincipalContext(requirePermission(request, reply, permission))) return reply;
}
try {
const result = await bindings.apply(request.body);
return reply.code(result.connectionStatus === "reachable" ? 200 : 422).send(result);
} catch (error) {
if (error instanceof z.ZodError) return reply.code(400).send({ code: "installation_input_invalid" });
if (error instanceof InstallationReconciliationRequired || error instanceof CatalogConflictError || error instanceof CatalogOperationInProgressError) {
return reply.code(409).send({ code: "installation_reconciliation_required" });
}
return reply.code(503).send({ code: "installation_binding_unavailable" });
}
});
}
+33
View File
@@ -3,6 +3,7 @@ import { lstatSync, mkdirSync } from "node:fs";
import { mkdir } from "node:fs/promises";
import { isAbsolute, join } from "node:path";
import { promisify, TextDecoder } from "node:util";
import { createHash } from "node:crypto";
import type { WorkspaceErrorCode, WorkspaceRegistryConfig } from "./types.js";
const execFileAsync = promisify(execFile);
@@ -29,6 +30,13 @@ export interface EvidenceTreeObject {
posixPath: string;
}
export interface PreparedWorkspaceSource {
remote: string;
branch: string;
revision: string;
files: Record<string, string>;
}
export class WorkspaceRegistryError extends Error {
constructor(readonly code: WorkspaceErrorCode, message: string) {
super(message);
@@ -187,6 +195,31 @@ export class GitWorkspaceRepository {
return await this.status();
}
/** Installation consumes exactly prepared contents; it never resets or retargets a checkout. */
async verifyPrepared(expected: PreparedWorkspaceSource): Promise<string> {
const mismatch = () => new WorkspaceRegistryError("workspace_stale", "Prepared workspace source differs from the configured repository.");
if (!this.config.remoteUrl || expected.branch !== this.config.branch || expected.remote !== this.config.remoteUrl) throw mismatch();
await this.ensureLayout();
if (isMissing(this.repoPath)) await this.clone();
const origin = (await this.git(["remote", "get-url", "origin"])).trim();
if (origin !== this.config.remoteUrl) throw mismatch();
if ((await this.git(["symbolic-ref", "--short", "HEAD"])).trim() !== expected.branch ||
(await this.git(["status", "--porcelain"])).trim()) throw mismatch();
const head = (await this.git(["rev-parse", "HEAD"])).trim();
if (expected.revision !== "content-snapshot" && expected.revision !== head) throw mismatch();
const entries = (await this.git(["ls-tree", "-r", "-z", head])).split("\0").filter(Boolean);
if (entries.length !== Object.keys(expected.files).length || entries.length > 10000) throw mismatch();
let total = 0;
for (const entry of entries) {
const match = /^(100644|100755) blob ([a-f0-9]{40})\t(.+)$/s.exec(entry);
if (!match || !Object.hasOwn(expected.files, match[3])) throw mismatch();
const bytes = await this.gitBlobBytes(match[2], 32 << 20, "prepared");
total += bytes.length;
if (total > 256 << 20 || createHash("sha256").update(bytes).digest("hex") !== expected.files[match[3]]) throw mismatch();
}
return head;
}
async pull(): Promise<GitStatus> {
await this.ensureLayout();
if (isMissing(this.repoPath)) return await this.bootstrap();
+14
View File
@@ -13,6 +13,7 @@ import {
WorkspaceRepositoryLock,
normalizeRepositoryIdentity,
type GitStatus,
type PreparedWorkspaceSource,
} from "./git-repository.js";
import {
parseWorkspaceYaml,
@@ -121,6 +122,19 @@ export class WorkspaceRegistry {
});
}
async prepareInstallation(expected: PreparedWorkspaceSource): Promise<{ revision: string }> {
await this.repository.ensureLayout();
return await this.lock.run(async () => {
const head = await this.repository.verifyPrepared(expected);
const active = await this.tryActiveState();
if (active && active.head !== head) {
throw new WorkspaceRegistryError("workspace_stale", "Reconcile the active workspace revision before installation.");
}
if (!active) await this.activate(head);
return { revision: head };
});
}
async pull(): Promise<GitStatus> {
await this.repository.ensureLayout();
return await this.lock.run(async () => {
+16 -1
View File
@@ -11,7 +11,7 @@ import {
rmSync,
writeFileSync,
} from "node:fs";
import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
import { createCipheriv, createDecipheriv, createHash, randomBytes, timingSafeEqual } from "node:crypto";
import { basename, join } from "node:path";
const STORE_ERROR = "Workspace secret store is unavailable.";
@@ -122,6 +122,21 @@ export class WorkspaceSecretStore {
return this.readVault().entries[entryKey(workspaceId, requirementId)] !== undefined;
}
/** Compare without exposing plaintext or a reusable digest to an API consumer. */
matches(workspaceId: string, requirementId: string, value: string): boolean {
const materialized = this.materialize(workspaceId, [requirementId]);
let current: Buffer | undefined;
const expected = Buffer.from(value, "utf8");
try {
const path = materialized.files.get(requirementId);
if (!path) return false;
current = readFileSync(path);
return current.length === expected.length && timingSafeEqual(current, expected);
} finally {
current?.fill(0); expected.fill(0); materialized.release();
}
}
generation(workspaceId: string): number {
assertIdentifier(workspaceId, "workspace identifier");
const vault = this.readVault();