diff --git a/PROJECT_STATE.md b/PROJECT_STATE.md index 9ef9cf01..aaf2fa15 100644 --- a/PROJECT_STATE.md +++ b/PROJECT_STATE.md @@ -30,7 +30,13 @@ and invariants are in [AGENTS.md](AGENTS.md); prior snapshots remain in Git. publishes amd64/arm64 images and native bundles. Its unmodified arm64 archive passed apply/retry, UI/admin login and live user revocation in a Linux consumer without host language runtimes; see [verification evidence](docs/reports/2026-10-06-installation-apply.md). - Binding import, workspace readiness, integrated source/recovery paths, real-host + Ticket #48 now adds authenticated binding import after platform health: exact prepared + repository verification, ordinary local admin login/CSRF, existing encrypted secret + storage, optimistic versions and container-side Catalog connection tests. Durable + Catalog import receipts survive administrative deletion; reruns stop on divergence. + Source/native command, authenticated client, concurrent/recovery and real PostgreSQL + tests cover this increment. These changes are not included in published preview.5. + Workspace readiness, integrated source/recovery paths, real-host acceptance and curated examples remain pending. Earlier previews are superseded for platform apply; no complete installer/OS acceptance is claimed. diff --git a/backend/src/app.ts b/backend/src/app.ts index d26a7cb9..e564b60a 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -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, diff --git a/backend/src/catalog/bootstrap-documents.ts b/backend/src/catalog/bootstrap-documents.ts index 1808976d..288cbf3e 100644 --- a/backend/src/catalog/bootstrap-documents.ts +++ b/backend/src/catalog/bootstrap-documents.ts @@ -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(); 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) => { diff --git a/backend/src/catalog/installation-bindings.ts b/backend/src/catalog/installation-bindings.ts new file mode 100644 index 00000000..98068f4b --- /dev/null +++ b/backend/src/catalog/installation-bindings.ts @@ -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)[item.id])) return conflict(); + const values: Record = { ...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 }; + } +} diff --git a/backend/src/catalog/memory-repository.ts b/backend/src/catalog/memory-repository.ts index 618abbad..de629651 100644 --- a/backend/src/catalog/memory-repository.ts +++ b/backend/src/catalog/memory-repository.ts @@ -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(); + private readonly installationImports = new Set(); private readonly tables = new Map(); private readonly columns = new Map(); private readonly relationships = new Map(); @@ -175,13 +176,13 @@ export class MemoryCatalogRepository implements CatalogRepository { ...relationships.map((relationship) => relationship.updatedAt), ])); } - async create(input: DatabaseConfigurationInput): Promise { - if ([...this.records.values()].some((record) => record.workspaceId === input.workspaceId)) { + async create(input: DatabaseConfigurationInput, creationId?: string): Promise { + 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 { diff --git a/backend/src/catalog/migrate.ts b/backend/src/catalog/migrate.ts index 76b421ed..f55220c9 100644 --- a/backend/src/catalog/migrate.ts +++ b/backend/src/catalog/migrate.ts @@ -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, }; }, }; diff --git a/backend/src/catalog/migrations/014_installation_binding_imports.ts b/backend/src/catalog/migrations/014_installation_binding_imports.ts new file mode 100644 index 00000000..60cb8bd0 --- /dev/null +++ b/backend/src/catalog/migrations/014_installation_binding_imports.ts @@ -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): Promise { + 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): Promise { + await db.schema.dropTable("installation_binding_imports").execute(); +} diff --git a/backend/src/catalog/repository.ts b/backend/src/catalog/repository.ts index 03e3562e..f9e092b1 100644 --- a/backend/src/catalog/repository.ts +++ b/backend/src/catalog/repository.ts @@ -273,6 +273,7 @@ interface CatalogSyncEventTable { } export interface CatalogDatabase { + installationBindingImports: { workspaceId: string; databaseId: string; createdAt: Generated }; 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 { + async create(input: DatabaseConfigurationInput, creationId?: string): Promise { 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, diff --git a/backend/src/catalog/types.ts b/backend/src/catalog/types.ts index 62167474..e074e8e7 100644 --- a/backend/src/catalog/types.ts +++ b/backend/src/catalog/types.ts @@ -462,7 +462,7 @@ export interface CatalogRepository { ): Promise; clearPreprocessing(workspaceId: string): Promise; getCatalogMetrics(databaseId?: string): Promise; - create(input: DatabaseConfigurationInput): Promise; + create(input: DatabaseConfigurationInput, creationId?: string): Promise; update(id: string, expectedVersion: number, input: DatabaseConfigurationInput): Promise; recordTest(id: string, expectedVersion: number, result: DatabaseTestResult): Promise; touch(id: string, expectedVersion: number): Promise; diff --git a/backend/src/routes/installation.ts b/backend/src/routes/installation.ts new file mode 100644 index 00000000..2d4d6c6b --- /dev/null +++ b/backend/src/routes/installation.ts @@ -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" }); + } + }); +} diff --git a/backend/src/workspaces/git-repository.ts b/backend/src/workspaces/git-repository.ts index a01203c1..1b7042c1 100644 --- a/backend/src/workspaces/git-repository.ts +++ b/backend/src/workspaces/git-repository.ts @@ -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; +} + 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 { + 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 { await this.ensureLayout(); if (isMissing(this.repoPath)) return await this.bootstrap(); diff --git a/backend/src/workspaces/registry.ts b/backend/src/workspaces/registry.ts index 2ce2f051..87e492d0 100644 --- a/backend/src/workspaces/registry.ts +++ b/backend/src/workspaces/registry.ts @@ -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 { await this.repository.ensureLayout(); return await this.lock.run(async () => { diff --git a/backend/src/workspaces/secret-store.ts b/backend/src/workspaces/secret-store.ts index 3431ea07..0781b1cf 100644 --- a/backend/src/workspaces/secret-store.ts +++ b/backend/src/workspaces/secret-store.ts @@ -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(); diff --git a/backend/test/catalog-repository.integration.test.ts b/backend/test/catalog-repository.integration.test.ts index 2cdcb6d6..2159eac2 100644 --- a/backend/test/catalog-repository.integration.test.ts +++ b/backend/test/catalog-repository.integration.test.ts @@ -1,5 +1,8 @@ import { spawnSync } from "node:child_process"; import { randomUUID } from "node:crypto"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { PostgreSqlContainer } from "@testcontainers/postgresql"; import { CamelCasePlugin, Kysely, PostgresDialect, sql } from "kysely"; import { Pool } from "pg"; @@ -19,6 +22,12 @@ import { up as upCanonicalModelIds } from "../src/catalog/migrations/010_canonic import { up as upLocalSensitivityAnalysis } from "../src/catalog/migrations/011_local_sensitivity_analysis.js"; import { up as upSensitivityReason } from "../src/catalog/migrations/012_sensitivity_reason.js"; import { up as upCatalogPreprocessingState } from "../src/catalog/migrations/013_catalog_preprocessing_state.js"; +import { up as upInstallationBindingImports } from "../src/catalog/migrations/014_installation_binding_imports.js"; +import { InstallationBindings } from "../src/catalog/installation-bindings.js"; +import { CatalogService } from "../src/catalog/service.js"; +import { CatalogOperationCoordinator } from "../src/catalog/operation-coordinator.js"; +import { WorkspaceSecretStore } from "../src/workspaces/secret-store.js"; +import type { WorkspaceRegistry } from "../src/workspaces/registry.js"; const dockerAvailable = spawnSync("docker", ["info"], { stdio: "ignore" }).status === 0; @@ -60,6 +69,7 @@ test.skipIf(!dockerAvailable)("PostgreSQL migration enforces one database per wo await upLocalSensitivityAnalysis(db); await upSensitivityReason(db); await upCatalogPreprocessingState(db); + await upInstallationBindingImports(db); await expect(db.selectFrom("sensitiveDataSuggestionRuns") .select(["engine", "modelId", "policyVersion", "unknown"]) .where("id", "=", historicalSuggestionRunId) @@ -319,6 +329,37 @@ test.skipIf(!dockerAvailable)("PostgreSQL migration enforces one database per wo expect(await repository.delete(created.id, 2)).toBe(true); expect(await repository.list()).toEqual([]); expect(await repository.listTables(created.id)).toEqual([]); + // Installation import uses the real transactional Catalog and a read-only PostgreSQL login. + await sql`CREATE ROLE installation_reader LOGIN PASSWORD 'installation-test-password'`.execute(db); + await sql`GRANT USAGE ON SCHEMA public TO installation_reader`.execute(db); + const secretRoot = mkdtempSync(join(tmpdir(), "catalog-installation-")); + try { + const secrets = new WorkspaceSecretStore({ root: secretRoot, installationId: "integration" }); + const revision = "a".repeat(40); + const registry = { read: async () => ({ workspace: { workspace: { schema_version: 4, id: "installation-test", name: "Test", language: "en" } }, + revision: { commit: revision } }) } as unknown as WorkspaceRegistry; + const operations = new CatalogOperationCoordinator(); + const service = new CatalogService(repository, registry, secrets, [], 5000, undefined, operations); + const importer = new InstallationBindings(repository, service, registry, secrets, operations, "integration"); + const request = { schemaVersion: 1, revision, configuration: { + workspaceId: "installation-test", engine: "postgres", databaseName: container.getDatabase(), schema: "public", + binding: { transport: "postgres_direct", host: container.getHost(), port: container.getPort(), username: "installation_reader" }, + }, secrets: { password: "installation-test-password" }, evidenceSecrets: {} }; + const applied = await importer.apply(request); + expect(applied).toMatchObject({ status: "applied", connectionStatus: "reachable", version: 2 }); + const generation = secrets.generation("installation-test"); + expect(await importer.apply(request)).toEqual({ ...applied, status: "unchanged" }); + expect(secrets.generation("installation-test")).toBe(generation); + expect(await repository.update(applied.databaseId, 1, request.configuration as never)).toBeUndefined(); + await repository.touch(applied.databaseId, applied.version); + secrets.put("installation-test", "catalog.dwh.password", "administrative-change"); + await expect(importer.apply(request)).rejects.toThrow("Reconcile"); + expect(secrets.matches("installation-test", "catalog.dwh.password", "administrative-change")).toBe(true); + const currentImport = (await repository.get(applied.databaseId))!; + expect(await repository.delete(applied.databaseId, currentImport.version)).toBe(true); + await expect(importer.apply(request)).rejects.toThrow("Workspace database already exists"); + expect(await repository.getByWorkspace("installation-test")).toBeUndefined(); + } finally { rmSync(secretRoot, { recursive: true, force: true }); } } finally { await db.destroy(); await container.stop(); diff --git a/backend/test/installation-bindings.test.ts b/backend/test/installation-bindings.test.ts new file mode 100644 index 00000000..625fa87d --- /dev/null +++ b/backend/test/installation-bindings.test.ts @@ -0,0 +1,166 @@ +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { spawn } from "node:child_process"; +import { createLocalAuthFixture, localPassword } from "./auth-test-fixtures.js"; +import { afterEach, expect, test, vi } from "vitest"; +import { buildApp } from "../src/app.js"; +import { loadConfig } from "../src/config.js"; +import { MemoryCatalogRepository } from "../src/catalog/memory-repository.js"; +import { WorkspaceSecretStore } from "../src/workspaces/secret-store.js"; +import type { WorkspaceRegistry } from "../src/workspaces/registry.js"; + +const roots: string[] = []; +afterEach(() => roots.splice(0).forEach(root => rmSync(root, { recursive: true, force: true }))); +const commit = "a".repeat(40); +const configuration = { workspaceId: "chinook", engine: "postgres", databaseName: "chinook", schema: "public", + binding: { transport: "postgres_direct", host: "database", port: 5432, username: "reader" } }; +function setup(environment: Record = {}) { + const root = mkdtempSync(join(tmpdir(), "installation-binding-")); roots.push(root); + const secrets = new WorkspaceSecretStore({ root, installationId: "installation" }); + const repository = new MemoryCatalogRepository(); + const registry = { + read: vi.fn(async () => ({ workspace: { workspace: { schema_version: 4, id: "chinook", name: "Chinook", language: "en" } }, + revision: { id: "chinook", commit, blob: "b".repeat(40) } })), + } as unknown as WorkspaceRegistry; + const app = buildApp(loadConfig({ NODE_ENV: "test", THT_HARNESS_DIR: "/missing", ...environment }), { + workspaceRegistry: registry, workspaceSecretStore: secrets, catalogRepository: repository, + catalogPostgresAccess: { connect: async () => ({ query: async () => ({ rows: [{ database: "chinook", schema: "public" }] }), end: async () => {} }) } as never, + }); + const apply = (values = { password: "private-test-password" }) => app.inject({ method: "POST", url: "/installation/bindings", + payload: { schemaVersion: 1, revision: commit, configuration, secrets: values, evidenceSecrets: {} } }); + return { app, apply, repository, secrets, registry }; +} + +test("prepared binding is imported once and equivalent rerun preserves credentials and version", async () => { + const { app, apply, repository, secrets } = setup(); + try { + const first = await apply(); expect(first.statusCode).toBe(200); + expect(first.json()).toMatchObject({ status: "applied", connectionStatus: "reachable" }); + const generation = secrets.generation("chinook"); + const before = await repository.getByWorkspace("chinook"); + const second = await apply(); expect(second.statusCode).toBe(200); + expect(second.json()).toMatchObject({ status: "unchanged", databaseId: before!.id, version: before!.version }); + expect(secrets.generation("chinook")).toBe(generation); + expect(await repository.list()).toHaveLength(1); + expect(second.body).not.toContain("private-test-password"); + } finally { await app.close(); } +}); + +test("released pipe client uses real local login, CSRF and logout without exposing credentials", async () => { + const original = setup(); await original.app.close(); + const registry = original.registry; + registry.prepareInstallation = async () => ({ revision: commit }); + const fixture = await createLocalAuthFixture({ workspaceRegistry: registry, + workspaceSecretStore: original.secrets, catalogRepository: original.repository, + catalogPostgresAccess: { connect: async () => ({ query: async () => ({ rows: [{ database: "chinook", schema: "public" }] }), end: async () => {} }) } as never, + }); + try { + const address = await fixture.app.listen({ host: "127.0.0.1", port: 0 }); + const payload = { username: "Admin", password: localPassword, origin: fixture.publicUrl, + source: { remote: "https://example.invalid/workspaces.git", branch: "main", revision: commit, + files: { "thoth-workspaces.yaml": "a".repeat(64) } }, + databases: [{ schemaVersion: 1, configuration, secrets: { password: "private-test-password" }, evidenceSecrets: {} }] }; + const run = () => new Promise<{ code: number | null; output: string }>((resolve, reject) => { + const child = spawn(process.execPath, ["--input-type=module", "-e", + `import { importPreparedBindings } from '../tools/tht/internal/installapply/import-bindings.mjs'; await importPreparedBindings(${JSON.stringify(address)});`], { + env: process.env, stdio: ["pipe", "pipe", "pipe"], + }); + let output = ""; child.stdout.on("data", data => { output += data; }); child.stderr.on("data", data => { output += data; }); + child.once("error", reject); child.once("close", code => resolve({ code, output })); + child.stdin.end(JSON.stringify(payload)); + }); + for (let i = 0; i < 2; i++) { + const result = await run(); + expect(result).toEqual({ code: 0, output: JSON.stringify({ ok: true, code: "bindings_ready", completed: 1 }) }); + } + expect(await original.repository.list()).toHaveLength(1); + } finally { await fixture.close(); } +}); + +test("administrative binding and credential changes require reconciliation without overwriting", async () => { + const { app, apply, repository, secrets } = setup(); + try { + expect((await apply()).statusCode).toBe(200); + const current = (await repository.getByWorkspace("chinook"))!; + secrets.put("chinook", "catalog.dwh.password", "changed-by-administrator"); + expect((await apply()).statusCode).toBe(409); + expect(secrets.matches("chinook", "catalog.dwh.password", "changed-by-administrator")).toBe(true); + const modified = { ...current, binding: { ...current.binding, host: "different-database" } }; + await repository.update(current.id, current.version, modified); + expect((await apply()).statusCode).toBe(409); + expect((await repository.get(current.id))!.binding.host).toBe("different-database"); + } finally { await app.close(); } +}); + +test("a manually configured binding is never silently adopted", async () => { + const { app, apply, repository } = setup(); + try { + const created = await app.inject({ method: "POST", url: "/catalog/databases", payload: configuration }); + expect(created.statusCode).toBe(201); + expect((await apply()).statusCode).toBe(409); + expect(await repository.list()).toHaveLength(1); + } finally { await app.close(); } +}); + +test("administrative deletion remains a reconciliation stop rather than recreating a binding", async () => { + const { app, apply, repository, secrets } = setup(); + try { + expect((await apply()).statusCode).toBe(200); + const database = (await repository.getByWorkspace("chinook"))!; + const deleted = await app.inject({ method: "DELETE", url: `/catalog/databases/${database.id}?version=${database.version}` }); + expect(deleted.statusCode).toBe(204); + expect((await apply()).statusCode).toBe(409); + expect(await repository.list()).toHaveLength(0); + expect(secrets.has("chinook", "catalog.dwh.password")).toBe(false); + } finally { await app.close(); } +}); + +test("interruption after Catalog commit resumes the same identity without a host journal", async () => { + const { app, apply, repository } = setup(); + const create = repository.create.bind(repository); + vi.spyOn(repository, "create").mockImplementationOnce(async (...args) => { + await create(...args); throw new Error("simulated connection loss after commit"); + }); + try { + expect((await apply()).statusCode).toBe(503); + const current = (await repository.getByWorkspace("chinook"))!; + expect((await apply()).json()).toMatchObject({ databaseId: current.id, connectionStatus: "reachable" }); + expect(await repository.list()).toHaveLength(1); + } finally { await app.close(); } +}); + +test("concurrent imports cannot duplicate or replace credentials", async () => { + const { app, apply, repository, secrets } = setup(); + let entered!: () => void; + let release!: () => void; + const started = new Promise(resolve => { entered = resolve; }); + const continueCreation = new Promise(resolve => { release = resolve; }); + const create = repository.create.bind(repository); + vi.spyOn(repository, "create").mockImplementationOnce(async (...args) => { + entered(); await continueCreation; return create(...args); + }); + try { + const first = apply(); + await started; + const second = await apply(); + release(); + const results = [await first, second]; + expect(results.map(result => result.statusCode).sort()).toEqual([200, 409]); + expect(await repository.list()).toHaveLength(1); + expect(secrets.matches("chinook", "catalog.dwh.password", "private-test-password")).toBe(true); + } finally { release(); await app.close(); } +}); + +test("imports and source activation require an authenticated administrator", async () => { + const { app, repository } = setup({ AUTH_MODE: "upstream" }); + try { + for (const url of ["/installation/bindings", "/installation/workspace-source"]) { + expect((await app.inject({ method: "POST", url, payload: {} })).statusCode).toBe(401); + expect((await app.inject({ method: "POST", url, payload: {}, headers: { + "x-thoth-principal-issuer": "portal", "x-thoth-principal-subject": "reader", "x-thoth-is-admin": "0", + } })).statusCode).toBe(403); + } + expect(await repository.list()).toHaveLength(0); + } finally { await app.close(); } +}); diff --git a/backend/test/installation-workspace-source.test.ts b/backend/test/installation-workspace-source.test.ts new file mode 100644 index 00000000..6953677d --- /dev/null +++ b/backend/test/installation-workspace-source.test.ts @@ -0,0 +1,34 @@ +import { execFileSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { mkdtempSync, mkdirSync, writeFileSync, rmSync, readFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, expect, test } from "vitest"; +import { WorkspaceRegistry } from "../src/workspaces/registry.js"; +const roots: string[] = []; +afterEach(() => roots.splice(0).forEach(root => rmSync(root, { recursive: true, force: true }))); +test("activates only the prepared source contents and never retargets an existing checkout", async () => { + const root = mkdtempSync(join(tmpdir(), "installation-source-")); roots.push(root); + const remote = join(root, "source"); mkdirSync(join(remote, "chinook"), { recursive: true }); + const files: Record = { + "thoth-workspaces.yaml": "schema_version: 1\nworkspaces: [{id: chinook, name: Chinook}]\n", + "chinook/workspace.yaml": "workspace:\n schema_version: 4\n id: chinook\n name: Chinook\n language: en\n", + }; + for (const [path, value] of Object.entries(files)) writeFileSync(join(remote, path), value); + const git = (args: string[], cwd = remote) => execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim(); + git(["init", "-b", "main"]); git(["add", "."]); + git(["-c", "user.name=Test", "-c", "user.email=test@example.invalid", "commit", "-m", "fixture"]); + const revision = git(["rev-parse", "HEAD"]); + const config = { root: join(root, "registry"), remoteUrl: remote, branch: "main", installationId: "test", secretRoots: [] }; + const registry = new WorkspaceRegistry(config); + const expected = { remote, branch: "main", revision, files: Object.fromEntries(Object.entries(files).map(([path, value]) => [path, createHash("sha256").update(value).digest("hex")])) }; + await expect(registry.prepareInstallation({ ...expected, files: { ...expected.files, "chinook/workspace.yaml": "0".repeat(64) } })).rejects.toThrow(); + await expect(registry.verifyStoredState()).rejects.toThrow(); + await expect(registry.prepareInstallation(expected)).resolves.toMatchObject({ revision }); + await expect(registry.prepareInstallation(expected)).resolves.toMatchObject({ revision }); + const checkout = join(config.root, "repo"); + git(["remote", "set-url", "origin", join(root, "another")], checkout); + await expect(registry.prepareInstallation(expected)).rejects.toThrow(); + expect(git(["remote", "get-url", "origin"], checkout)).toBe(join(root, "another")); + expect(readFileSync(join(checkout, "chinook/workspace.yaml"), "utf8")).toBe(files["chinook/workspace.yaml"]); +}); diff --git a/docs/install/installation-preflight.md b/docs/install/installation-preflight.md index 50754e0d..4880f95c 100644 --- a/docs/install/installation-preflight.md +++ b/docs/install/installation-preflight.md @@ -113,6 +113,22 @@ Cancellation cleans up named one-shot containers and releases the lock. Hard-kil processes require explicit stale-owner inspection; automatic destructive repair is not performed. Errors contain a stage/action without raw Docker output or secrets. -Success reports `platform_ready: true` and `workspace_ready: false`: services and -local authentication protection are checked, while binding import, workspace -preprocessing, model use and final readiness remain separate obligations. +Binding import uses a named, bounded one-shot client on the Compose network. Protected +bootstrap material travels through stdin, never arguments or journals. The client logs +in through local authentication, obtains CSRF protection, calls permission-checked +administration services, and logs out. Prepare `authentication.username` and +`authentication.passwordFile` in `database-bootstrap.yaml`; offline validation checks +the account/password against the private local registry and seals that file too. + +The registry consumes the exact prepared Git file inventory and optional commit, without +retargeting or refreshing an existing checkout. Binding creation and its durable import +receipt commit together in the Catalog. The receipt survives administrative deletion. +Reruns compare live configuration and encrypted-store contents, retain equivalent values, +and stop on divergence. No bootstrap document becomes runtime authority. The application +tests the imported connection; a successful host probe alone is insufficient. + +Success reports `platform_ready: true`, `bindings_ready: true`, `workspace_ready: false`. +The bounded `binding_import` report distinguishes authentication, workspace reconciliation, +binding reconciliation and container connectivity failures. Workspace preprocessing, +model use and final readiness remain separate obligations. Published preview.5 predates +binding import; use a subsequent matching image/operator release for this extension. diff --git a/docs/install/standalone-manual-en.md b/docs/install/standalone-manual-en.md index 4844e37e..c3d4457f 100644 --- a/docs/install/standalone-manual-en.md +++ b/docs/install/standalone-manual-en.md @@ -93,6 +93,9 @@ must exist. It starts no services and does not implicitly generate passwords. ```yaml schemaVersion: 1 + authentication: + username: admin + passwordFile: /private/path/my-installation/secrets/admin-password databases: - workspaceId: practice engine: postgres @@ -116,7 +119,11 @@ must exist. It starts no services and does not implicitly generate passwords. `evidenceSecretFiles` with key `evidence.signed_urls`; static S3 credentials need `evidence.access_key`, `evidence.secret_key` and optional `evidence.session_token`. All values are private file paths. Workspace descriptors remain schema v4; - this bootstrap input is not a second runtime Catalog. + this bootstrap input is not a second runtime Catalog. The document also includes + `authentication.username: admin` and `authentication.passwordFile` pointing to + private `secrets/admin-password`. Update these references before validation if + selecting another administrator. Execution uses ordinary login and administrative + permissions, without asking for a password during setup. 4. Explicitly generate technical credentials in the standard layout: ```sh @@ -211,10 +218,24 @@ comes from the prepared authentication documents. Secrets retain private permiss services that read them run with the operator's UID. This path does not convert an existing stack with incompatible volume ownership. -`platform_ready: true, workspace_ready: false` confirms platform startup and protected -endpoints, **not** readiness to query a database. Binding import, workspace activation -and preprocessing, and a model smoke test are subsequent steps. The three curated -example databases remain deferred. +Execution then imports bindings through authenticated Catalog services and the existing +secret store. It verifies the remote, branch, revision and exact contents against the +prepared plan, without silently retargeting an existing checkout. Database connectivity +is tested again by the application in the containers. + +`platform_ready: true, bindings_ready: true, workspace_ready: false` confirms the platform, +authentication and database connections. Workspace preprocessing and model checks remain +necessary before a question. The three curated examples remain deferred. This extension +requires a bundle newer than preview.5; preview.5 only certifies platform startup. + +An equivalent rerun does not duplicate bindings or credentials. Administrative changes +or deletion stop import with `binding_reconciliation_required`: compare the bootstrap +with Administration and preserve the intended change. Do not remove volumes or Catalog +receipts to bypass this check. `workspace_reconciliation_required` identifies a source +mismatch; `authentication_required` requires correcting the prepared administrator; +`container_connection_failed` means the DWH cannot be reached or authenticated from the +application network. Scalar credential files ignore outer whitespace, matching preflight +probes; PEM and known-host files retain their exact bytes. With the default configuration, open `http://127.0.0.1:8080` to sign in. The browser origin must match `publicUrl`; do not substitute `localhost` for `127.0.0.1`. diff --git a/docs/install/standalone-manual-it.md b/docs/install/standalone-manual-it.md index 3c399d00..300df56a 100644 --- a/docs/install/standalone-manual-it.md +++ b/docs/install/standalone-manual-it.md @@ -94,6 +94,9 @@ deve esistere. Non avvia servizi e non genera implicitamente password. ```yaml schemaVersion: 1 + authentication: + username: admin + passwordFile: /percorso/privato/mia-installazione/secrets/admin-password databases: - workspaceId: pratica engine: postgres @@ -118,7 +121,11 @@ deve esistere. Non avvia servizi e non genera implicitamente password. `evidence.signed_urls`; S3 con credenziali statiche richiede `evidence.access_key` e `evidence.secret_key`, con `evidence.session_token` facoltativo. Tutti i valori sono percorsi di file privati. I workspace rimangono nello schema v4: il bootstrap - è un input iniziale, non un secondo Catalog runtime. + è un input iniziale, non un secondo Catalog runtime. Il documento include anche + `authentication.username: admin` e `authentication.passwordFile` con il percorso + privato di `secrets/admin-password`. Se si cambia amministratore, aggiornare questi + riferimenti prima della validazione: il setup usa il login ordinario e i permessi + amministrativi, senza richiedere una password durante l'esecuzione. 4. Generare esplicitamente le credenziali tecniche nel layout standard: ```sh @@ -219,10 +226,26 @@ proviene dai documenti di autenticazione già preparati. I segreti mantengono i permessi privati: i servizi interessati usano l'UID dell'operatore. Questo percorso non converte stack preesistenti con proprietari o volumi incompatibili. -Il risultato `platform_ready: true, workspace_ready: false` certifica l'avvio della -piattaforma e la protezione degli endpoint, **non** la possibilità di interrogare -già il database. Import dei binding, attivazione/preprocessing dei workspace e -prova modello sono i passi successivi. I tre database di esempio restano differiti. +L'esecuzione importa poi i binding tramite i servizi autenticati del Catalog e il +secret store esistente. Verifica che remoto, branch, revisione e contenuti coincidano +con i documenti del piano; non cambia implicitamente un checkout già presente. +La connessione al DWH viene riprovata dall'applicazione nei container. + +Il risultato `platform_ready: true, bindings_ready: true, workspace_ready: false` +conferma piattaforma, autenticazione e collegamenti database. Preprocessing del +workspace e prova modello rimangono necessari prima di una domanda. I tre database +di esempio restano differiti. Questa estensione richiede un bundle successivo a +preview.5; preview.5 certifica soltanto l'avvio della piattaforma. + +Un secondo avvio non duplica binding o credenziali. Se un amministratore ha modificato +o eliminato un binding, il codice `binding_reconciliation_required` ferma l'import: +confrontare il bootstrap con la configurazione in Amministrazione e preservare la +modifica voluta. Non cancellare volumi o ricevute Catalog per aggirare il controllo. +`workspace_reconciliation_required` indica una differenza nella sorgente workspace; +`authentication_required` richiede di correggere l'amministratore predisposto; +`container_connection_failed` indica un DWH non raggiungibile o non autenticabile +dalla rete applicativa. I segreti scalari letti dai file ignorano spazi e ritorni a +capo esterni, come i probe preliminari; PEM e known-hosts restano invariati. Con il valore predefinito, aprire `http://127.0.0.1:8080` per l'accesso: l'origine del browser deve coincidere con `publicUrl`, quindi non sostituire `127.0.0.1` con `localhost`. diff --git a/docs/reports/2026-10-06-installation-bindings.md b/docs/reports/2026-10-06-installation-bindings.md new file mode 100644 index 00000000..1a9525d6 --- /dev/null +++ b/docs/reports/2026-10-06-installation-bindings.md @@ -0,0 +1,36 @@ +# Prepared Catalog binding import + +Ticket #48 extends document-first `installation apply` after platform health. +It verifies the exact prepared workspace source and imports the selected database +configurations through authenticated, permission-checked application services. +This source increment is not present in the published preview.5 bundle. + +The prepared bootstrap now includes a local administrator username and private +password-file reference. Offline validation verifies them against the authentication +documents. Runtime uses ordinary login, session and CSRF handling. A named one-shot +client on the Compose network receives secrets through stdin and logs out afterward. +The existing Docker runner removes that container on interruption. + +Each first import commits its Catalog database, binding and receipt together. The +receipt survives administrative deletion. Equivalent reruns preserve secret-store +generation and binding version; changed configuration, credentials, deleted bindings +or a different repository require reconciliation. Interrupted creation is recovered +from Catalog state even when the host journal has not yet recorded success. + +Verification includes: + +- Native prepare/validate/plan/apply/retry with closed stdin and no host runtime on + the consumer command PATH (Docker boundary fixture). +- Real local login, CSRF, binding API and logout through the shipped client module. +- Real Git source inventories, revision mismatch and refusal to retarget a checkout. +- Real PostgreSQL Catalog integration, read-only connector authentication, optimistic + versions, repeat imports and retained receipts after deletion. +- Secret newline normalization, no secret arguments/output, concurrent imports, + administrative divergence and interruption after database commit. +- Go suite, backend suite under the supported Node 24 runtime, TypeScript checking + and strict public documentation build. + +The PostgreSQL integration runs the application service against a Docker database; +the public-image consumer trial for this new increment remains to be performed. +It does not establish workspace preprocessing, model operation, a human-reviewed +question, curated example availability or fresh-machine OS acceptance. diff --git a/tools/tht/cmd/tht/installation_documents.go b/tools/tht/cmd/tht/installation_documents.go index fa47163e..1082d0ba 100644 --- a/tools/tht/cmd/tht/installation_documents.go +++ b/tools/tht/cmd/tht/installation_documents.go @@ -67,6 +67,7 @@ func installationDocumentsCommand(ctx context.Context, installationPath string, outsideWorkspace(path, "operator.env", "protected-file-reference") } if preparation.CheckYAML(bootstrap, "database-bootstrap.yaml", &report) { + preparation.CheckBootstrapAuthentication(installation, bootstrap, &report) var output, discarded bytes.Buffer code := workspaceDocumentsCommand(ctx, []string{"bootstrap", "--directory", workspace, "--bootstrap", bootstrap, "--json"}, &output, &discarded) var checked struct { diff --git a/tools/tht/cmd/tht/installation_preflight_integration_test.go b/tools/tht/cmd/tht/installation_preflight_integration_test.go index bd9e071c..36f187c4 100644 --- a/tools/tht/cmd/tht/installation_preflight_integration_test.go +++ b/tools/tht/cmd/tht/installation_preflight_integration_test.go @@ -79,7 +79,7 @@ func TestNativeInstallationPlanBeforeContainersExist(t *testing.T) { for name, data := range map[string][]byte{"secrets.env": []byte("OPENAI_API_KEY=PRIVATE_PROVIDER_VALUE\n"), "database-password": []byte("PRIVATE_DATABASE_VALUE"), "git-credentials": {}, "git-ca.pem": pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: git.Certificate().Raw})} { write(filepath.Join(installation, "secrets", name), data) } - write(filepath.Join(installation, "database-bootstrap.yaml"), []byte(fmt.Sprintf("schemaVersion: 1\ndatabases:\n - workspaceId: practice\n engine: postgres\n databaseName: practice\n schema: public\n binding: {transport: rest_api, baseUrl: %q, restPath: /health, restAuth: bearer}\n secretFiles: {apiKey: %q}\n", database.URL, filepath.Join(installation, "secrets/database-password")))) + write(filepath.Join(installation, "database-bootstrap.yaml"), []byte(fmt.Sprintf("schemaVersion: 1\nauthentication: {username: admin, passwordFile: %q}\ndatabases:\n - workspaceId: practice\n engine: postgres\n databaseName: practice\n schema: public\n binding: {transport: rest_api, baseUrl: %q, restPath: /health, restAuth: bearer}\n secretFiles: {apiKey: %q}\n", filepath.Join(installation, "secrets/admin-password"), database.URL, filepath.Join(installation, "secrets/database-password")))) manifest := preflight.Manifest{SchemaVersion: 1, Version: "1.0.0", Revision: strings.Repeat("b", 40), ValidatorProtocol: 1, Requirements: preflight.DefaultRequirements(), Components: []string{"pi", "catalog-migrations", "workspace-maintenance"}, Images: map[string]map[string]string{}, Files: map[string]string{}, Compose: []string{"compose.yaml"}} code, identityJSON := command("version") var identity version.Info @@ -111,6 +111,7 @@ run) case "$*" in *'/etc/passwd') printf 'root:x:0:0:root:/root:/bin/bash\nthoth container) :;; *) exit 1;;`, 1) script = strings.Replace(script, "else printf '%s\\n'", `elif case "$*" in *' ps '*) true;; *) false;; esac; then printf '%s\n' '[{"Service":"core","State":"running","Health":"healthy"},{"Service":"frontend","State":"running","Health":"healthy"},{"Service":"qdrant","State":"running","Health":"healthy"},{"Service":"embedding","State":"running","Health":"healthy"},{"Service":"embedding-model-init","State":"exited","ExitCode":0}]'; else printf '%s\n'`, 1) + script = strings.Replace(script, "else printf '%s\\n'", `elif case "$*" in *'protected input arrives only through stdin'*) true;; *) false;; esac; then while IFS= read -r line; do :; done; printf '%s\n' '{"ok":true,"code":"bindings_ready","completed":1}'; else printf '%s\n'`, 1) write(filepath.Join(root, "docker"), []byte(script)) _ = os.Chmod(filepath.Join(root, "docker"), 0o700) planPath := filepath.Join(installation, "plan.json") diff --git a/tools/tht/internal/installapply/bindings.go b/tools/tht/internal/installapply/bindings.go new file mode 100644 index 00000000..8dd6e9b2 --- /dev/null +++ b/tools/tht/internal/installapply/bindings.go @@ -0,0 +1,141 @@ +package installapply + +import ( + "bytes" + "context" + "crypto/sha256" + _ "embed" + "encoding/json" + "errors" + "fmt" + "path/filepath" + "slices" + "strings" + "time" + + "github.com/aritmolab/thothii/tools/tht/internal/authconfig" + "github.com/aritmolab/thothii/tools/tht/internal/compose" + "github.com/aritmolab/thothii/tools/tht/internal/preflight" + "github.com/aritmolab/thothii/tools/tht/internal/safeio" + "gopkg.in/yaml.v3" +) + +//go:embed import-bindings.mjs +var bindingClientModule string + +var bindingClient = bindingClientModule + "\nawait importPreparedBindings();\n" + +type BindingReport struct { + OK bool `json:"ok"` + Code string `json:"code"` + Completed int `json:"completed"` +} + +// Secrets travel only over the child pipe; they never enter argv, generated assets or journals. +func bindingPayload(plan preflight.Plan) ([]byte, error) { + failure := errors.New("Prepare authentication.username and authentication.passwordFile in the protected database bootstrap document, validate and produce a new plan.") + data, err := safeio.ReadCanonicalPrivateRegular(plan.BootstrapPath, 1<<20) + if err != nil { + return nil, failure + } + var doc struct { + SchemaVersion int `yaml:"schemaVersion"` + Authentication struct { + Username string `yaml:"username"` + PasswordFile string `yaml:"passwordFile"` + } `yaml:"authentication"` + Databases []map[string]any `yaml:"databases"` + } + if yaml.Unmarshal(data, &doc) != nil || doc.SchemaVersion != 1 || doc.Authentication.Username == "" || len(doc.Databases) == 0 { + return nil, failure + } + readSecret := func(path string) (string, error) { + if !slices.Contains(plan.Inputs, path) { + return "", failure + } + value, err := safeio.ReadCanonicalPrivateRegular(path, 64<<10) + if err != nil || len(value) == 0 { + return "", failure + } + return string(value), nil + } + password, err := readSecret(doc.Authentication.PasswordFile) + if err != nil { + return nil, failure + } + auth, _, err := authconfig.Load(plan.Installation.AuthenticationDirectory()) + if err != nil || auth.Mode != "local" { + return nil, failure + } + files := map[string]string{} + for _, path := range plan.Inputs { + rel, err := filepath.Rel(plan.WorkspaceDirectory, path) + if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || filepath.IsAbs(rel) { + continue + } + parts := strings.Split(filepath.ToSlash(rel), "/") + if slices.Contains(parts, ".git") { + continue + } + value, err := safeio.ReadCanonicalRegular(path, 32<<20) + if err != nil { + return nil, failure + } + files[filepath.ToSlash(rel)] = fmt.Sprintf("%x", sha256.Sum256(value)) + } + if len(files) == 0 { + return nil, failure + } + databases := []map[string]any{} + for _, entry := range doc.Databases { + values := map[string]any{} + for _, pair := range [][2]string{{"secretFiles", "secrets"}, {"evidenceSecretFiles", "evidenceSecrets"}} { + secrets := map[string]string{} + if refs, ok := entry[pair[0]].(map[string]any); ok { + for name, reference := range refs { + path, ok := reference.(string) + if !ok { + return nil, failure + } + secret, err := readSecret(path) + if err != nil { + return nil, failure + } + // Match file-based preflight adapters for scalar credentials; preserve PEM/known-host files. + if name != "sshPrivateKey" && name != "sshKnownHosts" && name != "tlsCa" { + secret = strings.TrimSpace(secret) + } + secrets[name] = secret + } + } + delete(entry, pair[0]) + values[pair[1]] = secrets + } + values["schemaVersion"] = 1 + values["configuration"] = entry + databases = append(databases, values) + } + return json.Marshal(map[string]any{"username": doc.Authentication.Username, "password": strings.TrimSpace(password), + "origin": strings.TrimSuffix(auth.PublicURL, "/"), "databases": databases, + "source": map[string]any{"remote": plan.Installation.WorkspaceRepository.Remote, "branch": plan.Installation.WorkspaceRepository.Branch, + "revision": plan.WorkspaceRevision, "files": files}}) +} + +func importBindings(ctx context.Context, plan preflight.Plan, runner compose.Runner, payload []byte) (BindingReport, error) { + bound, cancel := context.WithTimeout(ctx, 15*time.Minute) + defer cancel() + name, err := compose.NewOneShotContainerName(plan.Installation.ProjectName() + "-bindings") + if err != nil { + return BindingReport{Code: "binding_import_failed"}, err + } + result, err := runner.Run(bound, plan.Installation.ComposeArgs("run", "--rm", "-T", "--no-deps", "--pull", "never", "--name", name, + "--entrypoint", "node", "core", "--input-type=module", "-e", bindingClient), bytes.NewReader(payload)) + var report BindingReport + if json.Unmarshal([]byte(result.Stdout), &report) != nil || !slices.Contains([]string{"bindings_ready", "authentication_required", "workspace_reconciliation_required", "binding_reconciliation_required", "container_connection_failed", "binding_import_failed"}, report.Code) { + return BindingReport{Code: "binding_import_failed"}, errors.New("Binding import did not return a valid report") + } + if err != nil || result.ExitCode != 0 || !report.OK || report.Code != "bindings_ready" || report.Completed < 1 { + return report, errors.New("Binding import stopped; reconcile the prepared documents with application administration and repeat planning") + } + return report, nil +} diff --git a/tools/tht/internal/installapply/import-bindings.mjs b/tools/tht/internal/installapply/import-bindings.mjs new file mode 100644 index 00000000..96c086f5 --- /dev/null +++ b/tools/tht/internal/installapply/import-bindings.mjs @@ -0,0 +1,40 @@ +// Fixed client executed inside the released core; protected input arrives only through stdin. +export async function importPreparedBindings(base = "http://core:8787") { +let cookie = "", csrf = "", origin = "", completed = 0, code = "authentication_required"; +const request = async (path, body) => fetch(base + path, { + method: body === undefined ? "GET" : "POST", redirect: "error", signal: AbortSignal.timeout(180000), + headers: { "content-type": "application/json", origin, ...(cookie ? { cookie } : {}), ...(csrf ? { "x-thothii-csrf": csrf } : {}) }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), +}); +try { + let input = ""; + for await (const chunk of process.stdin) { input += chunk; if (Buffer.byteLength(input) > 16 * 1024 * 1024) throw Error(); } + const prepared = JSON.parse(input); input = ""; origin = prepared.origin; + const login = await request("/auth/local/login", { username: prepared.username, password: prepared.password, remember: false }); + prepared.password = ""; + if (!login.ok) throw Error(); + cookie = login.headers.get("set-cookie")?.split(";")[0] ?? ""; + if (!cookie) throw Error(); + const me = await request("/me"); if (!me.ok) throw Error(); + csrf = (await me.json()).csrfToken; if (!csrf) throw Error(); + code = "workspace_reconciliation_required"; + const source = await request("/installation/workspace-source", prepared.source); + if (!source.ok) throw Error(); + const { revision } = await source.json(); + for (const entry of prepared.databases) { + code = "binding_import_failed"; + const response = await request("/installation/bindings", { ...entry, revision }); + if (response.status === 409) code = "binding_reconciliation_required"; + if (response.status === 422) code = "container_connection_failed"; + if (!response.ok) throw Error(); + const value = await response.json(); + if (value.connectionStatus !== "reachable" || !["applied", "unchanged"].includes(value.status)) throw Error(); + completed++; + } + code = "bindings_ready"; +} catch { process.exitCode = 1; } +finally { + if (cookie && csrf) { try { await request("/auth/logout", {}); } catch {} } + process.stdout.write(JSON.stringify({ ok: code === "bindings_ready", code, completed })); +} +} diff --git a/tools/tht/internal/installapply/run.go b/tools/tht/internal/installapply/run.go index 7941fcb7..52058387 100644 --- a/tools/tht/internal/installapply/run.go +++ b/tools/tht/internal/installapply/run.go @@ -25,12 +25,14 @@ import ( type Request struct{ PlanPath, InstallationPath string } type Result struct { - SchemaVersion int `json:"schema_version"` - PlatformReady bool `json:"platform_ready"` - WorkspaceReady bool `json:"workspace_ready"` - Stage string `json:"stage"` - Action string `json:"action"` - Journal string `json:"journal,omitempty"` + SchemaVersion int `json:"schema_version"` + PlatformReady bool `json:"platform_ready"` + WorkspaceReady bool `json:"workspace_ready"` + BindingsReady bool `json:"bindings_ready"` + BindingImport *BindingReport `json:"binding_import,omitempty"` + Stage string `json:"stage"` + Action string `json:"action"` + Journal string `json:"journal,omitempty"` } type journal struct { SchemaVersion int `json:"schema_version"` @@ -88,6 +90,11 @@ func Run(ctx context.Context, request Request, runner compose.Runner, check Chec if _, err := preflight.ReadExecutionPlan(request.PlanPath); err != nil { return fail("validation", "Inputs changed during checks; repeat planning before execution.") } + payload, err := bindingPayload(plan) + if err != nil { + return fail("bootstrap-input", err.Error()) + } + defer clear(payload) result.Journal = filepath.Join(installation.ControlDirectory(), "installation-apply.json") state := journal{SchemaVersion: 1, Installation: installation.Path, ReleaseRevision: plan.Release.Revision, PlanSeal: plan.InputSeal} if _, err := os.Lstat(result.Journal); err == nil { @@ -194,6 +201,13 @@ func Run(ctx context.Context, request Request, runner compose.Runner, check Chec } return docker(time.Minute, "exec", "-T", "core", "node", "--input-type=module", "-e", runtimeCheck) }}, + {"bindings", func() error { + result.PlatformReady = true + report, err := importBindings(ctx, plan, runner, payload) + result.BindingImport = &report + result.BindingsReady = err == nil + return err + }}, } // Reconcile each idempotent stage against Docker/migration authority on every retry. // A journal entry alone is never proof that a container or migration still exists. @@ -203,8 +217,8 @@ func Run(ctx context.Context, request Request, runner compose.Runner, check Chec } } result.PlatformReady = true - result.Stage = "platform-ready" - result.Action = "Platform is running. Import prepared database bindings and complete workspace readiness before a human-reviewed question." + result.Stage = "bindings-ready" + result.Action = "Platform and prepared database bindings are ready. Complete workspace readiness before a human-reviewed question." return result, nil } diff --git a/tools/tht/internal/installapply/run_test.go b/tools/tht/internal/installapply/run_test.go index 6856382a..3b7894ec 100644 --- a/tools/tht/internal/installapply/run_test.go +++ b/tools/tht/internal/installapply/run_test.go @@ -40,7 +40,7 @@ func fixture(t *testing.T) (string, preflight.Plan) { b, _ := os.ReadFile(p) write(p, strings.ReplaceAll(string(b), "https://CHANGE_ME/workspaces.git", "https://example.com/workspaces.git")) } - for name, value := range map[string]string{"secrets.env": "OPENAI_API_KEY=PRIVATE_SENTINEL\n", "git-credentials": "", "git-ca.pem": "", "database-password": "PRIVATE_SENTINEL"} { + for name, value := range map[string]string{"secrets.env": "OPENAI_API_KEY=PRIVATE_SENTINEL\n", "git-credentials": "", "git-ca.pem": "", "database-password": "PRIVATE_SENTINEL\n"} { write(filepath.Join(dir, "secrets", name), value) } installation, err := config.LoadPrepared(filepath.Join(dir, "thothii-installation.yaml")) @@ -66,7 +66,11 @@ func fixture(t *testing.T) (string, preflight.Plan) { b, _ := json.Marshal(m) write(manifest, string(b)) inputs = append(inputs, manifest) - p := preflight.Plan{SchemaVersion: 1, ValidatorProtocol: 1, Installation: installation, Release: m, ManifestPath: manifest, BootstrapPath: filepath.Join(dir, "database-bootstrap.yaml"), Platform: "linux/amd64", Inputs: inputs, AbsentInputs: preflight.AbsentOverrides(installation), Report: preflight.NewReport()} + workspace := filepath.Join(root, "workspaces") + _ = os.Mkdir(workspace, 0o700) + write(filepath.Join(workspace, "thoth-workspaces.yaml"), "schema_version: 1\nworkspaces: []\n") + inputs = append(inputs, filepath.Join(workspace, "thoth-workspaces.yaml"), filepath.Join(dir, "secrets/admin-password"), filepath.Join(dir, "secrets/database-password"), filepath.Join(dir, "database-bootstrap.yaml")) + p := preflight.Plan{SchemaVersion: 1, ValidatorProtocol: 1, Installation: installation, Release: m, ManifestPath: manifest, BootstrapPath: filepath.Join(dir, "database-bootstrap.yaml"), WorkspaceDirectory: workspace, WorkspaceRevision: "content-snapshot", Platform: "linux/amd64", Inputs: inputs, AbsentInputs: preflight.AbsentOverrides(installation), Report: preflight.NewReport()} path := filepath.Join(dir, "plan.json") if err := preflight.WritePlan(path, &p); err != nil { t.Fatal(err) @@ -82,7 +86,22 @@ type dockerFixture struct { func (r *dockerFixture) Run(_ context.Context, args []string, input io.Reader) (compose.Result, error) { if input != nil { - return compose.Result{}, fmt.Errorf("unexpected interactive input") + if args[len(args)-1] != bindingClient { + return compose.Result{}, fmt.Errorf("unexpected interactive input") + } + command := strings.Join(args, " ") + if !strings.Contains(command, " run --rm -T --no-deps --pull never --name ") || !strings.Contains(command, " --entrypoint node core ") { + return compose.Result{}, fmt.Errorf("import must use a named one-shot for cancellation cleanup") + } + data, err := io.ReadAll(input) + if err != nil || !strings.Contains(string(data), "PRIVATE_SENTINEL") || strings.Contains(strings.Join(args, " "), "PRIVATE_SENTINEL") { + return compose.Result{}, fmt.Errorf("invalid protected pipe") + } + if strings.Contains(string(data), `PRIVATE_SENTINEL\n`) { + return compose.Result{}, fmt.Errorf("file newline leaked into scalar credential") + } + r.calls = append(r.calls, append([]string{}, args...)) + return compose.Result{Stdout: `{"ok":true,"code":"bindings_ready","completed":1}`}, nil } r.calls = append(r.calls, append([]string{}, args...)) line := strings.Join(args, " ") diff --git a/tools/tht/internal/preflight/plan.go b/tools/tht/internal/preflight/plan.go index 57091b79..b4bfcce2 100644 --- a/tools/tht/internal/preflight/plan.go +++ b/tools/tht/internal/preflight/plan.go @@ -237,6 +237,9 @@ func CollectInputs(installation config.Installation, workspace, bootstrap, manif return nil, "", invalidPlan() } var bindings struct { + Authentication struct { + PasswordFile string `yaml:"passwordFile"` + } `yaml:"authentication"` Databases []struct { SecretFiles map[string]string `yaml:"secretFiles"` EvidenceSecretFiles map[string]string `yaml:"evidenceSecretFiles"` @@ -245,6 +248,9 @@ func CollectInputs(installation config.Installation, workspace, bootstrap, manif if yaml.Unmarshal(data, &bindings) != nil { return nil, "", invalidPlan() } + if bindings.Authentication.PasswordFile != "" { + paths = append(paths, bindings.Authentication.PasswordFile) + } for _, entry := range bindings.Databases { for _, values := range []map[string]string{entry.SecretFiles, entry.EvidenceSecretFiles} { for _, path := range values { diff --git a/tools/tht/internal/preparation/documents.go b/tools/tht/internal/preparation/documents.go index 6a01e6ea..b93bee88 100644 --- a/tools/tht/internal/preparation/documents.go +++ b/tools/tht/internal/preparation/documents.go @@ -66,6 +66,9 @@ overrides: [%s] } bootstrap := fmt.Sprintf(`# Bootstrap input only; PostgreSQL Metadata Catalog remains the runtime authority. schemaVersion: 1 +authentication: + username: admin + passwordFile: %s databases: - workspaceId: CHANGE_ME engine: postgres @@ -78,7 +81,7 @@ databases: username: CHANGE_ME secretFiles: password: %s -`, root("secrets/database-password")) +`, root("secrets/admin-password"), root("secrets/database-password")) documents := map[string]string{ ".gitignore": "*\n", "thothii-installation.yaml": installation, "operator.env": environment, diff --git a/tools/tht/internal/preparation/validation.go b/tools/tht/internal/preparation/validation.go index f0b92e52..039c089d 100644 --- a/tools/tht/internal/preparation/validation.go +++ b/tools/tht/internal/preparation/validation.go @@ -5,6 +5,7 @@ import ( "encoding/json" "io" "regexp" + "slices" "strconv" "strings" @@ -32,6 +33,32 @@ type Report struct { func NewReport() Report { return Report{SchemaVersion: 1, Scope: "application-documents", Issues: []Issue{}, Warnings: []string{}, DeferredChecks: []string{"release-assets", "external-connectivity", "catalog-import", "runtime-readiness"}} } + +// Validate the prepared administrative login offline; execution still uses the normal login API. +func CheckBootstrapAuthentication(installation config.Installation, path string, report *Report) { + data, err := safeio.ReadCanonicalPrivateRegular(path, 1<<20) + var doc struct { + Authentication struct { + Username string `yaml:"username"` + PasswordFile string `yaml:"passwordFile"` + } `yaml:"authentication"` + } + valid := err == nil && yaml.Unmarshal(data, &doc) == nil && doc.Authentication.Username != "" + password, passwordErr := safeio.ReadCanonicalPrivateRegular(doc.Authentication.PasswordFile, 4096) + auth, users, authErr := authconfig.Load(installation.AuthenticationDirectory()) + matched := false + if valid && passwordErr == nil && authErr == nil && auth.Mode == "local" { + for _, user := range users.Users { + if strings.EqualFold(user.Username, doc.Authentication.Username) && user.Enabled && slices.Contains(user.Roles, authconfig.RoleAdmin) { + matched = authconfig.VerifyPassword([]byte(strings.TrimSpace(string(password))), user.PasswordHash) + } + } + } + clear(password) + if !matched { + report.Add("database-bootstrap.yaml", "authentication", "bootstrap_authentication_invalid", "Prepare an enabled local administrator username and its protected passwordFile before setup; both must match the authentication documents.") + } +} func (r *Report) Add(document, field, code, correction string) { r.OK = false r.Issues = append(r.Issues, Issue{document, field, code, correction})