feat: import prepared Catalog bindings through authenticated services
This commit is contained in:
@@ -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,
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
}
|
||||
@@ -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> {
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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>;
|
||||
|
||||
@@ -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" });
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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<string, string> = {}) {
|
||||
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<void>(resolve => { entered = resolve; });
|
||||
const continueCreation = new Promise<void>(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(); }
|
||||
});
|
||||
@@ -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<string, string> = {
|
||||
"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"]);
|
||||
});
|
||||
Reference in New Issue
Block a user