Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
977cf0e978 | ||
|
|
af6cf88b5a | ||
|
|
5c05778614 | ||
|
|
785d96ea50 | ||
|
|
af4c7b5df9 | ||
|
|
d720da721b | ||
|
|
24b03d4caf | ||
|
|
2aac228cdc | ||
|
|
d79e261e09 | ||
|
|
8b9a086fd6 | ||
|
|
c3c9f509bf | ||
|
|
931ac2fad4 |
+48
-9
@@ -1,6 +1,6 @@
|
||||
# Project state
|
||||
|
||||
Updated: 2026-09-28. This is a current snapshot, not a release diary. Stable commands
|
||||
Updated: 2026-10-06. This is a current snapshot, not a release diary. Stable commands
|
||||
and invariants are in [AGENTS.md](AGENTS.md); prior snapshots remain in Git.
|
||||
|
||||
## Current contracts
|
||||
@@ -16,8 +16,39 @@ and invariants are in [AGENTS.md](AGENTS.md); prior snapshots remain in Git.
|
||||
bindings. Ticket #45 adds host `installation preflight` and `installation plan`
|
||||
with release/image checks, canonical external diagnostics and private input seals;
|
||||
see [the preflight reference](docs/install/installation-preflight.md).
|
||||
The remainder of the installation tickets,
|
||||
Docker Hub publication and example databases remain pending.
|
||||
Ticket #46 adds the maintainer release producer and the first public
|
||||
[Linux amd64 prerelease](https://git.tylconsulting.it/mptyl/ThothII/releases/tag/installation-v0.1.0-install-preview.1),
|
||||
with Docker Hub core/frontend images and a downloadable native operator bundle.
|
||||
See [publication instructions](docs/install/publishing-images.md) and
|
||||
[verification evidence](docs/reports/2026-09-28-installation-prerelease.md).
|
||||
Ticket #47 delivers `installation apply --plan PATH`: fresh checks, immutable
|
||||
pulls, local operator UID, resumable volume initialization, Catalog/Memory migrations
|
||||
and service/authentication health. Tests cover the public native command with closed
|
||||
stdin and Linux volume/private-secret behavior using published images. Platform success
|
||||
explicitly leaves workspace readiness false. The current
|
||||
[preview.5 release](https://git.tylconsulting.it/mptyl/ThothII/releases/tag/installation-v0.1.0-install-preview.5)
|
||||
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).
|
||||
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.
|
||||
Ticket #49 adds existing durable Catalog Sync Runs and preprocessing to apply,
|
||||
preserving human review (exit 3), curated content and Memory. Named one-shot checks
|
||||
cover workspace diagnostics, workflow configuration and Pi/default-model smoke.
|
||||
Reports distinguish platform, binding, workspace readiness and manual functional
|
||||
acceptance. This increment also requires a later release than preview.5.
|
||||
Ticket #50 adds an explicit `prepare-source-installation.mjs` producer from an
|
||||
isolated committed worktree. Source bundles pin local application image IDs and
|
||||
upstream Docker Hub digests; the same native plan/apply path verifies provenance,
|
||||
shares journal/locks and never falls back to a build. Ticket #51 adds guarded
|
||||
interrupted preprocessing recovery, fencing of delayed/orphan workers and preserved
|
||||
pending schema review even during binding retry. Real-host
|
||||
acceptance and curated examples remain pending. Earlier previews are superseded
|
||||
for platform apply; no complete installer/OS acceptance is claimed.
|
||||
|
||||
- React supports full/embedded rendering independently of local/OIDC/upstream auth,
|
||||
with EN/IT UI and immutable session interaction language. See
|
||||
@@ -43,11 +74,13 @@ and invariants are in [AGENTS.md](AGENTS.md); prior snapshots remain in Git.
|
||||
|
||||
## Installation and workspace boundaries
|
||||
|
||||
Fresh standalone installations follow the manual terminal procedures in
|
||||
Fresh standalone installations follow the document-first procedures in
|
||||
[Italian](docs/install/standalone-manual-it.md) or
|
||||
[English](docs/install/standalone-manual-en.md), without an installer or launcher.
|
||||
[English](docs/install/standalone-manual-en.md). The guides retain a separate manual
|
||||
source path; do not mix its setup commands with a released-bundle installation.
|
||||
The [Compose reference](docs/operations/compose-reference.md) is for maintainers,
|
||||
not another quick start. Catalog and Memory migrations are explicit.
|
||||
not another quick start. Document-first apply runs Catalog and Memory migrations
|
||||
before bringing up application services.
|
||||
|
||||
Descriptors, authentication, provider credentials, certificates and runtime bindings
|
||||
stay in protected installation-local paths. Do not copy secrets into examples or
|
||||
@@ -80,8 +113,14 @@ A later deployment does not prove every earlier acceptance item passed.
|
||||
|
||||
## Remaining acceptance and design gates
|
||||
|
||||
- Fresh-machine Mac, Windows/WSL2 and Linux installation acceptance, including real
|
||||
DWH/model endpoints, remains a separate operator exercise.
|
||||
- The first installation acceptance uses an ad hoc
|
||||
[Chinook workspace without Evidence](docs/testing/chinook-installation-smoke.md),
|
||||
backed by a separate local PostgreSQL test container. Its fixture import,
|
||||
read-only credentials, offline validation and platform apply were verified; binding
|
||||
import, workspace readiness and a human-reviewed question remain pending. Evidence
|
||||
acceptance and the three curated examples are separate later work.
|
||||
- Fresh-machine installation acceptance, including real DWH/model endpoints, remains
|
||||
a separate operator exercise, ordered Windows/WSL2, then Omarchy, then macOS.
|
||||
- Real IdP/portal login, logout, embedded interaction and PSD semantic acceptance
|
||||
follow the [manual matrix](docs/testing/authentication-manual-acceptance.md) and
|
||||
delivery reports; synthetic tests do not close them.
|
||||
@@ -98,7 +137,7 @@ A later deployment does not prove every earlier acceptance item passed.
|
||||
|
||||
## Documentation maintenance
|
||||
|
||||
MkDocs publishes only 20 product/operator pages and five approved assets.
|
||||
MkDocs publishes only 22 product/operator pages and five approved assets.
|
||||
Architecture, contracts, ADRs, plans, research, tests and release evidence are
|
||||
excluded from HTML and search. The repository itself is public: editorial exclusion
|
||||
is not confidentiality.
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
#!/usr/bin/env node
|
||||
// Explicit advanced producer. The resulting bundle uses the ordinary document-first apply path.
|
||||
import { mkdirSync, mkdtempSync, realpathSync, existsSync, readFileSync, rmSync, copyFileSync, chmodSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { parse } from 'yaml';
|
||||
import { prepareBundle } from './release-bundle.mjs';
|
||||
import { commandRunner } from './publish-installation.mjs';
|
||||
import { dockerHub } from './release-registry.mjs';
|
||||
|
||||
const repositoryRoot = resolve(import.meta.dirname, '../..');
|
||||
export function sourceOptions(args) {
|
||||
const values = {};
|
||||
for (let i = 0; i < args.length; i += 2) {
|
||||
if (!['--revision', '--version', '--platform', '--output'].includes(args[i]) || !args[i + 1] || values[args[i]]) throw new Error('Use --revision COMMIT --version VERSION --platform linux/amd64|linux/arm64 --output NEW_DIRECTORY.');
|
||||
values[args[i]] = args[i + 1];
|
||||
}
|
||||
if (!values['--revision'] || values['--revision'].startsWith('-') || !/^[0-9]+\.[0-9]+\.[0-9]+(?:-[A-Za-z0-9.-]+)?$/.test(values['--version'] ?? '') || !['linux/amd64', 'linux/arm64'].includes(values['--platform']) || !values['--output']) throw new Error('Select an explicit source revision, version, Linux platform and new output directory.');
|
||||
return { revision: values['--revision'], version: values['--version'], platform: values['--platform'], output: resolve(values['--output']) };
|
||||
}
|
||||
|
||||
export async function buildSourceImages({ run, source, output, revision, version, platform }) {
|
||||
const images = {};
|
||||
for (const role of ['core', 'frontend']) {
|
||||
const iid = join(output, `${role}.iid`);
|
||||
const localTag = `thothii-source-${role}:${randomBytes(16).toString('hex')}`;
|
||||
await run('docker', ['buildx', 'build', '--load', '--tag', localTag, '--platform', platform, '--file', `docker/${role}.Dockerfile`,
|
||||
'--iidfile', iid, '--build-arg', `IMAGE_VERSION=${version}`, '--label', `org.opencontainers.image.revision=${revision}`,
|
||||
'--label', `org.opencontainers.image.version=${version}`, '--provenance=false', '--sbom=false', '.'], { cwd: source, timeout: 45 * 60_000 });
|
||||
const id = readFileSync(iid, 'utf8').trim();
|
||||
if (!/^sha256:[a-f0-9]{64}$/.test(id)) throw new Error('Source build did not produce an immutable local image identity.');
|
||||
// Containerd and classic Docker stores expose different IDs; resolve the local
|
||||
// daemon identity through our unique build tag, then pin that immutable ID.
|
||||
const image = JSON.parse(await run('docker', ['image', 'inspect', '--format', '{{json .}}', localTag], { quiet: true }));
|
||||
if (!/^sha256:[a-f0-9]{64}$/.test(image.Id ?? '') || `${image.Os}/${image.Architecture}` !== platform || image.Config?.Labels?.['org.opencontainers.image.revision'] !== revision || image.Config?.Labels?.['org.opencontainers.image.version'] !== version) throw new Error('Built image identity differs from the selected source.');
|
||||
images[role] = image.Id;
|
||||
}
|
||||
return images;
|
||||
}
|
||||
|
||||
export async function prepareSourceInstallation(options) {
|
||||
// mkdir is exclusive: never replace a bundle or mix an incomplete previous build with new inputs.
|
||||
mkdirSync(options.output, { mode: 0o700 });
|
||||
if (realpathSync(options.output) !== options.output) throw new Error('Use a canonical output path.');
|
||||
const logs = join(options.output, 'logs'); mkdirSync(logs, { mode: 0o700 });
|
||||
const run = commandRunner(logs);
|
||||
let temporary, source;
|
||||
try {
|
||||
const revision = (await run('git', ['rev-parse', '--verify', `${options.revision}^{commit}`], { quiet: true })).trim();
|
||||
if (!/^[a-f0-9]{40}$/.test(revision)) throw new Error('Select a committed source revision.');
|
||||
await run('docker', ['info', '--format', '{{.OSType}}']);
|
||||
await run('docker', ['buildx', 'version']);
|
||||
temporary = realpathSync(mkdtempSync(join(tmpdir(), 'thothii-source-')));
|
||||
source = join(temporary, 'source');
|
||||
await run('git', ['worktree', 'add', '--detach', source, revision]);
|
||||
console.log(`Building explicit source installation ${revision} for ${options.platform}.`);
|
||||
const images = await buildSourceImages({ run, source, output: options.output, revision, version: options.version, platform: options.platform });
|
||||
const compose = parse(readFileSync(join(source, 'compose.yaml'), 'utf8'));
|
||||
const registry = dockerHub();
|
||||
for (const [role, service] of [['catalog', 'catalog-db'], ['qdrant', 'qdrant'], ['embedding', 'embedding']]) {
|
||||
const [name, digest] = compose.services[service].image.split('@');
|
||||
if (!/^sha256:[a-f0-9]{64}$/.test(digest ?? '')) throw new Error('Upstream source images must already be pinned.');
|
||||
let repository = name.replace(/:[^/:]+$/, '').replace(/^docker.io\//, '');
|
||||
if (!repository.includes('/')) repository = `library/${repository}`;
|
||||
images[role] = (await registry.inspect(repository, digest, options.platform, { anonymous: true })).reference;
|
||||
}
|
||||
await run('npm', ['ci'], { cwd: join(source, 'backend'), timeout: 10 * 60_000 });
|
||||
const target = options.platform.replace('/', '-');
|
||||
const sourceTime = (await run('git', ['show', '-s', '--format=%cI', revision], { quiet: true })).trim();
|
||||
await run(process.execPath, [join(repositoryRoot, 'backend/scripts/build-workspace-tools.mjs'), target], {
|
||||
cwd: join(source, 'backend'), env: { ...process.env, THT_BUILD_SOURCE_ROOT: source, THT_BUILD_VERSION: options.version, THT_BUILD_TIME: sourceTime }, timeout: 10 * 60_000,
|
||||
});
|
||||
const bundle = join(options.output, 'bundle'); mkdirSync(bundle, { mode: 0o700 });
|
||||
prepareBundle({ source, destination: bundle, platform: options.platform, version: options.version, revision, images, distribution: 'source' });
|
||||
mkdirSync(join(bundle, 'bin'));
|
||||
for (const executable of ['tht', 'tht-workspace-documents']) {
|
||||
copyFileSync(join(source, 'dist/workspace-tools', target, executable), join(bundle, 'bin', executable));
|
||||
chmodSync(join(bundle, 'bin', executable), 0o755);
|
||||
}
|
||||
await run('docker', ['compose', '-f', join(bundle, 'compose.yaml'), '-f', join(bundle, 'deploy/compose.local.yaml'), '--profile', 'catalog-maintenance', '--profile', 'workspace-maintenance', 'config', '--no-interpolate', '--no-env-resolution', '--format', 'json']);
|
||||
console.log(`Source bundle prepared: ${bundle}. Use its operator for ordinary installation validate, plan and apply on this Docker daemon.`);
|
||||
return bundle;
|
||||
} finally {
|
||||
if (source && existsSync(source)) await run('git', ['worktree', 'remove', '--force', source]).catch(() => {});
|
||||
if (temporary && !existsSync(source ?? '')) rmSync(temporary, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
|
||||
try { await prepareSourceInstallation(sourceOptions(process.argv.slice(2))); }
|
||||
catch { console.error('Source preparation failed. Inspect the private build logs and use a new output directory to retry; no images were published.'); process.exitCode = 1; }
|
||||
}
|
||||
@@ -95,7 +95,7 @@ export async function publishInstallation(options) {
|
||||
await run('docker', ['info', '--format', '{{.OSType}}']);
|
||||
await run('docker', ['buildx', 'version']);
|
||||
const registry = dockerHub(await dockerCredentials(run));
|
||||
const hosting = await giteaHosting({ run, repository: options.repository, identity, body: `Installer prerelease for ${identity.platforms.join(', ')}.\n\nImages: docker.io/${identity.namespace}/thothii-core:${identity.version} and docker.io/${identity.namespace}/thothii-frontend:${identity.version}.\n\nDownload the native operator bundle and SHA256SUMS.txt below. This release supplies images, document validation and preflight; complete non-interactive setup and Windows/Omarchy/macOS acceptance are subsequent tickets. No example databases, credentials or user workspace data are included.` });
|
||||
const hosting = await giteaHosting({ run, repository: options.repository, identity, body: `Installer prerelease for ${identity.platforms.join(', ')}.\n\nImages: docker.io/${identity.namespace}/thothii-core:${identity.version} and docker.io/${identity.namespace}/thothii-frontend:${identity.version}.\n\nDownload the native operator bundle and SHA256SUMS.txt below. This release supplies images, document validation, preflight, non-interactive platform apply, prepared binding import and workspace/runtime readiness checks. Destructive schema review remains a human decision. Windows/Omarchy/macOS and human-reviewed question acceptance remain subsequent steps. No example databases, credentials or user workspace data are included.` });
|
||||
async function prepare() {
|
||||
if (state.assets) {
|
||||
const names = [...identity.platforms.map((platform) => `thothii-${identity.version}-${platform.replace('/', '-')}.tar.gz`), 'SHA256SUMS.txt'];
|
||||
@@ -157,7 +157,7 @@ export async function publishInstallation(options) {
|
||||
chmodSync(join(bundle, 'bin', executable), 0o755);
|
||||
}
|
||||
// Resolve source-independent resource/config shape without any operator credentials.
|
||||
await run('docker', ['compose', '-f', join(bundle, 'compose.yaml'), '-f', join(bundle, 'deploy/compose.local.yaml'), 'config', '--no-interpolate', '--no-env-resolution', '--format', 'json']);
|
||||
await run('docker', ['compose', '-f', join(bundle, 'compose.yaml'), '-f', join(bundle, 'deploy/compose.local.yaml'), '--profile', 'catalog-maintenance', '--profile', 'workspace-maintenance', 'config', '--no-interpolate', '--no-env-resolution', '--format', 'json']);
|
||||
const archive = join(options.output, name + '.tar.gz');
|
||||
await run('tar', ['-czf', archive, '-C', options.output, name]);
|
||||
assets.push({ name: basename(archive), path: archive, bytes: statSync(archive).size, sha256: sha256(readFileSync(archive)) });
|
||||
|
||||
@@ -7,11 +7,14 @@ export const serviceRoles = Object.freeze({ core: "core", frontend: "frontend",
|
||||
export const sha256 = (data) => createHash("sha256").update(data).digest("hex");
|
||||
|
||||
/** Only distribution assets enter the bundle: never a checkout, environment file or workspace. */
|
||||
export function prepareBundle({ source, destination, platform, version, revision, images }) {
|
||||
export function prepareBundle({ source, destination, platform, version, revision, images, distribution = "prebuilt" }) {
|
||||
if (!["prebuilt", "source"].includes(distribution)) throw new Error("Unknown installation distribution.");
|
||||
const compose = parse(readFileSync(join(source, "compose.yaml"), "utf8"));
|
||||
if (Object.keys(compose.services).sort().join() !== Object.keys(serviceRoles).sort().join()) throw new Error("Release service contract changed; review packaging before publishing.");
|
||||
for (const [name, role] of Object.entries(serviceRoles)) {
|
||||
if (!/^docker\.io\/[a-z0-9][a-z0-9._/-]*@sha256:[a-f0-9]{64}$/.test(images[role] ?? "")) throw new Error("Release requires immutable Docker Hub image references.");
|
||||
const local = distribution === "source" && ["core", "frontend"].includes(role);
|
||||
const pattern = local ? /^sha256:[a-f0-9]{64}$/ : /^docker\.io\/[a-z0-9][a-z0-9._/-]*@sha256:[a-f0-9]{64}$/;
|
||||
if (!pattern.test(images[role] ?? "")) throw new Error("Release requires immutable image references for its distribution.");
|
||||
delete compose.services[name].build;
|
||||
delete compose.services[name].pull_policy;
|
||||
compose.services[name].image = images[role];
|
||||
@@ -37,12 +40,35 @@ export function prepareBundle({ source, destination, platform, version, revision
|
||||
}
|
||||
}
|
||||
const manifest = { schema_version: 1, version, revision, validator_protocol: 1,
|
||||
...(distribution === "source" ? { distribution } : {}),
|
||||
requirements: { cpus: 2, memory_bytes: 4 * 2 ** 30, disk_bytes: 10 * 2 ** 30 },
|
||||
components: ["pi", "catalog-migrations", "workspace-maintenance"],
|
||||
images: Object.fromEntries(Object.entries(images).map(([role, reference]) => [role, { [platform]: reference }])),
|
||||
files, compose: ["compose.yaml", "deploy/compose.local.yaml"] };
|
||||
writeFileSync(join(destination, "release-manifest.json"), JSON.stringify(manifest, null, 2) + "\n");
|
||||
writeFileSync(join(destination, "README.md"), `# ThothII ${version} — ${platform}\n\nSource / Sorgente: ${revision}\n\nThis prerelease provides images and document/preflight tools. Non-interactive execution and real-host acceptance are separate follow-up tickets; this is not a certified complete installation.\nQuesta prerelease fornisce immagini e strumenti di preparazione/preflight. Esecuzione non interattiva e collaudi reali sono incrementi successivi: non è ancora un'installazione completa certificata.\n\nUse bin/tht and its sibling bin/tht-workspace-documents together; no Node, Python, Bun or application checkout is required on the consumer host.\nWindows: use the Linux amd64 bundle inside Ubuntu WSL2, not a native Windows shell.\n\n1. bin/tht workspace prepare --directory NEW_WORKSPACE --id practice --name Practice\n2. bin/tht workspace validate --directory WORKSPACE\n3. bin/tht installation prepare --directory NEW_PRIVATE_INSTALLATION\n4. bin/tht installation preflight --directory INSTALLATION --release ABSOLUTE_RELEASE_DIR/release-manifest.json\n5. Complete the commented documents, generate technical credentials explicitly, then run installation validate and installation plan with --installation ABSOLUTE_INSTALLATION_FILE.\n\nImages are pinned by digest; runtime credentials and user workspaces are never bundled.\nConsult the accompanying IT/EN guides for prepared documents and mandatory runtime checks.\n`);
|
||||
writeFileSync(join(destination, "README.md"), `# ThothII ${version} — ${platform}
|
||||
|
||||
Source / Sorgente: ${revision}
|
||||
|
||||
Distribution / Distribuzione: ${distribution}. ${distribution === 'source' ? 'Application images are local to the producer Docker daemon; this bundle is not a public image release. Le immagini applicative sono locali al daemon Docker del produttore.' : 'Application images are downloaded from Docker Hub. Le immagini applicative vengono scaricate da Docker Hub.'}
|
||||
|
||||
This prerelease provides images, document/preflight tools, non-interactive platform apply, prepared binding import and workspace/runtime readiness checks. A pending destructive schema review stops apply for a human decision. Windows/Omarchy/macOS and human-reviewed question acceptance remain separate; this is not a certified complete installation.
|
||||
Questa prerelease fornisce immagini, preparazione/preflight, avvio non interattivo, import dei binding e controlli di readiness workspace/runtime. Una revisione distruttiva dello schema ferma apply per una decisione umana. Collaudi Windows/Omarchy/macOS e domanda con revisione umana restano separati: non è ancora un'installazione completa certificata.
|
||||
|
||||
Use bin/tht and its sibling bin/tht-workspace-documents together; no Node, Python, Bun or application checkout is required on the consumer host.
|
||||
Windows: use the Linux amd64 bundle inside Ubuntu WSL2, not a native Windows shell.
|
||||
Run as the same non-root operator that prepared the documents, with access to local Docker.
|
||||
|
||||
1. bin/tht workspace prepare --directory NEW_WORKSPACE --id practice --name Practice
|
||||
2. bin/tht workspace validate --directory WORKSPACE
|
||||
3. bin/tht installation prepare --directory NEW_PRIVATE_INSTALLATION
|
||||
4. bin/tht installation preflight --directory INSTALLATION --release ABSOLUTE_RELEASE_DIR/release-manifest.json
|
||||
5. Complete the commented documents, generate technical credentials explicitly, then run installation validate and installation plan with --installation ABSOLUTE_INSTALLATION_FILE.
|
||||
6. bin/tht --installation ABSOLUTE_INSTALLATION_FILE installation apply --plan ABSOLUTE_PLAN --json
|
||||
|
||||
Images are pinned by digest; runtime credentials and user workspaces are never bundled.
|
||||
Consult the accompanying IT/EN guides for prepared documents, retry behavior and mandatory runtime checks.
|
||||
`);
|
||||
for (const [name, target] of [["standalone-manual-it.md", "GUIDE-IT.md"], ["standalone-manual-en.md", "GUIDE-EN.md"], ["installation-preflight.md", "PREFLIGHT.md"]]) writeFileSync(join(destination, target), readFileSync(join(source, "docs/install", name)));
|
||||
return manifest;
|
||||
}
|
||||
|
||||
@@ -17,6 +17,11 @@ test("consumer bundle pins every service and carries all source bind resources",
|
||||
assert.equal(compose.services["catalog-migrate"].image, images.core);
|
||||
assert.equal(compose.services["workspace-maintenance"].image, images.core);
|
||||
assert.equal(compose.services["embedding-model-init"].image, images.embedding);
|
||||
// Both session commands and maintenance must retain local identity under a
|
||||
// writable shared volume when the installer maps the operator's Unix UID.
|
||||
assert.equal(compose.services.core.environment.THT_HOME, "/data/sessions/.thothii");
|
||||
assert.equal(compose.services["workspace-maintenance"].environment.THT_HOME,
|
||||
compose.services.core.environment.THT_HOME);
|
||||
for (const service of Object.values(compose.services)) {
|
||||
assert.equal(service.build, undefined);
|
||||
assert.equal(service.pull_policy, undefined);
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { prepareBundle } from './release-bundle.mjs';
|
||||
import { buildSourceImages, sourceOptions } from './prepare-source-installation.mjs';
|
||||
|
||||
test('source builds load local images from the isolated checkout without publication or secrets', async () => {
|
||||
const output = mkdtempSync(join(tmpdir(), 'source-build-'));
|
||||
const calls = [];
|
||||
const revision = 'c'.repeat(40), version = '1.0.0-source', platform = 'linux/amd64';
|
||||
const run = async (command, args, options) => {
|
||||
calls.push({ command, args, options });
|
||||
if (args[0] === 'buildx') {
|
||||
assert.equal(options.cwd, '/isolated/committed-source');
|
||||
assert.ok(args.includes('--load'));
|
||||
assert.ok(!args.includes('--push'));
|
||||
assert.ok(!args.includes('--secret'));
|
||||
assert.deepEqual(args.filter((_, index) => args[index - 1] === '--build-arg'), [`IMAGE_VERSION=${version}`]);
|
||||
// Containerd may expose the manifest as local Id while Buildx writes its config digest.
|
||||
writeFileSync(args[args.indexOf('--iidfile') + 1], `sha256:${'b'.repeat(64)}`);
|
||||
return '';
|
||||
}
|
||||
return JSON.stringify({ Id: `sha256:${'a'.repeat(64)}`, Os: 'linux', Architecture: 'amd64', Config: { Labels: { 'org.opencontainers.image.revision': revision, 'org.opencontainers.image.version': version } } });
|
||||
};
|
||||
try {
|
||||
assert.deepEqual(await buildSourceImages({ run, source: '/isolated/committed-source', output, revision, version, platform }), { core: `sha256:${'a'.repeat(64)}`, frontend: `sha256:${'a'.repeat(64)}` });
|
||||
assert.equal(calls.length, 4);
|
||||
assert.throws(() => sourceOptions(['--revision', 'HEAD']), /explicit/);
|
||||
} finally { rmSync(output, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
test('source bundles identify their mode and use immutable local application images', () => {
|
||||
const output = mkdtempSync(join(tmpdir(), 'source-bundle-'));
|
||||
const images = Object.fromEntries(['core', 'frontend', 'catalog', 'qdrant', 'embedding'].map(role => [role,
|
||||
['core', 'frontend'].includes(role) ? `sha256:${'a'.repeat(64)}` : `docker.io/example/${role}@sha256:${'b'.repeat(64)}`]));
|
||||
try {
|
||||
const manifest = prepareBundle({ source: resolve(import.meta.dirname, '../..'), destination: output,
|
||||
platform: 'linux/arm64', version: '0.1.0-source', revision: 'c'.repeat(40), images, distribution: 'source' });
|
||||
assert.equal(manifest.distribution, 'source');
|
||||
assert.equal(manifest.images.core['linux/arm64'], images.core);
|
||||
assert.doesNotMatch(readFileSync(join(output, 'compose.yaml'), 'utf8'), /build:/);
|
||||
assert.throws(() => prepareBundle({ source: resolve(import.meta.dirname, '../..'), destination: output,
|
||||
platform: 'linux/arm64', version: '0.1.0-source', revision: 'c'.repeat(40), images }), /immutable/);
|
||||
} finally { rmSync(output, { recursive: true, force: true }); }
|
||||
});
|
||||
@@ -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>();
|
||||
@@ -77,6 +78,7 @@ export class MemoryCatalogRepository implements CatalogRepository {
|
||||
async beginPreprocessing(
|
||||
workspaceId: string,
|
||||
inputFingerprint: string,
|
||||
runId?: string,
|
||||
): Promise<CatalogPreprocessingStartResult> {
|
||||
const database = [...this.records.values()].find((record) => record.workspaceId === workspaceId);
|
||||
if (!database) return { kind: "not_found" };
|
||||
@@ -95,6 +97,7 @@ export class MemoryCatalogRepository implements CatalogRepository {
|
||||
...database,
|
||||
preprocessingStatus: "running",
|
||||
preprocessingInputFingerprint: inputFingerprint,
|
||||
preprocessingRunId: runId,
|
||||
preprocessedMetadataRevision: undefined,
|
||||
preprocessingStartedAt: now,
|
||||
preprocessingFinishedAt: undefined,
|
||||
@@ -109,12 +112,14 @@ export class MemoryCatalogRepository implements CatalogRepository {
|
||||
metadataContentRevision: number,
|
||||
inputFingerprint: string,
|
||||
outcome: { status: "succeeded" } | { status: "failed"; errorCode: string },
|
||||
runId?: string,
|
||||
): Promise<WorkspaceDatabase | undefined> {
|
||||
const database = [...this.records.values()].find((record) => record.workspaceId === workspaceId);
|
||||
if (!database
|
||||
|| database.preprocessingStatus !== "running"
|
||||
|| database.metadataContentRevision !== metadataContentRevision
|
||||
|| database.preprocessingInputFingerprint !== inputFingerprint) return undefined;
|
||||
|| database.preprocessingInputFingerprint !== inputFingerprint
|
||||
|| database.preprocessingRunId !== runId) return undefined;
|
||||
const updated: WorkspaceDatabase = {
|
||||
...database,
|
||||
preprocessingStatus: outcome.status,
|
||||
@@ -175,13 +180,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 +196,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,8 @@ 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";
|
||||
import * as preprocessingRunIdentityMigration from "./migrations/015_preprocessing_run_identity.js";
|
||||
|
||||
const connectionString = process.env.THT_CATALOG_MIGRATOR_DATABASE_URL;
|
||||
const host = process.env.THT_CATALOG_DB_HOST;
|
||||
@@ -54,6 +56,8 @@ const provider: MigrationProvider = {
|
||||
"011_local_sensitivity_analysis": localSensitivityAnalysisMigration,
|
||||
"012_sensitivity_reason": sensitivityReasonMigration,
|
||||
"013_catalog_preprocessing_state": catalogPreprocessingStateMigration,
|
||||
"014_installation_binding_imports": installationBindingImportsMigration,
|
||||
"015_preprocessing_run_identity": preprocessingRunIdentityMigration,
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { Kysely } from "kysely";
|
||||
import type { CatalogDatabase } from "../repository.js";
|
||||
|
||||
/** Fences late completions when recovery repeats exactly the same input revision. */
|
||||
export async function up(db: Kysely<CatalogDatabase>): Promise<void> {
|
||||
await db.schema.alterTable("workspace_databases")
|
||||
.addColumn("preprocessing_run_id", "text").execute();
|
||||
}
|
||||
|
||||
export async function down(db: Kysely<CatalogDatabase>): Promise<void> {
|
||||
await db.schema.alterTable("workspace_databases")
|
||||
.dropColumn("preprocessing_run_id").execute();
|
||||
}
|
||||
@@ -76,6 +76,7 @@ interface WorkspaceDatabaseTable {
|
||||
metadataContentRevision: Generated<number>;
|
||||
preprocessingStatus: Generated<WorkspaceDatabase["preprocessingStatus"]>;
|
||||
preprocessingInputFingerprint: Generated<string | null>;
|
||||
preprocessingRunId: Generated<string | null>;
|
||||
preprocessedMetadataRevision: Generated<number | null>;
|
||||
preprocessingStartedAt: NullableTimestamp;
|
||||
preprocessingFinishedAt: NullableTimestamp;
|
||||
@@ -273,6 +274,7 @@ interface CatalogSyncEventTable {
|
||||
}
|
||||
|
||||
export interface CatalogDatabase {
|
||||
installationBindingImports: { workspaceId: string; databaseId: string; createdAt: Generated<Date> };
|
||||
workspaceDatabases: WorkspaceDatabaseTable;
|
||||
databaseBindings: DatabaseBindingTable;
|
||||
catalogTables: CatalogTableTable;
|
||||
@@ -342,6 +344,7 @@ function serialize(row: JoinedRow): WorkspaceDatabase {
|
||||
metadataContentRevision: Number(row.metadataContentRevision),
|
||||
preprocessingStatus: row.preprocessingStatus,
|
||||
preprocessingInputFingerprint: present(row.preprocessingInputFingerprint),
|
||||
preprocessingRunId: present(row.preprocessingRunId),
|
||||
preprocessedMetadataRevision: row.preprocessedMetadataRevision == null
|
||||
? undefined
|
||||
: Number(row.preprocessedMetadataRevision),
|
||||
@@ -507,6 +510,7 @@ export class KyselyCatalogRepository implements CatalogRepository {
|
||||
async beginPreprocessing(
|
||||
workspaceId: string,
|
||||
inputFingerprint: string,
|
||||
runId?: string,
|
||||
): Promise<CatalogPreprocessingStartResult> {
|
||||
return await this.db.transaction().execute(async (trx) => {
|
||||
const database = await trx.selectFrom("workspaceDatabases")
|
||||
@@ -539,6 +543,7 @@ export class KyselyCatalogRepository implements CatalogRepository {
|
||||
.set({
|
||||
preprocessingStatus: "running",
|
||||
preprocessingInputFingerprint: inputFingerprint,
|
||||
preprocessingRunId: runId ?? null,
|
||||
preprocessedMetadataRevision: null,
|
||||
preprocessingStartedAt: sql`now()`,
|
||||
preprocessingFinishedAt: null,
|
||||
@@ -556,6 +561,7 @@ export class KyselyCatalogRepository implements CatalogRepository {
|
||||
metadataContentRevision: number,
|
||||
inputFingerprint: string,
|
||||
outcome: { status: "succeeded" } | { status: "failed"; errorCode: string },
|
||||
runId?: string,
|
||||
): Promise<WorkspaceDatabase | undefined> {
|
||||
const result = await this.db.updateTable("workspaceDatabases")
|
||||
.set({
|
||||
@@ -569,6 +575,7 @@ export class KyselyCatalogRepository implements CatalogRepository {
|
||||
.where("preprocessingStatus", "=", "running")
|
||||
.where("metadataContentRevision", "=", metadataContentRevision)
|
||||
.where("preprocessingInputFingerprint", "=", inputFingerprint)
|
||||
.where("preprocessingRunId", runId === undefined ? "is" : "=", runId ?? null)
|
||||
.returning("id")
|
||||
.executeTakeFirst();
|
||||
return result ? await this.get(result.id) : undefined;
|
||||
@@ -681,10 +688,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,
|
||||
|
||||
@@ -40,6 +40,7 @@ export interface WorkspaceDatabase {
|
||||
metadataContentRevision: number;
|
||||
preprocessingStatus: CatalogPreprocessingStatus;
|
||||
preprocessingInputFingerprint?: string;
|
||||
preprocessingRunId?: string;
|
||||
preprocessedMetadataRevision?: number;
|
||||
preprocessingStartedAt?: string;
|
||||
preprocessingFinishedAt?: string;
|
||||
@@ -453,16 +454,18 @@ export interface CatalogRepository {
|
||||
beginPreprocessing(
|
||||
workspaceId: string,
|
||||
inputFingerprint: string,
|
||||
runId?: string,
|
||||
): Promise<CatalogPreprocessingStartResult>;
|
||||
finishPreprocessing(
|
||||
workspaceId: string,
|
||||
metadataContentRevision: number,
|
||||
inputFingerprint: string,
|
||||
outcome: { status: "succeeded" } | { status: "failed"; errorCode: string },
|
||||
runId?: string,
|
||||
): 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>;
|
||||
|
||||
@@ -155,7 +155,7 @@ export function createPiManagement(config: AppConfig, deps: PiManagementDeps): P
|
||||
|
||||
const installationConfig = (): PiInstallationConfig => {
|
||||
const settings = readSettings();
|
||||
const reasoning = config.defaults.thinking ?? settings.thinking;
|
||||
const reasoning = config.defaults.thinking ?? settings.thinking ?? "low";
|
||||
const selected = deps.modelCatalog.defaultInteraction
|
||||
? splitCanonicalModelId(deps.modelCatalog.defaultInteraction)
|
||||
: undefined;
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
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 CatalogOperationInProgressError) return reply.code(409).send({ code: "installation_operation_pending" });
|
||||
if (error instanceof InstallationReconciliationRequired || error instanceof CatalogConflictError) {
|
||||
return reply.code(409).send({ code: "installation_reconciliation_required" });
|
||||
}
|
||||
return reply.code(503).send({ code: "installation_binding_unavailable" });
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import type { ThtRunner } from "../tht/tht-runner.js";
|
||||
import type { WorkspacePreprocessingService } from "../workspaces/preprocessing-service.js";
|
||||
import type { PreprocessingJobState } from "../workspaces/preprocessing-state.js";
|
||||
import type { WorkspaceRegistry } from "../workspaces/registry.js";
|
||||
import { PreprocessingStateError } from "../workspaces/preprocessing-state.js";
|
||||
|
||||
const workspaceIdSchema = z.string().regex(/^[a-z][a-z0-9-]{2,62}$/);
|
||||
const ACTIVE_SYNC_STATES = new Set(["queued", "running", "awaiting_confirmation", "applying"]);
|
||||
@@ -317,6 +318,9 @@ export async function readWorkspacePreprocessingStatus(
|
||||
}
|
||||
|
||||
function safeError(reply: FastifyReply, error: unknown) {
|
||||
if (error instanceof PreprocessingStateError) {
|
||||
return reply.code(409).send({ code: "preprocessing_conflict", state: "running", message: "Preprocessing is still owned by another process." });
|
||||
}
|
||||
if (error instanceof CatalogUnavailableError) {
|
||||
return reply.code(503).send({
|
||||
code: "catalog_unavailable",
|
||||
@@ -357,7 +361,8 @@ export function workspacePreprocessingRoutes(
|
||||
try {
|
||||
const workspaceId = workspaceIdFrom(request);
|
||||
const before = await readWorkspacePreprocessingStatus(workspaceId, deps);
|
||||
if (!before.actionable) {
|
||||
const options = z.object({ recoverInterrupted: z.boolean().optional() }).strict().parse(request.body ?? {});
|
||||
if (!before.actionable && !(before.state === "running" && options.recoverInterrupted)) {
|
||||
return reply.code(409).send({ ...before, code: "preprocessing_blocked" });
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import { WorkspaceSecretStore } from "./workspaces/secret-store.js";
|
||||
import { WorkspacePreprocessingService, type WorkspaceOperationResult } from "./workspaces/preprocessing-service.js";
|
||||
import { createCatalogRepository } from "./catalog/repository.js";
|
||||
import type { CatalogRepository } from "./catalog/types.js";
|
||||
import { guardedPreprocessingCommand } from "./workspaces/preprocessing-owner.js";
|
||||
|
||||
export interface WorkspaceMaintenanceIo {
|
||||
stdin: string;
|
||||
@@ -238,7 +239,7 @@ export function createProductionWorkspacePreprocessingService(
|
||||
active.releaseSecrets();
|
||||
}
|
||||
},
|
||||
runChild: async ({ argv, configPath }) => {
|
||||
runChild: async ({ argv, configPath, guard }) => {
|
||||
const configFd = openSync(configPath, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
|
||||
try {
|
||||
return await new Promise((resolve) => {
|
||||
@@ -254,7 +255,8 @@ export function createProductionWorkspacePreprocessingService(
|
||||
"THT_CATALOG_MIGRATOR_USER",
|
||||
"THT_CATALOG_MIGRATOR_PASSWORD_FILE",
|
||||
]) delete childEnvironment[name];
|
||||
const child = spawn(config.thtBin, argv, {
|
||||
const command = guard ? guardedPreprocessingCommand(guard, config.thtBin, argv) : { executable: config.thtBin, args: argv };
|
||||
const child = spawn(command.executable, command.args, {
|
||||
cwd: config.harnessDir,
|
||||
env: { ...childEnvironment, ...(config.dataRoot ? { THT_DATA_ROOT: config.dataRoot } : {}) },
|
||||
stdio: ["ignore", "pipe", "pipe", configFd],
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { PreprocessingStateError, PreprocessingStateStore } from "./preprocessing-state.js";
|
||||
|
||||
export interface PreprocessingChildGuard {
|
||||
lockPath: string;
|
||||
tokenPath: string;
|
||||
token: string;
|
||||
}
|
||||
|
||||
// The parent lock excludes live orchestrators. Worker locks survive parent death;
|
||||
// rotating the generation under their exclusive lock fences children not yet started.
|
||||
export async function acquirePreprocessingOwner(dataRoot: string, workspaceId: string) {
|
||||
const state = new PreprocessingStateStore({ dataRoot, workspaceId });
|
||||
const owner = await state.acquireWriterLock();
|
||||
try {
|
||||
const workers = await state.acquireWriterLock("workers");
|
||||
try {
|
||||
const token = state.rotateOwnerToken();
|
||||
return { guard: { lockPath: state.workerLockPath(), tokenPath: state.ownerTokenPath(), token }, release: owner.release,
|
||||
assertOwned: () => {
|
||||
if (!owner.isHeld() || readFileSync(state.ownerTokenPath(), "utf8") !== token) throw new PreprocessingStateError("preprocessing_conflict", "Preprocessing ownership was lost");
|
||||
} };
|
||||
} finally { await workers.release(); }
|
||||
} catch (error) { await owner.release(); throw error; }
|
||||
}
|
||||
|
||||
const guardedExec = [
|
||||
"import fcntl, os, sys",
|
||||
"fd = os.open(sys.argv[1], os.O_RDWR | getattr(os, 'O_NOFOLLOW', 0))",
|
||||
"try:",
|
||||
" fcntl.flock(fd, fcntl.LOCK_SH | fcntl.LOCK_NB)",
|
||||
"except BlockingIOError:",
|
||||
" sys.exit(73)",
|
||||
"token_fd = os.open(sys.argv[2], os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0))",
|
||||
"with os.fdopen(token_fd) as token_file:",
|
||||
" if token_file.read(65) != sys.argv[3]: sys.exit(73)",
|
||||
"os.set_inheritable(fd, True)",
|
||||
"os.execvp(sys.argv[4], sys.argv[4:])",
|
||||
].join("\n");
|
||||
|
||||
export function guardedPreprocessingCommand(guard: PreprocessingChildGuard, executable: string, args: string[]) {
|
||||
return { executable: "python3", args: ["-c", guardedExec, guard.lockPath, guard.tokenPath, guard.token, executable, ...args] };
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
import type { DeterministicRuntimeConfigLease } from "./runtime-config-lease.js";
|
||||
import { buildCatalogMetadataSnapshot } from "../catalog/metadata-snapshot.js";
|
||||
import type { CatalogRepository } from "../catalog/types.js";
|
||||
import { acquirePreprocessingOwner, type PreprocessingChildGuard } from "./preprocessing-owner.js";
|
||||
|
||||
export interface WorkspaceOperationResult {
|
||||
schemaVersion: 1;
|
||||
@@ -47,6 +48,7 @@ export interface WorkspaceOperationResult {
|
||||
export interface ChildProcessRequest {
|
||||
argv: string[];
|
||||
configPath: string;
|
||||
guard?: PreprocessingChildGuard;
|
||||
}
|
||||
|
||||
interface ActiveRuntime {
|
||||
@@ -79,6 +81,7 @@ export interface WorkspacePreprocessingServiceDeps {
|
||||
}
|
||||
|
||||
interface RunScope {
|
||||
owner: Awaited<ReturnType<typeof acquirePreprocessingOwner>>;
|
||||
runtime: ActiveRuntime;
|
||||
state: PreprocessingStateStore;
|
||||
job: PreprocessingJobState;
|
||||
@@ -205,13 +208,39 @@ export class WorkspacePreprocessingService {
|
||||
const runtime = await this.deps.acquireActiveRuntime(options.workspaceId);
|
||||
return baseResult(runtime, "preprocess run", "failed", "catalog_not_ready");
|
||||
}
|
||||
return await this.runFromCatalog(options);
|
||||
const owner = await acquirePreprocessingOwner(this.deps.dataRoot, options.workspaceId);
|
||||
try {
|
||||
const previous = await this.deps.catalogRepository.getByWorkspace(options.workspaceId);
|
||||
// Only runs created under this guard protocol can be reclaimed automatically.
|
||||
const lastJob = this.state(options.workspaceId).readLatestJob();
|
||||
if (previous?.preprocessingStatus === "running" && previous.preprocessingInputFingerprint
|
||||
&& (lastJob?.ownerProtocol !== 1 || !previous.preprocessingRunId || lastJob.runId !== previous.preprocessingRunId)) {
|
||||
const runtime = await this.deps.acquireActiveRuntime(options.workspaceId);
|
||||
return baseResult(runtime, "preprocess run", "failed", "preprocessing_conflict",
|
||||
{ warnings: ["An older preprocessing owner cannot be recovered automatically."] });
|
||||
}
|
||||
if (previous?.preprocessingStatus === "running" && previous.preprocessingInputFingerprint && lastJob?.ownerProtocol === 1) {
|
||||
owner.assertOwned();
|
||||
await this.deps.catalogRepository.finishPreprocessing(options.workspaceId,
|
||||
previous.metadataContentRevision, previous.preprocessingInputFingerprint,
|
||||
{ status: "failed", errorCode: "preprocessing_interrupted" }, previous.preprocessingRunId);
|
||||
}
|
||||
owner.assertOwned();
|
||||
return await this.runFromCatalog(options, owner);
|
||||
} finally { await owner.release(); }
|
||||
}
|
||||
|
||||
async clear(options: { workspaceId: string }): Promise<WorkspaceOperationResult> {
|
||||
const owner = await acquirePreprocessingOwner(this.deps.dataRoot, options.workspaceId);
|
||||
try { return await this.clearOwned(options, owner); }
|
||||
finally { await owner.release(); }
|
||||
}
|
||||
|
||||
private async clearOwned(options: { workspaceId: string }, owner: RunScope["owner"]): Promise<WorkspaceOperationResult> {
|
||||
const runtime = await this.deps.acquireActiveRuntime(options.workspaceId);
|
||||
const repository = this.deps.catalogRepository;
|
||||
if (!repository) return baseResult(runtime, "preprocess clear", "failed", "catalog_not_ready");
|
||||
owner.assertOwned();
|
||||
const cleared = await repository.clearPreprocessing(runtime.workspaceId);
|
||||
if (cleared.kind !== "cleared") {
|
||||
return baseResult(
|
||||
@@ -224,7 +253,9 @@ export class WorkspacePreprocessingService {
|
||||
const result = await this.deps.runChild({
|
||||
argv: ["preprocess", "clear", "--json", "-c", "/dev/fd/3"],
|
||||
configPath: runtime.configLease.path,
|
||||
guard: owner.guard,
|
||||
});
|
||||
owner.assertOwned();
|
||||
if (result.exitCode !== 0) {
|
||||
return baseResult(runtime, "preprocess clear", "failed", "preprocessing_clear_failed");
|
||||
}
|
||||
@@ -234,11 +265,13 @@ export class WorkspacePreprocessingService {
|
||||
});
|
||||
}
|
||||
|
||||
private async runFromCatalog(options: { workspaceId: string }): Promise<WorkspaceOperationResult> {
|
||||
const scope = await this.startRun(options.workspaceId);
|
||||
private async runFromCatalog(options: { workspaceId: string }, owner: RunScope["owner"]): Promise<WorkspaceOperationResult> {
|
||||
const scope = await this.startRun(options.workspaceId, owner);
|
||||
const repository = this.deps.catalogRepository!;
|
||||
const fingerprint = scope.runtime.configLease.inputFingerprint;
|
||||
const started = await repository.beginPreprocessing(scope.runtime.workspaceId, fingerprint);
|
||||
owner.assertOwned();
|
||||
const started = await repository.beginPreprocessing(scope.runtime.workspaceId, fingerprint, scope.job.runId);
|
||||
owner.assertOwned();
|
||||
if (started.kind !== "started") {
|
||||
scope.job.status = "failed";
|
||||
scope.state.writeJob(scope.job);
|
||||
@@ -260,19 +293,23 @@ export class WorkspacePreprocessingService {
|
||||
scope.runtime.workspaceId,
|
||||
revision,
|
||||
);
|
||||
owner.assertOwned();
|
||||
const snapshotPath = this.publishCatalogSnapshot(
|
||||
scope.runtime.workspaceId,
|
||||
JSON.stringify(snapshot),
|
||||
);
|
||||
this.completeStages(scope, "catalog_snapshot");
|
||||
const semantic = await this.deps.semanticPreflight(scope.runtime.workspace);
|
||||
owner.assertOwned();
|
||||
if (!semantic.ok) {
|
||||
await repository.finishPreprocessing(
|
||||
scope.runtime.workspaceId,
|
||||
revision,
|
||||
fingerprint,
|
||||
{ status: "failed", errorCode: semantic.code },
|
||||
scope.job.runId,
|
||||
);
|
||||
owner.assertOwned();
|
||||
scope.job.status = "failed";
|
||||
scope.state.writeJob(scope.job);
|
||||
finished = true;
|
||||
@@ -280,7 +317,7 @@ export class WorkspacePreprocessingService {
|
||||
}
|
||||
|
||||
failureCode = "schema_index_failed";
|
||||
const payload = await this.runJsonStage(scope.runtime, [
|
||||
const payload = await this.runJsonStage(scope, [
|
||||
"preprocess",
|
||||
"catalog",
|
||||
"--catalog-metadata",
|
||||
@@ -301,12 +338,15 @@ export class WorkspacePreprocessingService {
|
||||
this.evidenceDependencies(scope),
|
||||
);
|
||||
if (!["succeeded", "unchanged"].includes(outcome.status)) {
|
||||
owner.assertOwned();
|
||||
await repository.finishPreprocessing(
|
||||
scope.runtime.workspaceId,
|
||||
revision,
|
||||
fingerprint,
|
||||
{ status: "failed", errorCode: outcome.code },
|
||||
scope.job.runId,
|
||||
);
|
||||
owner.assertOwned();
|
||||
scope.job.status = "failed";
|
||||
scope.state.writeJob(scope.job);
|
||||
finished = true;
|
||||
@@ -319,29 +359,35 @@ export class WorkspacePreprocessingService {
|
||||
revision,
|
||||
fingerprint,
|
||||
{ status: "succeeded" },
|
||||
scope.job.runId,
|
||||
);
|
||||
owner.assertOwned();
|
||||
if (!completed) throw new Error("catalog preprocessing completion lost its lease");
|
||||
scope.job.status = "succeeded";
|
||||
scope.state.writeJob(scope.job);
|
||||
finished = true;
|
||||
return this.evidenceResult(scope, outcome);
|
||||
} catch (error) {
|
||||
owner.assertOwned();
|
||||
if (!finished) {
|
||||
await repository.finishPreprocessing(
|
||||
scope.runtime.workspaceId,
|
||||
revision,
|
||||
fingerprint,
|
||||
{ status: "failed", errorCode: failureCode },
|
||||
scope.job.runId,
|
||||
);
|
||||
}
|
||||
owner.assertOwned();
|
||||
scope.job.status = "failed";
|
||||
scope.state.writeJob(scope.job);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private async startRun(workspaceId: string): Promise<RunScope> {
|
||||
private async startRun(workspaceId: string, owner: RunScope["owner"]): Promise<RunScope> {
|
||||
const runtime = await this.deps.acquireActiveRuntime(workspaceId);
|
||||
owner.assertOwned();
|
||||
const state = this.state(runtime.workspaceId);
|
||||
const job = await state.beginJob({
|
||||
operation: "preprocess run",
|
||||
@@ -353,7 +399,10 @@ export class WorkspacePreprocessingService {
|
||||
embeddingId: runtime.configLease.effectiveConfig.embedding.id,
|
||||
embeddingDimensions: runtime.configLease.effectiveConfig.embedding.dimensions,
|
||||
});
|
||||
return { runtime, state, job };
|
||||
owner.assertOwned();
|
||||
job.ownerProtocol = 1;
|
||||
state.writeJob(job);
|
||||
return { runtime, state, job, owner };
|
||||
}
|
||||
|
||||
private state(workspaceId: string): PreprocessingStateStore {
|
||||
@@ -361,6 +410,7 @@ export class WorkspacePreprocessingService {
|
||||
}
|
||||
|
||||
private completeStages(scope: RunScope, ...stages: string[]): void {
|
||||
scope.owner.assertOwned();
|
||||
for (const stage of stages) {
|
||||
if (!scope.job.completedStages.includes(stage)) scope.job.completedStages.push(stage);
|
||||
}
|
||||
@@ -384,8 +434,8 @@ export class WorkspacePreprocessingService {
|
||||
|
||||
private evidenceDependencies(scope: RunScope): EvidencePreprocessingDependencies {
|
||||
return {
|
||||
runStage: async (argv) => await this.runJsonStage(scope.runtime, argv),
|
||||
persistJob: () => this.state(scope.runtime.workspaceId).writeJob(scope.job),
|
||||
runStage: async (argv) => await this.runJsonStage(scope, argv),
|
||||
persistJob: () => { scope.owner.assertOwned(); this.state(scope.runtime.workspaceId).writeJob(scope.job); },
|
||||
evidencePreflight: async () => await this.deps.evidencePreflight(scope.runtime.workspace),
|
||||
requireRunId: (value) => this.requireRunId(value),
|
||||
numberRecord: (value) => this.numberRecord(value),
|
||||
@@ -400,8 +450,10 @@ export class WorkspacePreprocessingService {
|
||||
return baseResult(scope.runtime, "preprocess run", status, code, extra);
|
||||
}
|
||||
|
||||
private async runJsonStage(runtime: ActiveRuntime, argv: string[]): Promise<Record<string, unknown>> {
|
||||
const result = await this.deps.runChild({ argv, configPath: runtime.configLease.path });
|
||||
private async runJsonStage(scope: RunScope, argv: string[]): Promise<Record<string, unknown>> {
|
||||
scope.owner.assertOwned();
|
||||
const result = await this.deps.runChild({ argv, configPath: scope.runtime.configLease.path, guard: scope.owner.guard });
|
||||
scope.owner.assertOwned();
|
||||
if (result.exitCode !== 0) throw new Error("workspace child failed");
|
||||
return JSON.parse(result.stdout) as Record<string, unknown>;
|
||||
}
|
||||
|
||||
@@ -34,6 +34,7 @@ export interface SessionInventoryRow {
|
||||
|
||||
export interface WriterLockLease {
|
||||
holderPid: number;
|
||||
isHeld(): boolean;
|
||||
release(): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -66,6 +67,7 @@ export interface PreprocessingJobState {
|
||||
status: "active" | "succeeded" | "blocked" | "failed";
|
||||
candidateDigest?: string;
|
||||
reviewDigest?: string;
|
||||
ownerProtocol?: 1;
|
||||
}
|
||||
|
||||
export interface FkReviewRecord {
|
||||
@@ -195,6 +197,14 @@ export class PreprocessingStateStore {
|
||||
}
|
||||
|
||||
writerLockPath(): string { return join(this.root, "writer.lock"); }
|
||||
workerLockPath(): string { return join(this.root, "workers.lock"); }
|
||||
ownerTokenPath(): string { return join(this.root, "owner-token"); }
|
||||
rotateOwnerToken(): string {
|
||||
this.ensureLayout();
|
||||
const token = randomBytes(32).toString("hex");
|
||||
writeAtomicFile(this.ownerTokenPath(), token, 0o600);
|
||||
return token;
|
||||
}
|
||||
runtimeConfigDirectory(): string { return join(this.root, "runtime-config"); }
|
||||
runtimeConfigManifestDirectory(): string { return join(this.root, "runtime-config-manifests"); }
|
||||
jobsDirectory(): string { return join(this.root, "jobs"); }
|
||||
@@ -216,9 +226,9 @@ export class PreprocessingStateStore {
|
||||
]) ensureDirectory(directory);
|
||||
}
|
||||
|
||||
async acquireWriterLock(): Promise<WriterLockLease> {
|
||||
async acquireWriterLock(kind: "writer" | "workers" = "writer"): Promise<WriterLockLease> {
|
||||
this.ensureLayout();
|
||||
const lockPath = this.writerLockPath();
|
||||
const lockPath = kind === "writer" ? this.writerLockPath() : this.workerLockPath();
|
||||
try {
|
||||
const entry = lstatSync(lockPath);
|
||||
if (!entry.isFile() || entry.isSymbolicLink()) throw new Error("invalid writer lock path");
|
||||
@@ -257,11 +267,14 @@ export class PreprocessingStateStore {
|
||||
let released = false;
|
||||
return {
|
||||
holderPid: holder.pid ?? 0,
|
||||
isHeld: () => !released && holder.exitCode === null && holder.signalCode === null,
|
||||
release: async () => {
|
||||
if (released) return;
|
||||
released = true;
|
||||
if (holder.exitCode !== null || holder.signalCode !== null) return;
|
||||
const exited = new Promise<void>((resolve) => holder.once("exit", () => resolve()));
|
||||
if (!holder.stdin.destroyed) holder.stdin.end();
|
||||
await new Promise<void>((resolve) => holder.once("exit", () => resolve()));
|
||||
await exited;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { expect, test } from "vitest";
|
||||
import { MemoryCatalogRepository } from "../src/catalog/memory-repository.js";
|
||||
|
||||
test("the in-memory Catalog enforces the same attempt identity as PostgreSQL", async () => {
|
||||
const repository = new MemoryCatalogRepository();
|
||||
const database = await repository.create({ workspaceId: "retry", engine: "postgres",
|
||||
databaseName: "warehouse", schema: "public",
|
||||
binding: { transport: "postgres_direct", host: "db", port: 5432, username: "reader" } });
|
||||
await repository.applySchemaSync(database.id, database.version, "all", [], {
|
||||
schemaVersion: 1, capabilities: { tables: "available", columns: "available", relationships: "available" },
|
||||
tables: [], columns: [], relationships: [],
|
||||
});
|
||||
const revision = (await repository.get(database.id))!.metadataContentRevision;
|
||||
const fingerprint = "sha256:" + "1".repeat(64);
|
||||
await repository.beginPreprocessing("retry", fingerprint, "old");
|
||||
await repository.finishPreprocessing("retry", revision, fingerprint,
|
||||
{ status: "failed", errorCode: "preprocessing_interrupted" }, "old");
|
||||
await repository.beginPreprocessing("retry", fingerprint, "replacement");
|
||||
expect(await repository.finishPreprocessing("retry", revision, fingerprint, { status: "succeeded" }, "old")).toBeUndefined();
|
||||
expect(await repository.finishPreprocessing("retry", revision, fingerprint, { status: "succeeded" }, "replacement"))
|
||||
.toMatchObject({ preprocessingStatus: "succeeded" });
|
||||
});
|
||||
@@ -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,13 @@ 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 { up as upPreprocessingRunIdentity } from "../src/catalog/migrations/015_preprocessing_run_identity.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 +70,8 @@ test.skipIf(!dockerAvailable)("PostgreSQL migration enforces one database per wo
|
||||
await upLocalSensitivityAnalysis(db);
|
||||
await upSensitivityReason(db);
|
||||
await upCatalogPreprocessingState(db);
|
||||
await upInstallationBindingImports(db);
|
||||
await upPreprocessingRunIdentity(db);
|
||||
await expect(db.selectFrom("sensitiveDataSuggestionRuns")
|
||||
.select(["engine", "modelId", "policyVersion", "unknown"])
|
||||
.where("id", "=", historicalSuggestionRunId)
|
||||
@@ -302,6 +314,16 @@ test.skipIf(!dockerAvailable)("PostgreSQL migration enforces one database per wo
|
||||
preprocessingStatus: "succeeded",
|
||||
preprocessedMetadataRevision: beforePreprocessing.metadataContentRevision,
|
||||
});
|
||||
const fingerprint = "sha256:" + "1".repeat(64);
|
||||
await repository.beginPreprocessing("preprocessing-lock", fingerprint, "old-run");
|
||||
await repository.finishPreprocessing("preprocessing-lock", beforePreprocessing.metadataContentRevision,
|
||||
fingerprint, { status: "failed", errorCode: "preprocessing_interrupted" }, "old-run");
|
||||
await repository.beginPreprocessing("preprocessing-lock", fingerprint, "replacement-run");
|
||||
// Identical inputs must not let a late completion finish the replacement run.
|
||||
await expect(repository.finishPreprocessing("preprocessing-lock", beforePreprocessing.metadataContentRevision,
|
||||
fingerprint, { status: "failed", errorCode: "late-owner" }, "old-run")).resolves.toBeUndefined();
|
||||
await expect(repository.finishPreprocessing("preprocessing-lock", beforePreprocessing.metadataContentRevision,
|
||||
fingerprint, { status: "succeeded" }, "replacement-run")).resolves.toMatchObject({ preprocessingStatus: "succeeded" });
|
||||
await db.insertInto("catalogTables").values({
|
||||
id: randomUUID(),
|
||||
databaseId: lockedDatabase.id,
|
||||
@@ -319,6 +341,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();
|
||||
|
||||
@@ -15,10 +15,34 @@ import {
|
||||
import { WorkspaceSecretStore } from "../src/workspaces/secret-store.js";
|
||||
import type { WorkspaceRegistry, WorkspaceRevision } from "../src/workspaces/registry.js";
|
||||
import type { WorkspaceDescriptor } from "../src/workspaces/schema.js";
|
||||
// @ts-expect-error The native operator embeds this plain ESM client.
|
||||
import { prepareWorkspace } from "../../tools/tht/internal/installapply/import-bindings.mjs";
|
||||
|
||||
const roots: string[] = [];
|
||||
afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });
|
||||
|
||||
test("installation retry preserves the durable destructive review and source comments", async () => {
|
||||
const { app, repository, database, setObserved } = await setup();
|
||||
try {
|
||||
await seedCatalog(repository, database);
|
||||
const tablesBefore = await repository.listTables(database.id);
|
||||
setObserved({ schemaVersion: 1, capabilities: { tables: "available", columns: "available", relationships: "available" }, tables: [], columns: [], relationships: [] });
|
||||
const started = await app.inject({ method: "POST", url: `/catalog/databases/${database.id}/sync-runs`, payload: { version: database.version, scope: "all", tableIds: [] } });
|
||||
const run = await waitFor(repository, started.json().id, "awaiting_confirmation");
|
||||
const request = async (path: string, body?: unknown) => {
|
||||
expect(body).toBeUndefined();
|
||||
const response = await app.inject({ method: "GET", url: path });
|
||||
return new Response(response.body, { status: response.statusCode, headers: { "content-type": "application/json" } });
|
||||
};
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
await expect(prepareWorkspace(request, "psd-clinical", revision.commit)).rejects.toMatchObject({ code: "schema_review_required", runId: run.id });
|
||||
}
|
||||
expect(await repository.listTables(database.id)).toEqual(tablesBefore);
|
||||
expect(await repository.listSyncRuns(database.id)).toHaveLength(1);
|
||||
expect((await repository.getSyncRun(run.id))?.state).toBe("awaiting_confirmation");
|
||||
} finally { await app.close(); }
|
||||
});
|
||||
|
||||
const workspace: WorkspaceDescriptor = {
|
||||
workspace: { schema_version: 4, id: "psd-clinical", name: "Policlinico San Donato", language: "it" },
|
||||
dwh: { engine: "postgres", database: "warehouse", schema: "datawarehouse", port: 5432, supported_transports: ["postgres_direct"] },
|
||||
|
||||
@@ -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,89 @@
|
||||
import { expect, test } from "vitest";
|
||||
// The shipped operator client is plain ESM, shared by the embedded command and these API-boundary tests.
|
||||
// @ts-expect-error JavaScript operator module has no separate declaration file.
|
||||
import { prepareWorkspace, importBinding } from "../../tools/tht/internal/installapply/import-bindings.mjs";
|
||||
|
||||
const revision = "a".repeat(40);
|
||||
|
||||
test("a stranded preprocessing state requests guarded recovery, then verifies fresh readiness", async () => {
|
||||
let state = "running";
|
||||
const request = async (path: string, body?: unknown): Promise<Response> => {
|
||||
if (path === "/catalog/databases") return Response.json([{ id: "database-id", workspaceId: "chinook", version: 2, schemaSyncedVersion: 2,
|
||||
binding: { transport: "postgres_direct" }, workspaceRevision: { commit: revision } }]);
|
||||
if (path.endsWith("/sync-runs")) return Response.json([]);
|
||||
if (path.endsWith("/preprocessing")) {
|
||||
if (body) { expect(body).toEqual({ recoverInterrupted: true }); state = "ready"; }
|
||||
return Response.json({ state });
|
||||
}
|
||||
throw Error("unexpected operation");
|
||||
};
|
||||
expect(await prepareWorkspace(request, "chinook", revision, async () => {})).toEqual({ workspaceId: "chinook", state: "ready" });
|
||||
});
|
||||
|
||||
test("retry reaches a pending human schema review even when its reservation blocks binding import", async () => {
|
||||
const request = async (path: string) => {
|
||||
if (path === "/installation/bindings") return Response.json({ code: "installation_operation_pending" }, { status: 409 });
|
||||
if (path === "/catalog/databases") return Response.json([{ workspaceId: "chinook", activeSyncRun: { id: "run-id", state: "awaiting_confirmation" } }]);
|
||||
throw Error("unexpected operation");
|
||||
};
|
||||
await expect(importBinding(request, { configuration: { workspaceId: "chinook" } }, revision, async () => {})).rejects.toMatchObject({ code: "schema_review_required", runId: "run-id" });
|
||||
});
|
||||
|
||||
test.each(["blocked", "failed"])("configured Evidence/index failure (%s) remains a real stop", async state => {
|
||||
const request = async (path: string, body?: unknown): Promise<Response> => {
|
||||
if (path === "/catalog/databases") return Response.json([{ id: "database-id", workspaceId: "chinook", version: 2, schemaSyncedVersion: 2,
|
||||
binding: { transport: "postgres_direct" }, workspaceRevision: { commit: revision } }]);
|
||||
if (path.endsWith("/sync-runs")) return Response.json([]);
|
||||
if (path.endsWith("/preprocessing")) return Response.json({ state }, { status: body === undefined ? 200 : 422 });
|
||||
throw Error("unexpected destructive operation");
|
||||
};
|
||||
await expect(prepareWorkspace(request, "chinook", revision, async () => {})).rejects.toMatchObject({ code: `preprocessing_${state}` });
|
||||
});
|
||||
|
||||
test("SSH metadata connectivity cannot be mistaken for session transport support", async () => {
|
||||
const calls: string[] = [];
|
||||
const request = async (path: string) => {
|
||||
calls.push(path);
|
||||
return Response.json([{ id: "database-id", workspaceId: "chinook", version: 2,
|
||||
binding: { transport: "ssh_tunnel" }, workspaceRevision: { commit: revision } }]);
|
||||
};
|
||||
await expect(prepareWorkspace(request, "chinook", revision)).rejects.toMatchObject({ code: "session_transport_unsupported" });
|
||||
expect(calls).toEqual(["/catalog/databases"]);
|
||||
});
|
||||
test("a destructive synchronization stops at the existing domain gate without confirmation", async () => {
|
||||
const calls: string[] = [];
|
||||
const request = async (path: string) => {
|
||||
calls.push(path);
|
||||
if (path === "/catalog/databases") return Response.json([{ id: "database-id", workspaceId: "chinook", version: 2,
|
||||
binding: { transport: "postgres_direct" }, workspaceRevision: { commit: revision } }]);
|
||||
if (path.endsWith("/sync-runs")) return Response.json([{ id: "run-id", state: "awaiting_confirmation", scope: "all" }]);
|
||||
throw Error("unexpected operation");
|
||||
};
|
||||
await expect(prepareWorkspace(request, "chinook", revision)).rejects.toMatchObject({ code: "schema_review_required", runId: "run-id" });
|
||||
expect(calls).toEqual(["/catalog/databases", "/catalog/databases/database-id/sync-runs"]);
|
||||
});
|
||||
|
||||
test("fresh additive sync and preprocessing use existing APIs once, then repeat as a no-op", async () => {
|
||||
const writes: string[] = [];
|
||||
let synchronized = false, preprocessed = false;
|
||||
const request = async (path: string, body?: unknown) => {
|
||||
if (body !== undefined) writes.push(path);
|
||||
if (path === "/catalog/databases") return Response.json([{ id: "database-id", workspaceId: "chinook", version: 2,
|
||||
schemaSyncedVersion: synchronized ? 2 : undefined,
|
||||
binding: { transport: "postgres_direct" }, workspaceRevision: { commit: revision } }]);
|
||||
if (path === "/catalog/databases/database-id") return Response.json({ version: 2, schemaSyncedVersion: 2 });
|
||||
if (path.endsWith("/sync-runs")) {
|
||||
if (body) { expect(body).toEqual({ version: 2, scope: "all", tableIds: [] }); return Response.json({ id: "run-id", state: "queued", scope: "all" }); }
|
||||
return Response.json(synchronized ? [{ id: "run-id", state: "succeeded", scope: "all" }] : []);
|
||||
}
|
||||
if (path === "/catalog/sync-runs/run-id") { synchronized = true; return Response.json({ id: "run-id", state: "succeeded", scope: "all" }); }
|
||||
if (path === "/workspaces/chinook/preprocessing") {
|
||||
if (body) preprocessed = true;
|
||||
return Response.json({ state: preprocessed ? "ready" : "required" });
|
||||
}
|
||||
throw Error("unexpected operation");
|
||||
};
|
||||
expect(await prepareWorkspace(request, "chinook", revision, async () => {})).toEqual({ workspaceId: "chinook", state: "ready" });
|
||||
expect(await prepareWorkspace(request, "chinook", revision, async () => {})).toEqual({ workspaceId: "chinook", state: "ready" });
|
||||
expect(writes).toEqual(["/catalog/databases/database-id/sync-runs", "/workspaces/chinook/preprocessing"]);
|
||||
});
|
||||
@@ -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"]);
|
||||
});
|
||||
@@ -54,6 +54,17 @@ const modelCatalog: RuntimeModelCatalog = {
|
||||
hasSession: (id) => id === "zai/glm-5.2",
|
||||
};
|
||||
|
||||
test("a fresh installation can smoke-test its catalog default without saved user settings", async () => {
|
||||
const smokeProvider = vi.fn(async () => undefined);
|
||||
const service = createPiManagement(configFor(), {
|
||||
modelCatalog, execute: successfulExec([]), readSettings: () => ({}), smokeProvider,
|
||||
});
|
||||
expect(await service.test()).toMatchObject({ ready: true });
|
||||
expect(smokeProvider).toHaveBeenCalledWith(expect.objectContaining({
|
||||
provider: "zai", model: "glm-5.2", reasoning: "low",
|
||||
}));
|
||||
});
|
||||
|
||||
function successfulExec(calls: Array<{ command: string; args: string[]; timeout: number }>): PiExecFile {
|
||||
return async (command, args, options) => {
|
||||
calls.push({ command, args, timeout: options.timeout });
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { expect, test } from "vitest";
|
||||
import { acquirePreprocessingOwner, guardedPreprocessingCommand } from "../src/workspaces/preprocessing-owner.js";
|
||||
|
||||
test("orphan worker prevents recovery; delayed old worker is fenced after recovery", async () => {
|
||||
const root = mkdtempSync(join(tmpdir(), "preprocess-owner-"));
|
||||
let worker;
|
||||
try {
|
||||
const owner = await acquirePreprocessingOwner(root, "chinook");
|
||||
const command = guardedPreprocessingCommand(owner.guard, "python3", ["-c", "import time; print('ready',flush=True); time.sleep(30)"]);
|
||||
worker = spawn(command.executable, command.args, { stdio: ["ignore", "pipe", "pipe"] });
|
||||
await new Promise<void>((resolve, reject) => { worker!.stdout!.once("data", () => resolve()); worker!.once("error", reject); worker!.once("exit", () => reject(Error("worker stopped early"))); });
|
||||
await owner.release();
|
||||
await expect(acquirePreprocessingOwner(root, "chinook")).rejects.toMatchObject({ code: "preprocessing_conflict" });
|
||||
const exited = new Promise(resolve => worker!.once("exit", resolve)); worker.kill("SIGKILL"); await exited;
|
||||
const replacement = await acquirePreprocessingOwner(root, "chinook");
|
||||
try {
|
||||
const stale = guardedPreprocessingCommand(owner.guard, "python3", ["-c", "raise Exception('must never run')"]);
|
||||
expect(spawnSync(stale.executable, stale.args).status).toBe(73);
|
||||
} finally { await replacement.release(); }
|
||||
} finally { worker?.kill("SIGKILL"); rmSync(root, { recursive: true, force: true }); }
|
||||
});
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
type WorkspacePreprocessingRouteDeps,
|
||||
} from "../src/routes/workspace-preprocessing.js";
|
||||
import type { WorkspaceRegistry } from "../src/workspaces/registry.js";
|
||||
import { PreprocessingStateError } from "../src/workspaces/preprocessing-state.js";
|
||||
|
||||
const admin: PrincipalContext = {
|
||||
issuer: "test",
|
||||
@@ -17,6 +18,22 @@ const admin: PrincipalContext = {
|
||||
isAdmin: true,
|
||||
};
|
||||
|
||||
test("explicit interrupted-run recovery is guarded and never steals an active owner", async () => {
|
||||
const run = vi.fn(async () => { throw new PreprocessingStateError("preprocessing_conflict", "private owner details"); });
|
||||
const deps = routeDeps(() => database({ preprocessingStatus: "running" }), { service: { run, clear: vi.fn() } });
|
||||
const app = Fastify();
|
||||
app.addHook("preHandler", async request => { request.principal = admin; });
|
||||
workspacePreprocessingRoutes(app, deps);
|
||||
try {
|
||||
const response = await app.inject({ method: "POST", url: "/workspaces/catalog-workspace/preprocessing", payload: { recoverInterrupted: true } });
|
||||
expect(response.statusCode).toBe(409);
|
||||
expect(response.json()).toMatchObject({ code: "preprocessing_conflict", state: "running" });
|
||||
expect(response.body).not.toContain("private owner");
|
||||
expect(run).toHaveBeenCalledOnce();
|
||||
expect(deps.service.clear).not.toHaveBeenCalled();
|
||||
} finally { await app.close(); }
|
||||
});
|
||||
|
||||
function database(overrides: Partial<WorkspaceDatabase> = {}): WorkspaceDatabase {
|
||||
return {
|
||||
id: "49b6491a-78bb-4cee-b27b-0efaf4419774",
|
||||
|
||||
@@ -3,6 +3,7 @@ import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, expect, test, vi } from "vitest";
|
||||
import { validateWorkspaceDescriptor } from "../src/workspaces/schema.js";
|
||||
import { PreprocessingStateStore, type WriterLockLease } from "../src/workspaces/preprocessing-state.js";
|
||||
import {
|
||||
WorkspacePreprocessingService,
|
||||
type ChildProcessRequest,
|
||||
@@ -10,6 +11,64 @@ import {
|
||||
|
||||
const roots: string[] = [];
|
||||
|
||||
test("a legacy running lease is never silently adopted by repeated recovery attempts", async () => {
|
||||
const catalog = repository({ getByWorkspace: vi.fn(async () => ({ ...database, preprocessingInputFingerprint: "sha256:legacy" })) });
|
||||
const instance = service({ repository: catalog });
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
expect(await instance.run({ workspaceId: "catalog-workspace" })).toMatchObject({ status: "failed", code: "preprocessing_conflict" });
|
||||
}
|
||||
expect(catalog.beginPreprocessing).not.toHaveBeenCalled();
|
||||
expect(catalog.finishPreprocessing).not.toHaveBeenCalled();
|
||||
expect(catalog.clearPreprocessing).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("retry after loss of Catalog completion restarts guarded preprocessing without clearing data", async () => {
|
||||
let stranded = false;
|
||||
let runId: string | undefined;
|
||||
const catalog = repository({ getByWorkspace: vi.fn(async () => ({ ...database,
|
||||
...(stranded ? { preprocessingInputFingerprint: "sha256:" + "f".repeat(64), preprocessingRunId: runId } : {}) })),
|
||||
beginPreprocessing: vi.fn(async (_workspace, _fingerprint, id) => {
|
||||
runId = id; return { kind: "started", database };
|
||||
}),
|
||||
});
|
||||
catalog.finishPreprocessing.mockRejectedValueOnce(Error("Catalog connection lost"))
|
||||
.mockRejectedValueOnce(Error("Catalog still unavailable"));
|
||||
const instance = service({ repository: catalog, runChild: async () => {
|
||||
stranded = true;
|
||||
return { exitCode: 0, stdout: JSON.stringify({ counts: { tables: 1 } }), stderr: "" };
|
||||
} });
|
||||
await expect(instance.run({ workspaceId: "catalog-workspace" })).rejects.toThrow();
|
||||
const second = await instance.run({ workspaceId: "catalog-workspace" });
|
||||
expect(second.status).toBe("succeeded");
|
||||
expect(catalog.finishPreprocessing).toHaveBeenCalledWith("catalog-workspace", 9, "sha256:" + "f".repeat(64),
|
||||
{ status: "failed", errorCode: "preprocessing_interrupted" }, expect.any(String));
|
||||
expect(catalog.clearPreprocessing).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("loss of the real owner during semantic preflight cannot complete or rewrite the job", async () => {
|
||||
let lease: WriterLockLease | undefined;
|
||||
const original = PreprocessingStateStore.prototype.acquireWriterLock;
|
||||
const spy = vi.spyOn(PreprocessingStateStore.prototype, "acquireWriterLock")
|
||||
.mockImplementation(async function (kind) {
|
||||
const acquired = await original.call(this, kind);
|
||||
if (kind !== "workers") lease = acquired;
|
||||
return acquired;
|
||||
});
|
||||
const catalog = repository();
|
||||
const instance = service({ repository: catalog, semanticPreflight: async () => {
|
||||
process.kill(lease!.holderPid, "SIGKILL");
|
||||
for (let i = 0; i < 100 && lease!.isHeld(); i++) await new Promise(resolve => setTimeout(resolve, 10));
|
||||
expect(lease!.isHeld()).toBe(false);
|
||||
return { ok: false, code: "semantic_index_incompatible" };
|
||||
} });
|
||||
try {
|
||||
await expect(instance.run({ workspaceId: "catalog-workspace" })).rejects.toMatchObject({ code: "preprocessing_conflict" });
|
||||
expect(catalog.finishPreprocessing).not.toHaveBeenCalled();
|
||||
const latest = new PreprocessingStateStore({ dataRoot: roots.at(-1)!, workspaceId: "catalog-workspace" }).readLatestJob();
|
||||
expect(latest?.status).toBe("active");
|
||||
} finally { spy.mockRestore(); }
|
||||
});
|
||||
|
||||
test("Evidence consolidation runs only its stage and preserves blocked Catalog readiness", async () => {
|
||||
const catalog = repository();
|
||||
const runChild = vi.fn(async () => ({ exitCode: 0, stdout: JSON.stringify({ status: "succeeded", counts: { documents: 2 } }), stderr: "" }));
|
||||
@@ -219,6 +278,7 @@ test("complete preprocessing snapshots Catalog metadata and commits its PostgreS
|
||||
9,
|
||||
"sha256:" + "f".repeat(64),
|
||||
{ status: "succeeded" },
|
||||
expect.any(String),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -257,6 +317,7 @@ test("preprocessing records a failed PostgreSQL state when its hidden worker fai
|
||||
9,
|
||||
"sha256:" + "f".repeat(64),
|
||||
{ status: "failed", errorCode: "schema_index_failed" },
|
||||
expect.any(String),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -273,6 +334,7 @@ test("semantic preflight failure is persisted before returning", async () => {
|
||||
9,
|
||||
"sha256:" + "f".repeat(64),
|
||||
{ status: "failed", errorCode: "semantic_index_incompatible" },
|
||||
expect.any(String),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -310,6 +372,7 @@ test("clear invalidates Catalog readiness before clearing only derived worker da
|
||||
expect(runChild).toHaveBeenCalledWith({
|
||||
argv: ["preprocess", "clear", "--json", "-c", "/dev/fd/3"],
|
||||
configPath: expect.any(String),
|
||||
guard: { lockPath: expect.any(String), tokenPath: expect.any(String), token: expect.stringMatching(/^[a-f0-9]{64}$/) },
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
status: "succeeded",
|
||||
|
||||
+3
-1
@@ -12,6 +12,7 @@ services:
|
||||
THT_HARNESS_DIR: /app/harness
|
||||
THT_BIN: /opt/venv/bin/tht
|
||||
THT_DATA_ROOT: /data
|
||||
THT_HOME: /data/sessions/.thothii
|
||||
SETTINGS_FILE: /data/settings/settings.json
|
||||
THT_EVIDENCE_HOST_REGISTRY_ROOT: ${THT_WORKSPACE_REGISTRY_ROOT:-}
|
||||
THT_MAINTENANCE_FILE: /data/settings/maintenance.json
|
||||
@@ -86,7 +87,7 @@ services:
|
||||
test:
|
||||
- CMD-SHELL
|
||||
- >-
|
||||
pg_isready -U thothii_catalog_migrate -d thothii_catalog
|
||||
pg_isready -h 127.0.0.1 -U thothii_catalog_migrate -d thothii_catalog
|
||||
&& test "$(psql -U thothii_catalog_migrate -d thothii_catalog -Atqc
|
||||
"select count(*) from pg_catalog.pg_roles where rolname = 'thothii_catalog_runtime'")" = "1"
|
||||
interval: 5s
|
||||
@@ -124,6 +125,7 @@ services:
|
||||
THT_HARNESS_DIR: /app/harness
|
||||
THT_BIN: /opt/venv/bin/tht
|
||||
THT_DATA_ROOT: /data
|
||||
THT_HOME: /data/sessions/.thothii
|
||||
THT_WORKSPACE_REGISTRY_ROOT: /data/workspace-registry
|
||||
THT_WORKSPACE_GIT_REMOTE: ${THT_WORKSPACE_GIT_REMOTE:?set THT_WORKSPACE_GIT_REMOTE}
|
||||
THT_WORKSPACE_GIT_BRANCH: ${THT_WORKSPACE_GIT_BRANCH:-main}
|
||||
|
||||
@@ -153,6 +153,30 @@ Core admission requires all of the following:
|
||||
Failure leaves the workspace unavailable to the core. There is no rollback: fix the cause and run
|
||||
the complete command again.
|
||||
|
||||
## Interrupted owner recovery
|
||||
|
||||
Current preprocessing runs also hold a kernel writer lock on the shared workspace
|
||||
volume. Every mutating worker inherits a separate shared kernel lock and validates
|
||||
an owner generation before starting. Recovery takes both locks exclusively before
|
||||
rotating that generation: a surviving orphan worker blocks recovery, while a delayed
|
||||
worker from the old generation cannot start. These guards establish process ownership;
|
||||
PostgreSQL remains the readiness authority.
|
||||
|
||||
A repeated `preprocess run` can mark an orphaned current-protocol Catalog lease as
|
||||
`preprocessing_interrupted` through the version/fingerprint/run-identity-checked completion
|
||||
operation, then restart the entire pipeline. It does not resume internal stages or
|
||||
clear Memory, sessions, curated descriptions or canonical Evidence. Older running jobs
|
||||
without this ownership protocol are not automatically adopted; inspect their original
|
||||
owner during upgrade instead of deleting data or resetting leases speculatively.
|
||||
Each attempt records its unique run identity in PostgreSQL (migration 015). A late
|
||||
completion from the previous attempt cannot finish its replacement, even when the
|
||||
metadata revision and input fingerprint are unchanged.
|
||||
|
||||
The installer requests this guarded recovery when status remains running. An active
|
||||
owner returns a conflict and the installer waits. A pending destructive Catalog Sync
|
||||
Run is preserved for human review, including when its reservation temporarily blocks
|
||||
binding import. Interrupted synchronization is retried through the existing domain API.
|
||||
|
||||
## Administration sidebar
|
||||
|
||||
The Administration sidebar exposes the same one-shot operation for the workspace selected in the
|
||||
|
||||
@@ -39,9 +39,8 @@ platform without pulling layers. `docker compose config --format json` checks th
|
||||
effective service configuration. Compose receives only Docker connection/trust,
|
||||
proxy and executable-discovery host variables; application parameters come from
|
||||
the prepared environment file. Raw Docker output is never copied into reports.
|
||||
Each Docker command has a 15-second bound. No release is currently certified merely
|
||||
because controlled manifest tests pass: publication and real pull acceptance belong
|
||||
to the publication/execution tickets.
|
||||
Each preflight Docker command has a 15-second bound. Public image publication is
|
||||
verified separately; controlled manifest tests alone do not certify host acceptance.
|
||||
|
||||
## External checks and bounds
|
||||
|
||||
@@ -85,7 +84,62 @@ is generated. Credential rotation invalidates the plan. Added/deleted/changed
|
||||
workspace files invalidate it as well. Changes during the checks abort publication.
|
||||
Plan output never overwrites an existing plan or key.
|
||||
|
||||
Execution and resumption must call `VerifyPlanInputs` **and repeat live checks and
|
||||
Execution and resumption call `ReadExecutionPlan` **and repeat live checks and
|
||||
credential reads before mutations**. A valid seal alone does not certify current
|
||||
network availability, Docker state or runtime readiness. Keep both plan files
|
||||
private and outside the workspace repository; they are installation-local artifacts.
|
||||
|
||||
## Non-interactive platform execution
|
||||
|
||||
`tht --installation ABS_DESCRIPTOR installation apply --plan ABS_PLAN [--json]`
|
||||
requires an operator whose version and revision match the manifest. Plans must
|
||||
include the manifest and bootstrap paths; regenerate older plans. The only permitted
|
||||
absent-input transition is materialization of a standard release transport overlay
|
||||
with exactly its packaged digest. All other input changes invalidate execution.
|
||||
|
||||
The local profile uses the preparing non-root Unix operator's UID/GID for core,
|
||||
maintenance, migrations and PostgreSQL. Original private authentication directory
|
||||
and credential mounts remain authoritative. A pinned, offline one-shot helper seeds
|
||||
only installation-owned volumes, retaining a root-owned initialization marker for
|
||||
interruption recovery. Existing ready volumes are never recursively chowned.
|
||||
Account collisions and foreign volumes stop execution. This requires local Docker;
|
||||
Windows runs inside WSL2 rather than the native Windows shell.
|
||||
|
||||
The lifecycle lock excludes concurrent operations. Asset publication and journal
|
||||
updates are atomic. Every retry repeats reconciliation, even after a completed
|
||||
journal stage. Pull and service startup have 30-minute bounds; Catalog startup and
|
||||
migration have 5-minute bounds; final health inspection has a 1-minute bound.
|
||||
Cancellation cleans up named one-shot containers and releases the lock. Hard-killed
|
||||
processes require explicit stale-owner inspection; automatic destructive repair is
|
||||
not performed. Errors contain a stage/action without raw Docker output or secrets.
|
||||
|
||||
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: true`.
|
||||
The bounded `binding_import` report distinguishes authentication, workspace reconciliation,
|
||||
binding reconciliation and container connectivity failures. `workspace_preparation`
|
||||
reports existing Catalog synchronization and preprocessing outcomes. Pending destructive
|
||||
review returns exit 3 with `schema_review_required`; resolve it in Administration and
|
||||
repeat apply. Other failures return exit 1. No confirmation, curation overwrite, AI
|
||||
description generation or Memory clearing is implicit. Current completed stages are reused.
|
||||
|
||||
`runtime_checks` retains workspace diagnostics (DWH, Evidence, Qdrant and embedding),
|
||||
workflow diagnostics and Pi/default-provider smoke as pending/passed/failed. These
|
||||
checks use bounded named one-shot containers, preserving cancellation cleanup. The
|
||||
Pi smoke sends a short provider request with no DWH context and may incur usage.
|
||||
Runtime failure preserves platform/binding success but leaves workspace readiness false.
|
||||
`functional_acceptance` stays false: only a real human-reviewed question provides that
|
||||
acceptance. Published preview.5 predates binding import and readiness; use a subsequent
|
||||
matching image/operator release for this extension.
|
||||
|
||||
@@ -2,6 +2,12 @@
|
||||
|
||||
## Italiano
|
||||
|
||||
Per l'avvio automatico usare la
|
||||
[preview.5](https://git.tylconsulting.it/mptyl/ThothII/releases/tag/installation-v0.1.0-install-preview.5):
|
||||
include `installation apply`, immagini e bundle Linux amd64/arm64. L'avvio della
|
||||
piattaforma è stato verificato dal pacchetto pubblico; import dei binding, readiness
|
||||
dei workspace e collaudi sui sistemi operativi restano passi successivi.
|
||||
|
||||
Questo comando è riservato al manutentore. L'utente finale scarica il pacchetto e
|
||||
le immagini già compilati. La prima prerelease riguarda **Linux amd64**, utilizzato
|
||||
da Ubuntu WSL2 su Windows e successivamente da Omarchy; non certifica ancora il
|
||||
@@ -11,6 +17,12 @@ Prerequisiti del manutentore: Git, Node 24/npm, Go indicato in `tools/tht/go.mod
|
||||
Docker con Buildx e capacità di eseguire Linux amd64, `tar`. Bun viene installato
|
||||
dal lock npm e serve soltanto per compilare il pacchetto. Il commit da pubblicare
|
||||
deve essere già disponibile sul repository Gitea pubblico.
|
||||
Eseguire il produttore su Linux, WSL2 o macOS; la shell Windows nativa non è supportata.
|
||||
|
||||
La prima [prerelease Linux amd64](https://git.tylconsulting.it/mptyl/ThothII/releases/tag/installation-v0.1.0-install-preview.1)
|
||||
è disponibile: `0.1.0-install-preview.1`, con immagini pubbliche
|
||||
[core](https://hub.docker.com/r/tylconsulting/thothii-core) e
|
||||
[frontend](https://hub.docker.com/r/tylconsulting/thothii-frontend).
|
||||
|
||||
1. Eseguire `docker login` sul computer di pubblicazione con un account autorizzato
|
||||
a creare repository pubblici e pubblicare immagini nel namespace scelto.
|
||||
@@ -56,6 +68,11 @@ questa macchina di pubblicazione non sostituisce il successivo collaudo Windows.
|
||||
|
||||
## English
|
||||
|
||||
Use [preview.5](https://git.tylconsulting.it/mptyl/ThothII/releases/tag/installation-v0.1.0-install-preview.5)
|
||||
for automatic platform startup: it includes `installation apply`, Linux amd64/arm64
|
||||
images and native bundles. Platform startup was verified from the public archive;
|
||||
binding import, workspace readiness and operating-system acceptance remain later steps.
|
||||
|
||||
This is a maintainer command. Consumers download precompiled images and the native
|
||||
operator bundle. The first prerelease targets **Linux amd64** for Ubuntu WSL2 and
|
||||
later Omarchy; full installation and real-host acceptance remain separate work.
|
||||
@@ -66,6 +83,10 @@ Bun for producer builds only. Push the selected source commit to the public Gite
|
||||
repository before publication. Use Docker's credential store for `docker login`
|
||||
and Git's credential helper for Gitea release/attachment permissions. Never pass
|
||||
tokens as command arguments or include them in a checkout or archive.
|
||||
Run the producer on Linux, WSL2 or macOS, not a native Windows shell.
|
||||
|
||||
The first [Linux amd64 prerelease](https://git.tylconsulting.it/mptyl/ThothII/releases/tag/installation-v0.1.0-install-preview.1)
|
||||
is available as `0.1.0-install-preview.1`, with public Docker Hub core/frontend images.
|
||||
|
||||
From `backend`, run `npm ci`, then the command above with an explicit revision,
|
||||
version, namespace, platforms and a new private output directory. A temporary Git
|
||||
|
||||
@@ -13,9 +13,11 @@ The first two steps of the new flow work without Docker, Node, Python, Pi or an
|
||||
installation descriptor. Use the platform bundle with **both** `tht` and
|
||||
`tht-workspace-documents` in the same directory (`.exe` on Windows). Put that directory
|
||||
on `PATH`, or invoke the absolute executable path. Older packages containing only
|
||||
`tht` do not provide this capability. Maintainers can currently build the bundle;
|
||||
publishing assets and Docker Hub images belongs to a later delivery step. The rest
|
||||
of this guide still describes the existing installation path.
|
||||
`tht` do not provide this capability. Download bundles from the
|
||||
[public releases](https://git.tylconsulting.it/mptyl/ThothII/releases); core and frontend
|
||||
images are published on Docker Hub. `installation apply` requires a bundle containing
|
||||
that command: the first preview provided preparation and preflight only. On Windows,
|
||||
use the Linux bundle inside Ubuntu WSL2.
|
||||
|
||||
1. Choose a new directory outside the application checkout, with an existing parent:
|
||||
|
||||
@@ -91,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
|
||||
@@ -114,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
|
||||
@@ -126,7 +135,7 @@ must exist. It starts no services and does not implicitly generate passwords.
|
||||
`secrets/pi-auth.json`. Existing files are retained; invalid ones stop the command.
|
||||
The initial administrator is `admin`; its password stays in private
|
||||
`secrets/admin-password` and is never printed. The default is local authentication
|
||||
at `http://localhost:8080`: review and edit `auth/auth.yaml` before validation.
|
||||
at `http://127.0.0.1:8080`: review and edit `auth/auth.yaml` before validation.
|
||||
This increment does not validate offline OIDC bootstrap for the existing path.
|
||||
5. Fill the provider key in `secrets/secrets.env` and create the DWH password file.
|
||||
For Git HTTPS supply the referenced credentials and CA files; empty credentials
|
||||
@@ -179,8 +188,8 @@ tht --installation /path/installation/thothii-installation.yaml installation pla
|
||||
This repeats document checks, verifies image digests and Compose, Git, available
|
||||
external databases and Evidence, then saves the plan and its separate private
|
||||
`.key` file. It does not execute setup. Missing images and unavailable existing
|
||||
dependencies block the plan. Actual Docker Hub publication remains the next ticket;
|
||||
an invented manifest cannot bypass publication.
|
||||
dependencies block the plan. The manifest and executables must belong to the same
|
||||
release; an invented manifest cannot bypass these checks.
|
||||
|
||||
Correct `error` outcomes and read `warning` outcomes. `deferred-to-runtime` entries
|
||||
are mandatory checks after startup, not readiness already achieved. After changing
|
||||
@@ -192,7 +201,118 @@ incur ordinary service request charges. See the
|
||||
[preflight reference](installation-preflight.md) for limits, the manifest
|
||||
format and runtime obligations.
|
||||
|
||||
## Before you start: the two repositories
|
||||
## Start the platform from verified documents
|
||||
|
||||
Use the same non-root operator that prepared the documents, with access to local
|
||||
Docker. The command asks no questions and accepts closed stdin:
|
||||
|
||||
```sh
|
||||
tht --installation /path/installation/thothii-installation.yaml installation apply \
|
||||
--plan /path/installation/installation-plan.json --json
|
||||
```
|
||||
|
||||
It repeats live checks and plan verification, copies verified assets, pulls images,
|
||||
initializes new installation volumes, starts PostgreSQL, applies Catalog and Memory
|
||||
migrations, and starts services. It never builds sources. The initial administrator
|
||||
comes from the prepared authentication documents. Secrets retain private permissions;
|
||||
services that read them run with the operator's UID. This path does not convert an
|
||||
existing stack with incompatible volume ownership.
|
||||
|
||||
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.
|
||||
|
||||
Execution continues through existing Catalog Sync Runs and preprocessing, reusing
|
||||
source comments, curated descriptions and Evidence without AI description generation
|
||||
or Memory clearing. Evidence may be absent; an invalid configured source blocks
|
||||
preparation. Completed, current work is not duplicated. SSH supports metadata
|
||||
diagnostics but not sessions; select direct or REST transport for a usable workspace.
|
||||
|
||||
A destructive synchronization awaiting review returns exit code 3 and
|
||||
`schema_review_required`, with workspace and run identifiers. Open Administration,
|
||||
review the diff through its existing domain gate, then repeat `apply`. The installer
|
||||
never confirms the diff or asks for configuration interactively.
|
||||
|
||||
Before reporting `workspace_ready: true`, it checks DWH connectivity, Evidence,
|
||||
Qdrant/embedding dimensions, workflow configuration and Pi with the default model.
|
||||
**The Pi check sends a short provider request and can incur usage charges**; it
|
||||
contains no DWH data and creates no user session. `runtime_checks` retains each
|
||||
check as `pending`, `passed` or `failed`. `platform_ready` and `bindings_ready`
|
||||
remain distinct from full workspace readiness. `functional_acceptance: false`
|
||||
means a real human-reviewed question still needs testing in the UI. 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`.
|
||||
|
||||
For HTTPS Git, supply the server's specific CA in PEM format, within the 64 KiB
|
||||
protected-file limit. A complete operating-system CA bundle may exceed that limit.
|
||||
|
||||
After a failure, correct the cause and repeat `apply`. The private journal under
|
||||
`.tht/<installation>/installation-apply.json` records stages; actual service state is
|
||||
checked again. Retries preserve data, never reset volumes and never fall back to
|
||||
building sources. Changed documents or credentials require a new plan. Ctrl+C releases
|
||||
the lock; after a forcibly killed process, confirm that its owner is no longer running
|
||||
before explicitly removing a stale lock. A different release requires the upgrade
|
||||
path rather than this command.
|
||||
|
||||
If apply is interrupted during synchronization or preprocessing, repeat the same command.
|
||||
Persisted Catalog runs are read again and pending human decisions remain pending. Active
|
||||
preprocessing is awaited. If its owner has exited, recovery also checks that no orphan
|
||||
worker is still running before restarting the complete pipeline. It never clears sessions,
|
||||
curated Evidence, descriptions or Memory. Do not use `workspace preprocess clear` or volume
|
||||
deletion as a recovery remedy. Older jobs without the ownership protocol require inspection
|
||||
during an upgrade.
|
||||
|
||||
A changed credential or endpoint invalidates the old plan. Correct the documents, repeat
|
||||
`validate`, then `plan` with a new filename. If a binding was already imported, apply the
|
||||
intended correction in Administration too: bootstrap inputs must agree with the Catalog
|
||||
and never overwrite administrative changes. Other stages reconcile actual Docker/Catalog
|
||||
state without recreating existing data.
|
||||
|
||||
## Advanced source build with the same prepared documents
|
||||
|
||||
Source compilation is an explicit choice before planning. It requires a ThothII
|
||||
checkout containing the selected commit, Git, Node 24/npm, Go, Docker Buildx and
|
||||
network access for dependencies. From `backend`, after `npm ci`:
|
||||
|
||||
```bash
|
||||
node scripts/prepare-source-installation.mjs \
|
||||
--revision COMMIT --version 0.1.0-source.1 \
|
||||
--platform linux/amd64 --output /private/path/new-build
|
||||
```
|
||||
|
||||
The command builds an isolated temporary worktree, excluding local edits and
|
||||
untracked secrets. It does not publish images. The output directory must be new;
|
||||
after failure preserve its private logs and retry in a new directory. Select
|
||||
`--platform linux/arm64` explicitly when appropriate.
|
||||
|
||||
Use the resulting `bundle/bin/tht` and `bundle/release-manifest.json` in the same
|
||||
`installation validate`, `plan` and `apply` steps above. The sealed plan records
|
||||
`release.distribution: source`, revision, version and immutable local image IDs.
|
||||
Use the Docker daemon containing those images and a Linux operator host matching
|
||||
the bundle architecture; Windows runs the operator in WSL2.
|
||||
|
||||
`apply` pulls only PostgreSQL, Qdrant and Ollama and shares locks, journal,
|
||||
migrations, binding import and readiness with prebuilt installation. A missing
|
||||
local image or different source revision blocks planning, without automatic build
|
||||
fallback. Changing revision or distribution requires a separate installation or
|
||||
explicit upgrade. Source testing does not certify a public Docker Hub release.
|
||||
|
||||
## Manual source path: the two repositories
|
||||
|
||||
The remaining sections describe the existing manual path. Do not run its build/setup
|
||||
commands over an installation created with `installation apply`.
|
||||
|
||||
There are two separate repositories:
|
||||
|
||||
|
||||
@@ -14,9 +14,10 @@ un file di installazione. Usare il bundle della propria piattaforma con **entram
|
||||
gli eseguibili `tht` e `tht-workspace-documents` nella stessa cartella (`.exe` su
|
||||
Windows). Aggiungere la cartella al `PATH`, oppure usare il percorso completo.
|
||||
Il vecchio pacchetto con il solo `tht` non contiene questa capacità. Il bundle è
|
||||
attualmente producibile dal manutentore; pubblicazione degli asset e immagini
|
||||
Docker Hub appartengono a una fase successiva. Il resto della guida descrive ancora
|
||||
il percorso di installazione esistente.
|
||||
scaricabile dai [rilasci pubblici](https://git.tylconsulting.it/mptyl/ThothII/releases).
|
||||
Le immagini core e frontend sono pubblicate su Docker Hub. Per `installation apply`
|
||||
occorre un bundle che includa questo comando: la prima preview conteneva solo
|
||||
preparazione e preflight. Su Windows usare il bundle Linux in Ubuntu WSL2.
|
||||
|
||||
1. Scegliere una cartella nuova, esterna all'applicazione, con padre già esistente:
|
||||
|
||||
@@ -93,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
|
||||
@@ -117,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
|
||||
@@ -129,12 +137,14 @@ deve esistere. Non avvia servizi e non genera implicitamente password.
|
||||
e `secrets/pi-auth.json`. I file esistenti vengono conservati; se non validi, il
|
||||
comando si ferma. L'amministratore iniziale è `admin`, la password è nel file
|
||||
privato `secrets/admin-password` e non viene stampata. Il default è autenticazione
|
||||
locale con URL pubblico `http://localhost:8080`: verificare e, se necessario,
|
||||
locale con URL pubblico `http://127.0.0.1:8080`: verificare e, se necessario,
|
||||
modificare `auth/auth.yaml` prima del controllo. Questo incremento non valida il
|
||||
bootstrap OIDC del percorso esistente.
|
||||
5. Inserire la chiave del provider in `secrets/secrets.env` e creare il file della
|
||||
password DWH. Per HTTPS Git fornire i file referenziati per credenziali e CA:
|
||||
credenziali vuote sono ammesse per un remoto pubblico, la CA deve essere disponibile.
|
||||
Fornire la CA specifica del server in PEM, entro 64 KiB; l'intero bundle CA del
|
||||
sistema può superare il limite dei file protetti.
|
||||
Per SSH fornire chiave e known_hosts, scegliendo il relativo override nel descrittore.
|
||||
I provider `pi_auth` richiedono credenziali Pi già preparate. Conservare tutti
|
||||
questi file fuori dal repository workspace e proteggere l'accesso al solo utente
|
||||
@@ -185,8 +195,8 @@ tht --installation /percorso/installazione/thothii-installation.yaml installatio
|
||||
Il comando ripete i controlli dei documenti, verifica immagini/digest e Compose,
|
||||
Git, database ed Evidence esterne disponibili, poi salva il piano e il suo file
|
||||
privato `.key`. Non esegue il setup. Le immagini assenti e le dipendenze esterne
|
||||
irraggiungibili bloccano il piano. Al momento la pubblicazione reale Docker Hub
|
||||
è ancora il ticket successivo: un manifest inventato non permette di aggirarla.
|
||||
irraggiungibili bloccano il piano. Il manifest deve provenire dallo stesso rilascio
|
||||
degli eseguibili; un manifest inventato non permette di aggirare queste verifiche.
|
||||
|
||||
Correggere gli esiti `error`; leggere gli `warning`. Gli esiti
|
||||
`deferred-to-runtime` identificano controlli obbligatori dopo l'avvio, non una
|
||||
@@ -199,7 +209,121 @@ generazione LLM viene invocata; le richieste HTTP/S3 possono avere i normali cos
|
||||
del servizio. Limiti, manifest e obblighi sono nel
|
||||
[riferimento di preflight](installation-preflight.md).
|
||||
|
||||
## Prima di iniziare: i due repository
|
||||
## Avviare la piattaforma dai documenti verificati
|
||||
|
||||
Eseguire come lo stesso utente non root che ha preparato i documenti, con Docker
|
||||
locale accessibile. Il comando non pone domande e funziona anche con stdin chiuso:
|
||||
|
||||
```sh
|
||||
tht --installation /percorso/installazione/thothii-installation.yaml installation apply \
|
||||
--plan /percorso/installazione/installation-plan.json --json
|
||||
```
|
||||
|
||||
Ripete le verifiche live e del piano, copia gli asset verificati, scarica le immagini,
|
||||
inizializza i volumi della nuova installazione, avvia PostgreSQL, applica le migrazioni
|
||||
Catalog e Memory e avvia i servizi. Non compila sorgenti. L'amministratore iniziale
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
L'esecuzione prosegue con i Catalog Sync Runs esistenti e con il preprocessing:
|
||||
riusa commenti, descrizioni curate ed Evidence senza generare descrizioni con AI
|
||||
e senza cancellare Memory. Evidence assenti sono ammesse; una fonte configurata
|
||||
ma non valida blocca la preparazione. Un run già completato e ancora valido non
|
||||
viene duplicato. SSH supporta i controlli di metadati, ma non le sessioni: per un
|
||||
workspace utilizzabile scegliere un trasporto diretto o REST.
|
||||
|
||||
Se una sincronizzazione distruttiva richiede revisione, `apply` termina con codice
|
||||
3 e `schema_review_required`, riportando workspace e run. Aprire Amministrazione,
|
||||
valutare il diff e decidere nel controllo di dominio esistente, poi ripetere
|
||||
`apply`. L'installatore non conferma il diff e non chiede parametri interattivi.
|
||||
|
||||
Prima di dichiarare `workspace_ready: true`, esegue anche i controlli DWH,
|
||||
Evidence, Qdrant/dimensioni embedding, configurazione del workflow e una prova Pi
|
||||
sul provider/modello predefinito. **La prova invia una breve richiesta al provider
|
||||
e può consumare credito**; non contiene dati DWH e non crea una sessione utente.
|
||||
`runtime_checks` mostra ogni controllo come `pending`, `passed` o `failed`.
|
||||
`platform_ready` e `bindings_ready` rimangono distinti dalla readiness completa.
|
||||
`functional_acceptance: false` ricorda che la domanda reale con revisione umana
|
||||
va ancora collaudata nell'interfaccia. 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`.
|
||||
|
||||
In caso di errore, correggere la causa e ripetere `apply`: il journal privato in
|
||||
`.tht/<installazione>/installation-apply.json` registra gli stadi, mentre lo stato
|
||||
reale dei servizi viene ricontrollato. Il retry conserva i dati; non elimina volumi
|
||||
e non ricorre a una build. Dopo modifiche ai documenti o alle credenziali serve un
|
||||
nuovo piano. Ctrl+C rilascia il lock; dopo un arresto forzato del processo verificare
|
||||
che non sia più attivo prima di rimuovere esplicitamente il suo lock residuo.
|
||||
Un rilascio differente richiede il percorso di aggiornamento, non questo comando.
|
||||
|
||||
Se `apply` viene interrotto durante sync o preprocessing, ripetere lo stesso comando.
|
||||
I run Catalog persistiti vengono riletti; una decisione umana pendente resta pendente.
|
||||
Il preprocessing in corso viene atteso. Se il suo proprietario è terminato, la ripresa
|
||||
verifica anche l'assenza di processi figli ancora attivi e riesegue la pipeline completa
|
||||
con il contratto esistente. Non cancella sessioni, Evidence curate, descrizioni o Memory.
|
||||
Non usare `workspace preprocess clear` o la cancellazione dei volumi come rimedio.
|
||||
I vecchi job senza il protocollo di ownership richiedono un'ispezione durante upgrade.
|
||||
|
||||
Una credenziale o un endpoint modificato rende il piano vecchio inutilizzabile.
|
||||
Correggere i documenti e ripetere `validate` e `plan` con un nome di piano nuovo.
|
||||
Se il binding era già importato, applicare la correzione voluta anche in Amministrazione:
|
||||
il bootstrap deve corrispondere al Catalog, non sovrascrive modifiche amministrative.
|
||||
Le altre fasi vengono riconciliate con Docker e Catalog senza ricreare dati già presenti.
|
||||
|
||||
## Percorso avanzato da sorgenti con gli stessi documenti
|
||||
|
||||
La build è una scelta esplicita precedente alla predisposizione del piano.
|
||||
Richiede un checkout ThothII con il commit desiderato, Git, Node 24/npm, Go,
|
||||
Docker Buildx e rete per le dipendenze. Da `backend`, dopo `npm ci`:
|
||||
|
||||
```bash
|
||||
node scripts/prepare-source-installation.mjs \
|
||||
--revision COMMIT --version 0.1.0-source.1 \
|
||||
--platform linux/amd64 --output /percorso/privato/build-nuova
|
||||
```
|
||||
|
||||
Il comando usa un worktree temporaneo del commit, escludendo modifiche locali e
|
||||
segreti non tracciati. Non pubblica immagini. L'output deve essere nuovo; se la
|
||||
build fallisce, conservarne i log privati e riprovare in una nuova directory.
|
||||
Per Linux arm64 scegliere esplicitamente `--platform linux/arm64`.
|
||||
|
||||
Usare `bundle/bin/tht` e `bundle/release-manifest.json` prodotti dal comando
|
||||
negli stessi passi `installation validate`, `plan` e `apply` descritti sopra.
|
||||
Il piano sigilla `release.distribution: source`, revisione, versione e identità
|
||||
immutabili delle immagini locali. L'operatore deve usare lo stesso daemon Docker
|
||||
che contiene quelle immagini; la piattaforma del bundle deve corrispondere al
|
||||
sistema Linux che esegue l'operatore. Su Windows usare WSL2.
|
||||
|
||||
`apply` scarica solo PostgreSQL, Qdrant e Ollama. Usa gli stessi lock, journal,
|
||||
migrazioni, binding e controlli di readiness del percorso precompilato. Un'immagine
|
||||
locale mancante o di un'altra revisione blocca il piano: nessuna build automatica.
|
||||
Cambiare revisione o modalità richiede una nuova installazione o il percorso
|
||||
esplicito di aggiornamento. La prova da sorgenti non vale come accettazione del
|
||||
rilascio pubblico Docker Hub.
|
||||
|
||||
## Percorso manuale da sorgenti: i due repository
|
||||
|
||||
Le sezioni successive documentano il percorso manuale esistente. Non eseguire i
|
||||
suoi comandi di build o setup sopra un'installazione creata con `installation apply`.
|
||||
|
||||
Servono due repository distinti:
|
||||
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
# First installation prerelease — ticket #46
|
||||
|
||||
Date: 2026-09-28. Source: `ec0421e9fd47176f4883a4e9b4054d5c2a3ad2b8`.
|
||||
Branch: `codex/guided-standalone-install`. Platform: **linux/amd64**.
|
||||
|
||||
## Public artifacts
|
||||
|
||||
- [Gitea prerelease and downloads](https://git.tylconsulting.it/mptyl/ThothII/releases/tag/installation-v0.1.0-install-preview.1)
|
||||
- [Docker Hub core](https://hub.docker.com/r/tylconsulting/thothii-core)
|
||||
- [Docker Hub frontend](https://hub.docker.com/r/tylconsulting/thothii-frontend)
|
||||
- Image version: `0.1.0-install-preview.1`.
|
||||
- Git tag: `installation-v0.1.0-install-preview.1`.
|
||||
|
||||
The release was created as a draft, then made public only after image pulls,
|
||||
smoke tests and uploaded attachment checks passed. Docker and Git credential
|
||||
stores supplied publisher authentication; no token is present in this report,
|
||||
the source worktree or the release bundle.
|
||||
|
||||
Archive: `thothii-0.1.0-install-preview.1-linux-amd64.tar.gz` (40,926,764 bytes).
|
||||
SHA-256: `4c130276a265c3c66249abb39e3c1cf02b8603efc00a06985d91385bd8112fff`.
|
||||
`SHA256SUMS.txt` is the second release attachment.
|
||||
|
||||
The archive contains native `tht` and its sibling workspace/document validator,
|
||||
the release manifest, Compose files, initialization scripts/SQL and IT/EN guides.
|
||||
There is no application checkout, user workspace, environment credential file,
|
||||
example database or embedded compiler dependency on the consumer host.
|
||||
|
||||
## Immutable image references
|
||||
|
||||
All references use `docker.io/` and SHA-256 platform manifests:
|
||||
|
||||
| Role | Repository | Digest |
|
||||
| --- | --- | --- |
|
||||
| Core, Catalog migration, workspace maintenance | `tylconsulting/thothii-core` | `7ac0b3362c93837c02d9f8d3153d3ab3441cc43594ee7786dafc845a69d5c956` |
|
||||
| Frontend | `tylconsulting/thothii-frontend` | `2f2b5426a96687702c1f2574c547ea1d1c339419dae05382e83f3706eec6a582` |
|
||||
| Catalog | `library/postgres` | `45cd22f8d32e189d245403954882f88e7a8714301fda80dab6da90f1265b25a3` |
|
||||
| Qdrant | `qdrant/qdrant` | `da65a06bc75e42702f80c992b99c5144b0fbd675ae7a96d2991de0bf957b7071` |
|
||||
| Embedding and model initialization | `ollama/ollama` | `67366844c1f0ed498888b8ee804f629d47ff22a4b559d76154154249bff0dd44` |
|
||||
|
||||
## Verification
|
||||
|
||||
- Backend: 111 test files passed; 1,422 tests passed, 41 skipped. Typecheck passed.
|
||||
- Producer: seven tests passed, covering real-source packaging, interrupted
|
||||
preparation, immutable published retries, registry digest/platform verification,
|
||||
redirect credential isolation, conflicting Git tags and subprocess timeouts.
|
||||
- Strict MkDocs build passed with 22 allowed public pages.
|
||||
- Both images built from the detached source commit and pushed successfully.
|
||||
- All five image roles pulled by digest using an empty Docker client configuration.
|
||||
- Network-isolated core checks: embedded Pi version, workflow CLI, migration and
|
||||
workspace-maintenance assets. Frontend configuration smoke passed.
|
||||
- Packaged Compose rendered without a source checkout or installation credentials.
|
||||
- Gitea attachment bytes matched local checksums before and after publication;
|
||||
the public download checks used no authentication. Git tag matched source SHA.
|
||||
- Re-running the identical publication command after completion succeeded through
|
||||
the existing-release path, verifying images and public attachments without
|
||||
rebuilding, uploading replacement files or republishing the release.
|
||||
- In a network-isolated Linux amd64 PostgreSQL container, the downloaded-format
|
||||
bundle reported the correct release/commit and successfully performed
|
||||
`workspace prepare`, `workspace validate` and `installation prepare`. Those
|
||||
commands used the two bundled executables mounted read-only; no application
|
||||
checkout, Node, Bun or Python was mounted into the consumer container.
|
||||
|
||||
## Remaining acceptance
|
||||
|
||||
This is an image and tooling prerelease. It includes document preparation,
|
||||
validation, preflight and planning delivered by #43–45. It does not yet implement
|
||||
the full non-interactive execution, binding import, workspace readiness or recovery
|
||||
increments. Example databases remain deferred independently.
|
||||
|
||||
The publisher ran on macOS with Linux amd64 container execution. This is not the
|
||||
manual Windows/WSL2 installation gate. That gate follows integration of the
|
||||
remaining installer tickets and requires a newly published integrated release,
|
||||
real DWH/model endpoints, one human-reviewed question and persistence checks.
|
||||
Omarchy and macOS acceptance follow Windows in separate steps.
|
||||
@@ -0,0 +1,97 @@
|
||||
# Published installation platform apply
|
||||
|
||||
Date: 2026-10-06. Scope: [Installare la piattaforma dal rilascio senza domande](https://git.tylconsulting.it/mptyl/ThothII/issues/47).
|
||||
|
||||
The public [0.1.0-install-preview.5 release](https://git.tylconsulting.it/mptyl/ThothII/releases/tag/installation-v0.1.0-install-preview.5)
|
||||
contains the native operator, validator and immutable Docker Hub image references for
|
||||
Linux amd64 and arm64. Source revision: `24b03d4caf2998b424038435bf6d0d4e241469b5`.
|
||||
Use this preview for platform apply; earlier previews do not establish this result.
|
||||
Publication attempts 2 and 4 were interrupted in draft; preview 3 was superseded
|
||||
after the full consumer trial exposed maintenance-profile and default-origin issues.
|
||||
|
||||
## Result and scope
|
||||
|
||||
The final trial downloaded the public arm64 archive and checksum anonymously, then
|
||||
used its unmodified executables inside Ubuntu 24.04 with Docker CLI/Compose. The
|
||||
consumer had no separately installed Node, Python, Bun, Go or application checkout.
|
||||
Its bind-mounted input directory supplied the released bundle and private test
|
||||
documents; no application source checkout was mounted or compiled by the consumer.
|
||||
|
||||
The Linux consumer used Docker Desktop on an arm64 Mac host. This is an automated
|
||||
platform execution proof, **not** Windows, Omarchy or macOS fresh-machine acceptance.
|
||||
Manual acceptance remains ordered Windows/WSL2, then Omarchy, then macOS.
|
||||
|
||||
| Check | Observed result |
|
||||
| --- | --- |
|
||||
| Workspace preparation and validation | Native released tools; ad hoc Chinook workspace, Evidence absent |
|
||||
| Application preparation, credentials and validation | Native released tools; protected files, generated local administrator |
|
||||
| Live plan | Released manifest, registry, Compose, HTTPS Git and real PostgreSQL reader probe passed |
|
||||
| Platform apply | Closed stdin, no source build, immutable pulls, volume initialization, Catalog/Memory migrations, service startup |
|
||||
| Repeat apply | Passed; existing installation reconciled |
|
||||
| Frontend | HTTP 200 |
|
||||
| Workspace API without authentication | HTTP 401 |
|
||||
| Prepared administrator login | HTTP 200 |
|
||||
| Native CLI user addition | New user could log in without restarting core |
|
||||
| Native CLI user disable | Existing session immediately received HTTP 401 |
|
||||
| Final readiness | `platform_ready: true`, `workspace_ready: false` |
|
||||
|
||||
The completed trial timestamp was `2026-10-06T14:19:12.714Z`. Application test
|
||||
containers were stopped afterwards; their volumes and private documents were retained.
|
||||
The final user-add/disable probe intentionally changed authentication inputs, so a
|
||||
subsequent apply requires a fresh plan rather than reusing the pre-mutation plan.
|
||||
|
||||
The separate Chinook fixture contained 11 tables, 3,503 tracks, 412 invoices and
|
||||
2,240 invoice lines. Preflight used `thoth_reader`, not the database administrator.
|
||||
The HTTPS Git check used the public ThothII repository only as an accessible remote
|
||||
for this platform fixture; it did not activate the local Chinook workspace from that
|
||||
remote. Repository activation and matching workspace revisions remain part of binding
|
||||
import. A synthetic provider key was used; no LLM generation or credential-validity
|
||||
claim was made. No database binding was imported into the application Catalog.
|
||||
|
||||
## Changes and regression coverage
|
||||
|
||||
- `installation apply --plan` verifies the sealed inputs and repeats live checks,
|
||||
then executes under the installation lifecycle lock with an atomic private journal.
|
||||
- Runtime services use the preparing non-root operator's identity. Original private
|
||||
authentication files stay authoritative; updates and revocation remain live.
|
||||
- A pinned offline helper initializes only owned volumes. Ready volumes are never
|
||||
recursively chowned. Pi home and harness configuration volumes preserve their seed
|
||||
files; PostgreSQL uses a data subdirectory beneath its initialization marker.
|
||||
- Migration execution bypasses Pi home initialization. The PostgreSQL health check
|
||||
waits for TCP readiness rather than accepting the temporary `initdb` server.
|
||||
- Compose validation explicitly includes both maintenance profiles. Authentication
|
||||
preparation defaults to `http://127.0.0.1:8080`, and validation rejects incompatible
|
||||
local origins before startup.
|
||||
- Atomic publication propagates write/short-write errors and never exposes partial
|
||||
final assets. Initialization markers remain root-owned across interrupted seeding.
|
||||
|
||||
Validation included the full Go suite (`go test -p 1 ./...`), affected-package tests
|
||||
after subsequent fixes, native public-command prepare/plan/apply/retry with closed
|
||||
stdin, Windows CLI cross-compilation, release producer tests and strict documentation
|
||||
build. A cancellation test hit its existing short deadline during the initial parallel
|
||||
suite; its focused rerun and serialized suite passed.
|
||||
|
||||
The opt-in Docker identity test used published images and actual Linux volume
|
||||
ownership. It exercised an interruption immediately before the ready marker, private
|
||||
password access, both migration scripts, Pi writes, PostgreSQL restart and preservation
|
||||
of an inserted row. Final published-bundle execution then verified the complete
|
||||
platform path independently of the controlled Docker boundary used by unit tests.
|
||||
|
||||
## Published archive checksums
|
||||
|
||||
| Archive | SHA-256 |
|
||||
| --- | --- |
|
||||
| `thothii-0.1.0-install-preview.5-linux-amd64.tar.gz` | `51393b1cfc99afed790fc947535f319c7ae37691eb024a8b27bb643983e9e0c3` |
|
||||
| `thothii-0.1.0-install-preview.5-linux-arm64.tar.gz` | `9077ca5acf5a2c2997b9bf03edc0b7ba0cb966c4955b645c880a1a85b758781c` |
|
||||
|
||||
Exact image digests are in each archive's `release-manifest.json`. Publication verified
|
||||
anonymous pulls of all five image roles and core/frontend smoke checks on both CPUs.
|
||||
|
||||
## Remaining work
|
||||
|
||||
[Apply prepared Catalog bindings](https://git.tylconsulting.it/mptyl/ThothII/issues/48)
|
||||
and [workspace runtime readiness](https://git.tylconsulting.it/mptyl/ThothII/issues/49)
|
||||
remain separate increments. The explicit source-mode integration and recovery across
|
||||
all stages are also pending. A human-reviewed question and the Windows/WSL2 acceptance
|
||||
exercise follow those increments. Curated example databases and Evidence remain the
|
||||
deferred examples subproject.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,36 @@
|
||||
# Installation workspace readiness — T07/#49
|
||||
|
||||
Implemented on `codex/guided-standalone-install`, following binding import T06.
|
||||
|
||||
`installation apply` now calls existing authenticated Catalog Sync Runs and
|
||||
workspace preprocessing services. It polls existing work, skips current completed
|
||||
preparation and never confirms destructive schema changes. Pending human review
|
||||
returns exit 3, the workspace/run identifier and an Administration instruction.
|
||||
It does not generate AI descriptions, clear Memory or overwrite curated content.
|
||||
Optional Evidence remains optional; invalid configured Evidence blocks readiness.
|
||||
|
||||
Named, bounded one-shot containers run the existing workspace, workflow and
|
||||
Pi/default-provider diagnostics. Reports preserve pending/failed runtime checks
|
||||
and distinguish platform, bindings, workspace readiness and functional acceptance.
|
||||
A real human-reviewed question remains manual acceptance. The Pi smoke sends a
|
||||
short provider request without DWH context and can incur usage charges.
|
||||
|
||||
## Verification
|
||||
|
||||
- Focused backend tests: 55 passed, including actual Catalog APIs preserving the
|
||||
same destructive review and source comments across two installation retries.
|
||||
- Full backend suite on Node 24.16.0: 1,436 passed, 41 skipped, one failure in the
|
||||
existing concurrent OIDC state-creation test. Its isolated 48-test group passed
|
||||
on immediate rerun. Repeating the full suite with two workers passed all 1,437
|
||||
tests (41 skipped, 114 files passed).
|
||||
- TypeScript typecheck and full Go suite passed.
|
||||
- Rebuilt native macOS arm64 bundle: public prepare/validate/plan/apply/retry test
|
||||
passed with closed stdin and no language runtimes in PATH. Docker is an external
|
||||
process fixture in that test, so this is not a real OS/platform acceptance.
|
||||
- Strict documentation build passed; release-bundle packaging regression passed.
|
||||
- Standards and Spec reviews found no actionable violations.
|
||||
|
||||
The current public preview.5 predates this code. These checks do not constitute a
|
||||
published-image consumer proof, a real provider acceptance, or Windows/WSL2,
|
||||
Omarchy or macOS manual acceptance. Integrated source mode and comprehensive
|
||||
interruption recovery are subsequent T08/T09 increments.
|
||||
@@ -0,0 +1,41 @@
|
||||
# Installation recovery — T09/#51
|
||||
|
||||
The installer retains pending schema review even when a durable synchronization's
|
||||
reservation blocks binding import. It waits for busy operations, retries interrupted
|
||||
sync through the domain API and explicitly requests guarded preprocessing recovery.
|
||||
|
||||
Preprocessing now uses the existing kernel writer-lock mechanism plus inherited
|
||||
worker locks and an owner-generation check. A surviving orphan worker prevents
|
||||
recovery; a delayed worker from an older generation cannot start. Once absence of
|
||||
writers is established, the Catalog fingerprint/revision/run-identity CAS marks an orphaned
|
||||
current-protocol run interrupted and the full pipeline can run again. Legacy owners
|
||||
without this protocol are not silently adopted. Clear operations use the same guard
|
||||
but are never invoked by installation recovery.
|
||||
|
||||
No new Catalog authority or generic reset was added. Existing document seals detect
|
||||
changed credentials and inputs; corrected documents need a new plan. Imported binding
|
||||
changes must also be reconciled through Administration, preserving intentional edits.
|
||||
Source and prebuilt installations share this behavior.
|
||||
|
||||
Migration 015 stores the attempt identity so a late completion cannot finish a new
|
||||
attempt using the same inputs. Ownership is rechecked after asynchronous work before
|
||||
updating the job. Regression tests kill the real lock holder during semantic preflight
|
||||
and verify rejection of a stale completion against real PostgreSQL.
|
||||
|
||||
Real source installation exposed two additional contract defects: containerd image
|
||||
stores may identify a locally loaded image by its manifest rather than Buildx's config
|
||||
digest; unsupported Git ports must fail document validation before runtime startup.
|
||||
Both now have regression tests. A fresh installation also uses `low` reasoning for
|
||||
the Pi smoke when neither installation nor saved settings select a level.
|
||||
|
||||
Verification includes real kernel-lock/child-process tests, delayed-worker rejection,
|
||||
service retry after Catalog completion loss, legacy-owner refusal, authenticated route
|
||||
conflict handling and installation client readiness checks. Full suite results and
|
||||
published consumer acceptance are recorded after completion, not inferred from mocks.
|
||||
|
||||
Validation before publication: the full backend suite and all Go packages passed;
|
||||
backend typecheck, source-producer tests and the strict documentation build passed.
|
||||
After aligning the in-memory Catalog test double with the new run identity, the
|
||||
focused Catalog route/service/identity suite passed (39 tests), as did typecheck.
|
||||
Standards and Spec reviews found no remaining production blocker. Real consumer
|
||||
fault-recovery acceptance remains pending at this commit.
|
||||
@@ -0,0 +1,16 @@
|
||||
# Explicit source installation — T08/#50
|
||||
|
||||
The advanced `backend/scripts/prepare-source-installation.mjs` command builds core
|
||||
and frontend from an isolated committed worktree, loads local image IDs and creates
|
||||
a source bundle. It never publishes images or uses uncommitted operator files.
|
||||
Native planning checks local image identity, OCI revision/version and architecture;
|
||||
the sealed manifest records source mode. Apply shares document validation, lock,
|
||||
journal, migrations, binding import and readiness with the prebuilt path. Only
|
||||
upstream service images are pulled. Switching distribution is not an implicit upgrade.
|
||||
|
||||
Verification before the real source build: source producer command-boundary and
|
||||
bundle tests passed (3 Node tests including prebuilt packaging); Go preflight and
|
||||
apply suites passed, including local identity rejection, no registry fallback and
|
||||
source apply through the common readiness stages. Standards and Spec review found
|
||||
no code findings. A real build/start proof remains pending and is required before
|
||||
calling T08 acceptance complete; it does not certify a published-image installation.
|
||||
@@ -0,0 +1,112 @@
|
||||
# First installation acceptance fixture: Chinook without Evidence
|
||||
|
||||
Decision agreed on 2026-09-28: the first installer acceptance may use one ad hoc
|
||||
workspace and a downloadable local database without Evidence. The three curated
|
||||
example databases remain a separate deferred subproject.
|
||||
|
||||
Use [Chinook v1.4.5](https://github.com/lerocha/chinook-database/releases/tag/v1.4.5),
|
||||
the sample digital music store. The upstream PostgreSQL SQL asset contains both
|
||||
schema and data: 11 related tables for artists, albums, tracks, customers, employees,
|
||||
invoices and playlists. The source is licensed under
|
||||
[MIT](https://github.com/lerocha/chinook-database/blob/master/LICENSE.md).
|
||||
This fixture does not supply Evidence or claim that SQL schema information is Evidence.
|
||||
It uses native PostgreSQL DDL/data, so SQLite type conversion is not involved.
|
||||
|
||||
## Prepare the independent test database
|
||||
|
||||
Run in Ubuntu WSL2 with Docker Desktop integration, or in a Linux/macOS Bash
|
||||
terminal for a preliminary check. Docker, curl and OpenSSL must be available.
|
||||
The first formal host acceptance remains Windows/WSL2.
|
||||
|
||||
The helper below is in the ThothII repository for maintainers/testers; it is not
|
||||
yet included in the downloadable operator bundle. It provisions only the test DWH,
|
||||
which is a separate container from the installation's PostgreSQL Metadata Catalog.
|
||||
|
||||
```bash
|
||||
cd /path/to/ThothII
|
||||
bash scripts/prepare-chinook-test.sh "$HOME/thothii-chinook-test"
|
||||
```
|
||||
|
||||
Use a new directory outside any workspace repository. The helper pins the upstream
|
||||
SQL version and checksum, creates private random passwords, starts PostgreSQL,
|
||||
imports schema/data, and creates `thoth_reader` with SELECT privileges. Passwords
|
||||
remain in the private directory, not in a workspace YAML or this repository.
|
||||
An existing directory or container is refused; the helper never resets it.
|
||||
An interrupted preparation leaves its private logs/container available for diagnosis.
|
||||
Do not rerun the upstream import manually against another database: its opening
|
||||
statements drop and recreate `chinook`.
|
||||
|
||||
Default container: `thothii-test-chinook`. Host endpoint: `127.0.0.1:55432`.
|
||||
Override names/port before the command if needed:
|
||||
|
||||
```bash
|
||||
CHINOOK_TEST_CONTAINER=my-chinook CHINOOK_TEST_PORT=55433 \
|
||||
bash scripts/prepare-chinook-test.sh "$HOME/my-chinook-test"
|
||||
```
|
||||
|
||||
Expected import counts: 11 tables, 3,503 tracks, 412 invoices and 2,240 invoice lines.
|
||||
The SQL download is 600,200 bytes. Its SHA-256 is
|
||||
`e3fde5c1a5b51a2a91429a702c9ca6e69ba56e6c7f5e112724d70c3d03db695e`.
|
||||
|
||||
Stop/start retains the database:
|
||||
|
||||
```bash
|
||||
docker stop thothii-test-chinook
|
||||
docker start thothii-test-chinook
|
||||
```
|
||||
|
||||
Only when deliberately discarding this test database, `docker rm -f -v
|
||||
thothii-test-chinook` removes the container and its anonymous data volume. Private
|
||||
files in the preparation directory are separate and remain until removed explicitly.
|
||||
|
||||
## Prepare the workspace documents
|
||||
|
||||
Using the native bundle, keep `tht` beside `tht-workspace-documents` and run:
|
||||
|
||||
```bash
|
||||
/path/to/bundle/bin/tht workspace prepare \
|
||||
--directory "$HOME/thothii-workspaces-test" \
|
||||
--id chinook-test --name "Chinook installation test" --language it
|
||||
/path/to/bundle/bin/tht workspace validate \
|
||||
--directory "$HOME/thothii-workspaces-test"
|
||||
```
|
||||
|
||||
The generated workspace has Evidence absent. Keep that configuration; no fake
|
||||
Evidence document or credential should be added merely to satisfy installation.
|
||||
|
||||
The later installation-local binding must select PostgreSQL, database `chinook`,
|
||||
schema `public`, user `thoth_reader`, and reference the private `reader-password`
|
||||
file. Do not use the PostgreSQL administrator as the ThothII data source account.
|
||||
The host endpoint above is for host-side tools: `127.0.0.1` inside ThothII core
|
||||
would refer to core itself. At integration, configure and verify connectivity from
|
||||
both the preflight process and the core container; do not copy the host endpoint
|
||||
unchanged into a runtime binding. That integration belongs to the remaining
|
||||
installer/binding tickets and is not established by successful import here.
|
||||
|
||||
## Acceptance scope
|
||||
|
||||
After the remaining installer increments are available, verify prepared documents,
|
||||
non-interactive setup using published images, database connection, schema sync,
|
||||
required preprocessing/readiness and a real human-reviewed question. Then verify
|
||||
stop/start preserves application state. These checks do not validate Evidence
|
||||
ingestion, retrieval or interpretation; record those as not exercised for this fixture.
|
||||
|
||||
Suggested practice questions, without target SQL:
|
||||
|
||||
- Which five artists have the most tracks in the catalogue?
|
||||
- Which countries have the largest total invoice amounts?
|
||||
- Which customers bought tracks from more than three genres?
|
||||
|
||||
These are practice prompts, not benchmark scores or a substitute for human review.
|
||||
Windows/WSL2 acceptance is followed by Omarchy and macOS in separate steps.
|
||||
|
||||
## Preliminary verification, 2026-09-28
|
||||
|
||||
The helper imported the pinned SQL into a fresh Linux amd64 PostgreSQL container
|
||||
on the macOS development host. Counts matched the values above. A real TCP
|
||||
connection using the generated `thoth_reader` password read the data;
|
||||
`default_transaction_read_only` was `on`, and an UPDATE without matching rows
|
||||
was still rejected with SQLSTATE `42501` even inside `BEGIN READ WRITE`.
|
||||
Native workspace preparation and JSON validation reported `ok: true` and
|
||||
`evidence: absent`, explicitly deferring Catalog binding, connectivity and runtime
|
||||
preprocessing. These are fixture checks, not Windows or full-installer acceptance.
|
||||
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env bash
|
||||
# Disposable acceptance fixture, separate from the ThothII Metadata Catalog.
|
||||
set -euo pipefail
|
||||
umask 077
|
||||
|
||||
if [[ $# -ne 1 || "$1" != /* || -e "$1" ]]; then
|
||||
echo 'Usage: bash scripts/prepare-chinook-test.sh /absolute/NEW-private-directory' >&2
|
||||
exit 2
|
||||
fi
|
||||
test_dir="$1"
|
||||
container="${CHINOOK_TEST_CONTAINER:-thothii-test-chinook}"
|
||||
port="${CHINOOK_TEST_PORT:-55432}"
|
||||
[[ "$container" =~ ^[a-zA-Z0-9][a-zA-Z0-9_.-]+$ ]] || exit 2
|
||||
[[ "$port" =~ ^[1-9][0-9]{0,4}$ ]] && (( port <= 65535 )) || exit 2
|
||||
for executable in docker curl openssl; do command -v "$executable" >/dev/null; done
|
||||
docker info >/dev/null
|
||||
if docker container inspect "$container" >/dev/null 2>&1; then
|
||||
echo "Container $container already exists; this command never resets an existing database." >&2
|
||||
exit 2
|
||||
fi
|
||||
mkdir "$test_dir"
|
||||
test_dir="$(cd "$test_dir" && pwd -P)"
|
||||
sql="$test_dir/Chinook_PostgreSql.sql"
|
||||
curl --fail --location --proto '=https' --tlsv1.2 --max-time 120 \
|
||||
'https://github.com/lerocha/chinook-database/releases/download/v1.4.5/Chinook_PostgreSql.sql' \
|
||||
--output "$sql"
|
||||
expected=e3fde5c1a5b51a2a91429a702c9ca6e69ba56e6c7f5e112724d70c3d03db695e
|
||||
actual="$(openssl dgst -sha256 "$sql")"
|
||||
[[ "${actual##* }" == "$expected" ]] || { echo 'Chinook checksum mismatch.' >&2; exit 1; }
|
||||
openssl rand -hex 24 > "$test_dir/reader-password"
|
||||
printf 'POSTGRES_PASSWORD=%s\n' "$(openssl rand -hex 24)" > "$test_dir/postgres.env"
|
||||
printf '%s\n' "$container" > "$test_dir/container-name"
|
||||
|
||||
# Use the same PostgreSQL linux/amd64 image as the initial installation prerelease.
|
||||
# PostgreSQL gets its own anonymous data volume; stop/start preserves it.
|
||||
docker run --detach --name "$container" --platform linux/amd64 \
|
||||
--publish "127.0.0.1:${port}:5432" \
|
||||
--env-file "$test_dir/postgres.env" \
|
||||
docker.io/library/postgres@sha256:45cd22f8d32e189d245403954882f88e7a8714301fda80dab6da90f1265b25a3 >/dev/null
|
||||
ready=false
|
||||
for ((attempt = 0; attempt < 90; attempt++)); do
|
||||
# The entrypoint's temporary bootstrap server has only a Unix socket.
|
||||
if docker exec "$container" pg_isready -h 127.0.0.1 -U postgres -d postgres >/dev/null 2>&1; then
|
||||
ready=true
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
[[ "$ready" == true ]] || { echo "PostgreSQL did not start. Inspect docker logs $container." >&2; exit 1; }
|
||||
# The upstream script drops/recreates chinook: it is used only in this NEW container.
|
||||
docker exec -i "$container" psql -X -U postgres -d postgres -v ON_ERROR_STOP=1 < "$sql" > "$test_dir/import.log" 2>&1
|
||||
{
|
||||
printf "CREATE ROLE thoth_reader LOGIN PASSWORD '%s';\n" "$(cat "$test_dir/reader-password")"
|
||||
cat <<'SQL'
|
||||
GRANT CONNECT ON DATABASE chinook TO thoth_reader;
|
||||
GRANT USAGE ON SCHEMA public TO thoth_reader;
|
||||
GRANT SELECT ON ALL TABLES IN SCHEMA public TO thoth_reader;
|
||||
ALTER ROLE thoth_reader SET default_transaction_read_only = on;
|
||||
SQL
|
||||
} | docker exec -i "$container" psql -X -U postgres -d chinook -v ON_ERROR_STOP=1 > "$test_dir/reader-setup.log" 2>&1
|
||||
docker exec "$container" psql -X -U postgres -d chinook -v ON_ERROR_STOP=1 -c \
|
||||
"SELECT (SELECT count(*) FROM information_schema.tables WHERE table_schema='public' AND table_type='BASE TABLE') AS tables, (SELECT count(*) FROM track) AS tracks, (SELECT count(*) FROM invoice) AS invoices, (SELECT count(*) FROM invoice_line) AS invoice_lines;"
|
||||
printf '\nReady: container=%s, host=127.0.0.1, port=%s, database=chinook, schema=public, user=thoth_reader\n' "$container" "$port"
|
||||
printf 'Protected password file: %s/reader-password\n' "$test_dir"
|
||||
printf 'Use this read-only account for ThothII. Evidence is absent. No ThothII stack was started.\n'
|
||||
@@ -97,6 +97,35 @@ THT_INSTALLATION_TEST_CLI=/absolute/path/dist/workspace-tools/darwin-arm64/tht \
|
||||
go test ./cmd/tht -run TestNativeInstallationPlanBeforeContainersExist -count=1
|
||||
```
|
||||
|
||||
## Non-interactive platform apply (issue #47)
|
||||
|
||||
With the matching released operator and a fresh sealed plan:
|
||||
|
||||
```sh
|
||||
tht --installation /absolute/path/thothii-installation.yaml \
|
||||
installation apply --plan /absolute/path/installation-plan.json --json
|
||||
```
|
||||
|
||||
The command repeats checks, pulls immutable images, initializes local runtime identity
|
||||
and volumes, migrates Catalog/Memory and starts the platform without stdin prompts.
|
||||
It preserves original protected authentication files and uses the non-root preparing
|
||||
operator's UID. Retry reconciles services and preserves existing data. Platform success
|
||||
does not claim workspace readiness. See the IT/EN guides for recovery and limitations.
|
||||
|
||||
The native fixture test above also exercises apply and retry with closed stdin and
|
||||
without host Node/Python/Bun. An additional opt-in proof uses the already-published
|
||||
preview images to test Linux volume ownership, interrupted initialization, PostgreSQL
|
||||
startup with a private password file and data preservation across restart:
|
||||
|
||||
```sh
|
||||
cd tools/tht
|
||||
THT_INSTALLATION_DOCKER_TEST=1 go test ./internal/installapply \
|
||||
-run TestPublishedImagesAcceptProtectedOperatorIdentity -count=1 -v
|
||||
```
|
||||
|
||||
This proof needs the pinned amd64 images pulled locally. Emulation on another CPU is
|
||||
a runtime compatibility check, not platform certification.
|
||||
|
||||
## Shell configuration
|
||||
|
||||
The schema-v2 `thothii-installation.yaml` accepts this optional section:
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/compose"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/installapply"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/preflight"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/version"
|
||||
)
|
||||
|
||||
func installationApplyCommand(ctx context.Context, installationPath string, args []string, stdout io.Writer) int {
|
||||
structured := slices.Contains(args, "--json")
|
||||
write := func(result installapply.Result) {
|
||||
if structured {
|
||||
_ = json.NewEncoder(stdout).Encode(result)
|
||||
} else {
|
||||
fmt.Fprintf(stdout, "%s: %s\n", result.Stage, result.Action)
|
||||
}
|
||||
}
|
||||
var planPath string
|
||||
valid := len(args) > 0 && args[0] == "apply" && filepath.IsAbs(installationPath)
|
||||
seenJSON := false
|
||||
for index := 1; index < len(args); index++ {
|
||||
switch args[index] {
|
||||
case "--json":
|
||||
if seenJSON {
|
||||
valid = false
|
||||
}
|
||||
seenJSON = true
|
||||
case "--plan":
|
||||
if planPath != "" || index+1 >= len(args) {
|
||||
valid = false
|
||||
} else {
|
||||
index++
|
||||
planPath = args[index]
|
||||
}
|
||||
default:
|
||||
valid = false
|
||||
}
|
||||
}
|
||||
if !valid || !filepath.IsAbs(planPath) {
|
||||
write(installapply.Result{SchemaVersion: 1, Stage: "usage", Action: "Use --installation ABS_PATH installation apply --plan ABS_PLAN [--json]."})
|
||||
return 2
|
||||
}
|
||||
runner := compose.NewRunnerWithEnvironment("", installationDockerEnvironment())
|
||||
check := func(ctx context.Context, p preflight.Plan) error {
|
||||
if version.Current().Commit != p.Release.Revision || version.Current().Version != p.Release.Version {
|
||||
return errors.New("use the operator supplied with this release")
|
||||
}
|
||||
var documents bytes.Buffer
|
||||
if installationDocumentsCommand(ctx, installationPath, []string{"validate", "--workspaces", p.WorkspaceDirectory, "--bootstrap", p.BootstrapPath, "--json"}, &documents) != 0 {
|
||||
return errors.New("prepared documents failed validation")
|
||||
}
|
||||
host, err := preflight.InspectHost(p.Installation.ProjectDirectory)
|
||||
if err != nil || "linux/"+host.Arch != p.Platform {
|
||||
return errors.New("host platform differs from plan")
|
||||
}
|
||||
report := preflight.CheckHost(ctx, runner, host, p.Release.Requirements)
|
||||
if report.OK {
|
||||
report.Merge(preflight.CheckImages(ctx, runner, p.Release, p.Platform))
|
||||
}
|
||||
if report.OK {
|
||||
report.Merge(preflight.CheckCompose(ctx, runner, p.Installation, p.Release, p.ManifestPath, p.Platform))
|
||||
}
|
||||
if report.OK {
|
||||
report.Merge(preflight.CheckExternal(ctx, p.Installation))
|
||||
}
|
||||
if report.OK {
|
||||
var out, discarded bytes.Buffer
|
||||
bound, cancel := context.WithTimeout(ctx, 60*time.Second)
|
||||
defer cancel()
|
||||
code := workspaceDocumentsCommand(bound, []string{"probe", "--directory", p.WorkspaceDirectory, "--bootstrap", p.BootstrapPath, "--json"}, &out, &discarded)
|
||||
var probes preflight.Report
|
||||
if code != 0 || json.Unmarshal(out.Bytes(), &probes) != nil || !probes.OK || len(probes.Checks) == 0 {
|
||||
return errors.New("current database/evidence probes failed")
|
||||
}
|
||||
}
|
||||
if !report.OK {
|
||||
return errors.New("current prerequisites failed")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
result, err := installapply.Run(ctx, installapply.Request{PlanPath: planPath, InstallationPath: installationPath}, runner, check)
|
||||
write(result)
|
||||
if err != nil {
|
||||
if result.NeedsReview() {
|
||||
return 3
|
||||
}
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -129,14 +129,7 @@ func installationPreflightCommand(ctx context.Context, installationPath string,
|
||||
}
|
||||
// Docker connection/trust and executable discovery remain host-owned. Compose parameters
|
||||
// are exclusively read from the authored env file, not inherited shell overrides.
|
||||
dockerEnvironment := []string{}
|
||||
for _, entry := range os.Environ() {
|
||||
key, _, _ := strings.Cut(entry, "=")
|
||||
if slices.Contains([]string{"PATH", "HOME", "USERPROFILE", "SystemRoot", "SYSTEMROOT", "TEMP", "TMP", "TMPDIR", "DOCKER_HOST", "DOCKER_CONTEXT", "DOCKER_CONFIG", "DOCKER_TLS_VERIFY", "DOCKER_CERT_PATH", "HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "no_proxy"}, key) {
|
||||
dockerEnvironment = append(dockerEnvironment, entry)
|
||||
}
|
||||
}
|
||||
runner := compose.NewRunnerWithEnvironment("", dockerEnvironment)
|
||||
runner := compose.NewRunnerWithEnvironment("", installationDockerEnvironment())
|
||||
if report.OK {
|
||||
report.Merge(preflight.CheckHost(ctx, runner, host, minimum))
|
||||
}
|
||||
@@ -166,6 +159,7 @@ func installationPreflightCommand(ctx context.Context, installationPath string,
|
||||
} else {
|
||||
preflight.AddRuntimeObligations(&report)
|
||||
plan := preflight.Plan{SchemaVersion: 1, ValidatorProtocol: preflight.Protocol, Validator: version.Current(), Installation: installation, Release: manifest, Platform: platform, WorkspaceDirectory: options["--workspaces"], WorkspaceRevision: revision, Inputs: inputs, AbsentInputs: absent, Report: report}
|
||||
plan.ManifestPath, plan.BootstrapPath = options["--release"], options["--bootstrap"]
|
||||
if err := preflight.WritePlan(options["--output"], &plan, unchanged); err != nil {
|
||||
report.Add("plan-output", "error", "output", "Choose a new filename in a private canonical directory; existing plans and key files are never overwritten.")
|
||||
}
|
||||
@@ -181,6 +175,17 @@ func installationPreflightCommand(ctx context.Context, installationPath string,
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
func installationDockerEnvironment() []string {
|
||||
environment := []string{}
|
||||
for _, entry := range os.Environ() {
|
||||
key, _, _ := strings.Cut(entry, "=")
|
||||
if slices.Contains([]string{"PATH", "HOME", "USERPROFILE", "SystemRoot", "SYSTEMROOT", "TEMP", "TMP", "TMPDIR", "DOCKER_HOST", "DOCKER_CONTEXT", "DOCKER_CONFIG", "DOCKER_TLS_VERIFY", "DOCKER_CERT_PATH", "HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "no_proxy"}, key) {
|
||||
environment = append(environment, entry)
|
||||
}
|
||||
}
|
||||
return environment
|
||||
}
|
||||
func writePreflight(stdout io.Writer, report preflight.Report, structured bool) {
|
||||
if structured {
|
||||
_ = json.NewEncoder(stdout).Encode(report)
|
||||
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/preflight"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/version"
|
||||
)
|
||||
|
||||
func TestNativeInstallationPlanBeforeContainersExist(t *testing.T) {
|
||||
@@ -78,8 +79,14 @@ 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
|
||||
if code != 0 || json.Unmarshal([]byte(identityJSON), &identity) != nil {
|
||||
t.Fatal("compiled operator identity unavailable")
|
||||
}
|
||||
manifest.Version, manifest.Revision = identity.Version, identity.Commit
|
||||
platform := "linux/" + runtime.GOARCH
|
||||
services := map[string]map[string]string{}
|
||||
for _, role := range []string{"core", "frontend", "catalog", "qdrant", "embedding"} {
|
||||
@@ -89,7 +96,7 @@ func TestNativeInstallationPlanBeforeContainersExist(t *testing.T) {
|
||||
services[service] = map[string]string{"image": manifest.Images[role][platform]}
|
||||
}
|
||||
_ = os.Mkdir(filepath.Join(release, "deploy"), 0o700)
|
||||
for name, contents := range map[string]string{"compose.yaml": "services: {}\n", "deploy/compose.git-https.yaml": "services: {}\n"} {
|
||||
for name, contents := range map[string]string{"compose.yaml": "services: {}\n", "deploy/compose.local.yaml": "services: {}\n", "deploy/compose.git-https.yaml": "services: {}\n"} {
|
||||
write(filepath.Join(release, filepath.FromSlash(name)), []byte(contents))
|
||||
sum := sha256.Sum256([]byte(contents))
|
||||
manifest.Files[name] = hex.EncodeToString(sum[:])
|
||||
@@ -99,6 +106,13 @@ func TestNativeInstallationPlanBeforeContainersExist(t *testing.T) {
|
||||
write(manifestPath, manifestJSON)
|
||||
effective, _ := json.Marshal(map[string]any{"services": services})
|
||||
script := fmt.Sprintf("#!/bin/sh\ncase \"$1\" in\ninfo) printf '%%s\\n' '{\"OSType\":\"linux\",\"Architecture\":\"%s\",\"NCPU\":4,\"MemTotal\":17179869184}';;\ncompose) if [ \"$2\" = version ]; then printf '2.39.0\\n'; else printf '%%s\\n' '%s'; fi;;\nmanifest) printf '%%s\\n' '{\"Descriptor\":{\"digest\":\"sha256:%s\",\"platform\":{\"os\":\"linux\",\"architecture\":\"%s\"}}}';;\n*) exit 1;;\nesac\n", runtime.GOARCH, effective, strings.Repeat("a", 64), runtime.GOARCH)
|
||||
script = strings.Replace(script, "*) exit 1;;", `volume) if [ "$2" = inspect ]; then for last in "$@"; do :; done; printf '{"io.thothii.installation":"%s","io.thothii.volume":"%s"}\n' "${last%%_*}" "${last#*_}"; fi;;
|
||||
run) case "$*" in *'/etc/passwd') printf 'root:x:0:0:root:/root:/bin/bash\nthoth:x:10001:10001::/home/thoth:/bin/bash\npostgres:x:999:999::/var/lib/postgresql:/bin/bash\n';; esac;;
|
||||
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)
|
||||
script = strings.Replace(script, "elif case", `elif case "$*" in *"await importPreparedBindings(undefined, 'workspaces');"*) true;; *) false;; esac; then while IFS= read -r line; do :; done; printf '%s\n' '{"ok":true,"code":"workspaces_prepared","completed":1}'; elif case "$*" in *'/app/backend/dist/operator-command.js'*) true;; *) false;; esac; then printf '%s\n' '{"ready":true}'; elif case`, 1)
|
||||
write(filepath.Join(root, "docker"), []byte(script))
|
||||
_ = os.Chmod(filepath.Join(root, "docker"), 0o700)
|
||||
planPath := filepath.Join(installation, "plan.json")
|
||||
@@ -124,6 +138,16 @@ func TestNativeInstallationPlanBeforeContainersExist(t *testing.T) {
|
||||
if err := preflight.VerifyPlanInputs(planPath); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for attempt := 0; attempt < 2; attempt++ {
|
||||
code, text := command("--installation", descriptor, "installation", "apply", "--plan", planPath)
|
||||
var result struct {
|
||||
PlatformReady bool `json:"platform_ready"`
|
||||
WorkspaceReady bool `json:"workspace_ready"`
|
||||
}
|
||||
if code != 0 || json.Unmarshal([]byte(text), &result) != nil || !result.PlatformReady || !result.WorkspaceReady || strings.Contains(text, "PRIVATE_") {
|
||||
t.Fatalf("noninteractive apply attempt %d: %s", attempt, text)
|
||||
}
|
||||
}
|
||||
write(filepath.Join(installation, "secrets/database-password"), []byte("rotated-invalid"))
|
||||
if preflight.VerifyPlanInputs(planPath) == nil {
|
||||
t.Fatal("rotation did not invalidate plan")
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
@@ -53,6 +54,8 @@ Commands:
|
||||
Check host prerequisites and optionally the published release, without a stack.
|
||||
installation plan --workspaces PATH --release MANIFEST --output NEW_PLAN [--bootstrap PATH] [--json]
|
||||
Validate documents and live dependencies, then seal a private plan; requires --installation.
|
||||
installation apply --plan ABS_PLAN [--json]
|
||||
Recheck and apply the released plan without prompts; workspace readiness remains separate.
|
||||
installation migrate --output PATH --session-default PROVIDER/MODEL
|
||||
--embedding-id PROVIDER/MODEL --embedding-dimensions N
|
||||
Create a review-only schema-v2 candidate from all three legacy model sources.
|
||||
@@ -148,6 +151,11 @@ func run(ctx context.Context, args []string, stdout, stderr io.Writer) int {
|
||||
return versionCommand(commandArgs, stdout, stderr)
|
||||
}
|
||||
if command == "installation" {
|
||||
if len(commandArgs) > 0 && commandArgs[0] == "apply" {
|
||||
bound, stop := signal.NotifyContext(ctx, os.Interrupt)
|
||||
defer stop()
|
||||
return installationApplyCommand(bound, installationPath, commandArgs, stdout)
|
||||
}
|
||||
if len(commandArgs) > 0 && (commandArgs[0] == "preflight" || commandArgs[0] == "plan") {
|
||||
return installationPreflightCommand(ctx, installationPath, commandArgs, stdout)
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -713,7 +714,7 @@ func parseConfigure(args []string) (configureRequest, error) {
|
||||
*target, args = args[0], args[1:]
|
||||
seen[option] = true
|
||||
}
|
||||
if request.mode != "local" && request.mode != "oidc" || !validPublicURL(request.publicURL) {
|
||||
if request.mode != "local" && request.mode != "oidc" || !ValidPublicURL(request.publicURL) {
|
||||
return configureRequest{}, errCommandRefused
|
||||
}
|
||||
if request.mode == "local" {
|
||||
@@ -1173,9 +1174,19 @@ func rolesToStrings(roles []Role) []string {
|
||||
return values
|
||||
}
|
||||
|
||||
func validPublicURL(value string) bool {
|
||||
// ValidPublicURL follows the backend policy: HTTP requires canonical literal loopback.
|
||||
func ValidPublicURL(value string) bool {
|
||||
parsed, err := url.Parse(value)
|
||||
return err == nil && (parsed.Scheme == "http" || parsed.Scheme == "https") && parsed.Host != "" && parsed.User == nil && parsed.Path == "" && parsed.RawQuery == "" && parsed.Fragment == ""
|
||||
if err != nil || parsed.Hostname() == "" || strings.Contains(parsed.Hostname(), "%") || parsed.User != nil || (parsed.Path != "" && parsed.Path != "/") || parsed.RawQuery != "" || parsed.Fragment != "" {
|
||||
return false
|
||||
}
|
||||
if port := parsed.Port(); port != "" {
|
||||
n, err := strconv.Atoi(port)
|
||||
if err != nil || n < 0 || n > 65535 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return parsed.Scheme == "https" || parsed.Scheme == "http" && isLoopbackURL(value)
|
||||
}
|
||||
|
||||
func validOIDCURL(value string) bool {
|
||||
@@ -1191,10 +1202,28 @@ func isHTTPS(value string) bool {
|
||||
return err == nil && parsed.Scheme == "https"
|
||||
}
|
||||
func isLoopbackURL(value string) bool {
|
||||
if !strings.HasPrefix(value, "http://") {
|
||||
return false
|
||||
}
|
||||
parsed, err := url.Parse(value)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
host := parsed.Hostname()
|
||||
return host == "localhost" || net.ParseIP(host) != nil && net.ParseIP(host).IsLoopback()
|
||||
ip := net.ParseIP(host)
|
||||
if ip == nil || !ip.IsLoopback() || ip.String() != host {
|
||||
return false
|
||||
}
|
||||
authority := host
|
||||
if strings.Contains(host, ":") {
|
||||
authority = "[" + host + "]"
|
||||
}
|
||||
if port := parsed.Port(); port != "" {
|
||||
n, err := strconv.Atoi(port)
|
||||
if err != nil || n < 0 || n > 65535 || strconv.Itoa(n) != port {
|
||||
return false
|
||||
}
|
||||
authority += ":" + port
|
||||
}
|
||||
return parsed.Host == authority
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package authconfig
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestLocalHTTPOriginMatchesBackendLiteralLoopbackPolicy(t *testing.T) {
|
||||
for _, origin := range []string{"http://127.0.0.1:8080", "http://127.0.0.2", "http://[::1]:8080"} {
|
||||
if !isLoopbackURL(origin) {
|
||||
t.Errorf("canonical origin refused: %s", origin)
|
||||
}
|
||||
}
|
||||
for _, origin := range []string{"http://localhost:8080", "http://127.1:8080", "http://[::ffff:127.0.0.1]:8080", "http://127.0.0.1:08080", "http://127.0.0.1:", "http://127.0.0.1:99999"} {
|
||||
if isLoopbackURL(origin) {
|
||||
t.Errorf("backend-incompatible origin accepted: %s", origin)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublicOriginMatchesBackendURLContract(t *testing.T) {
|
||||
for _, origin := range []string{"http://127.0.0.1:8080/", "https://example.com/", "https://example.com:443", "http://[::1]:8080/"} {
|
||||
if !ValidPublicURL(origin) {
|
||||
t.Errorf("runtime-valid origin refused: %s", origin)
|
||||
}
|
||||
}
|
||||
for _, origin := range []string{"https://:443", "https://[fe80::1%25eth0]", "https://example.com:99999", "http://localhost:8080", "HTTP://127.0.0.1:8080", "https://example.com/path", "http://example.com", "https://user:password@example.com"} {
|
||||
if ValidPublicURL(origin) {
|
||||
t.Errorf("runtime-invalid origin accepted: %s", origin)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -440,6 +440,9 @@ func validateRepositoryRemote(remote, access string) error {
|
||||
if access == "ssh" && parsed.Scheme != "ssh" {
|
||||
return errors.New("workspaceRepository remote does not match SSH access")
|
||||
}
|
||||
if parsed.Port() != "" && !(parsed.Scheme == "https" && parsed.Port() == "443") {
|
||||
return errors.New("workspaceRepository remote uses a port unsupported by the runtime registry")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -452,6 +455,9 @@ func (i Installation) ComposeFiles() []string {
|
||||
}
|
||||
files = append(files, i.Overrides...)
|
||||
files = append(files, i.ModelProjectionComposePath())
|
||||
if info, err := os.Lstat(i.LocalIdentityOverridePath()); err == nil && info.Mode().IsRegular() {
|
||||
files = append(files, i.LocalIdentityOverridePath())
|
||||
}
|
||||
if i.HasRuntimeAuthProjection() {
|
||||
files = append(files, i.runtimeAuthProjectionComposePath())
|
||||
}
|
||||
@@ -501,6 +507,11 @@ func (i Installation) CurrentImageOverridePath() string {
|
||||
return filepath.Join(i.ControlDirectory(), "current-image.yaml")
|
||||
}
|
||||
|
||||
// LocalIdentityOverridePath is generated only by document-first standalone apply.
|
||||
func (i Installation) LocalIdentityOverridePath() string {
|
||||
return filepath.Join(i.ControlDirectory(), "compose.local-identity.yaml")
|
||||
}
|
||||
|
||||
func (i Installation) UpdateStatePath() string {
|
||||
return filepath.Join(i.ControlDirectory(), "update-state.json")
|
||||
}
|
||||
|
||||
@@ -490,3 +490,11 @@ func containsSequence(values, wanted []string) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
func TestPreparedGitRemoteRejectsPortsUnsupportedByRuntimeRegistry(t *testing.T) {
|
||||
if validateRepositoryRemote("https://git.example.test:8443/workspaces.git", "https") == nil {
|
||||
t.Fatal("runtime-rejected Git port accepted during document preparation")
|
||||
}
|
||||
if err := validateRepositoryRemote("https://git.example.test:443/workspaces.git", "https"); err != nil {
|
||||
t.Fatal("standard HTTPS port must match URL normalization")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
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"
|
||||
var readinessClient = bindingClientModule + "\nawait importPreparedBindings(undefined, 'workspaces');\n"
|
||||
|
||||
type BindingReport struct {
|
||||
OK bool `json:"ok"`
|
||||
Code string `json:"code"`
|
||||
Completed int `json:"completed"`
|
||||
WorkspaceID string `json:"workspaceId,omitempty"`
|
||||
RunID string `json:"runId,omitempty"`
|
||||
}
|
||||
|
||||
// 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) {
|
||||
return runPreparedClient(ctx, plan, runner, payload, false)
|
||||
}
|
||||
|
||||
func runPreparedClient(ctx context.Context, plan preflight.Plan, runner compose.Runner, payload []byte, prepare bool) (BindingReport, error) {
|
||||
client, success, timeout := bindingClient, "bindings_ready", 15*time.Minute
|
||||
codes := []string{"bindings_ready", "authentication_required", "workspace_reconciliation_required", "binding_reconciliation_required", "container_connection_failed", "binding_import_failed", "binding_operation_pending", "schema_review_required"}
|
||||
if prepare {
|
||||
client, success, timeout = readinessClient, "workspaces_prepared", 60*time.Minute
|
||||
codes = append(codes, "workspaces_prepared", "workspace_preparation_failed", "session_transport_unsupported", "schema_review_required", "schema_sync_failed", "schema_sync_pending", "preprocessing_failed", "preprocessing_blocked", "preprocessing_pending")
|
||||
}
|
||||
bound, cancel := context.WithTimeout(ctx, timeout)
|
||||
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", client), bytes.NewReader(payload))
|
||||
var report BindingReport
|
||||
if json.Unmarshal([]byte(result.Stdout), &report) != nil || !slices.Contains(codes, 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 != success || report.Completed < 1 {
|
||||
return report, errors.New("Binding import stopped; reconcile the prepared documents with application administration and repeat planning")
|
||||
}
|
||||
return report, nil
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package installapply
|
||||
|
||||
import (
|
||||
"context"
|
||||
_ "embed"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/compose"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/config"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/preflight"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/safeio"
|
||||
)
|
||||
|
||||
// The original protected host files remain authoritative, including atomic auth updates.
|
||||
// Standalone services therefore run as the preparing operator, never as root. This does
|
||||
// not change the default image user or the server authentication projection protocol.
|
||||
func prepareIdentity(i config.Installation) error {
|
||||
uid, gid := os.Geteuid(), os.Getegid()
|
||||
if uid <= 0 || gid < 0 {
|
||||
return errors.New("standalone installation requires a non-root Unix operator")
|
||||
}
|
||||
services := map[string]any{}
|
||||
for _, service := range []string{"core", "catalog-migrate", "workspace-maintenance", "catalog-db"} {
|
||||
account := "core"
|
||||
if service == "catalog-db" {
|
||||
account = "catalog"
|
||||
}
|
||||
services[service] = map[string]any{
|
||||
"user": fmt.Sprintf("%d:%d", uid, gid),
|
||||
"volumes": []any{map[string]any{"type": "bind", "source": filepath.Join(i.ControlDirectory(), account+".passwd"), "target": "/etc/passwd", "read_only": true, "bind": map[string]any{"create_host_path": false}}},
|
||||
}
|
||||
}
|
||||
core := services["core"].(map[string]any)
|
||||
// Migrations do not launch Pi and must not mutate its image-owned home.
|
||||
services["catalog-migrate"].(map[string]any)["entrypoint"] = []string{"/usr/bin/tini", "--"}
|
||||
core["volumes"] = append(core["volumes"].([]any), map[string]any{"type": "volume", "source": "harness-pi", "target": "/app/harness/.pi"})
|
||||
services["catalog-db"].(map[string]any)["environment"] = map[string]string{"PGDATA": "/var/lib/postgresql/data/data"}
|
||||
volumes := map[string]any{}
|
||||
for _, v := range ownedVolumes {
|
||||
volumes[v.name] = map[string]any{"name": i.ProjectName() + "_" + v.name, "external": true}
|
||||
}
|
||||
b, err := json.MarshalIndent(map[string]any{"services": services, "volumes": volumes}, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return publishIdentical(i.LocalIdentityOverridePath(), b, 0o600)
|
||||
}
|
||||
|
||||
func publishIdentical(path string, b []byte, mode os.FileMode) error {
|
||||
if old, err := safeio.ReadCanonicalRegular(path, 4<<20); err == nil {
|
||||
if string(old) == string(b) {
|
||||
return nil
|
||||
}
|
||||
return errors.New("existing runtime identity differs; use the original operator and release")
|
||||
}
|
||||
return safeio.PublishCanonicalNewFile(path, b, mode)
|
||||
}
|
||||
|
||||
var ownedVolumes = []struct{ name, seed string }{
|
||||
{"settings", "/data/settings"}, {"pi-state", "/home/thoth/.pi"},
|
||||
{"harness-pi", "/app/harness/.pi"}, {"workspace-registry", "/data/workspace-registry"},
|
||||
{"workspace-secrets", "/data/workspace-secrets"}, {"sessions", "/data/sessions"},
|
||||
{"auth-state", "/data/auth"}, {"catalog-data", ""},
|
||||
}
|
||||
|
||||
//go:embed initialize-volumes.py
|
||||
var initializeVolumes string
|
||||
|
||||
func initializeIdentity(ctx context.Context, runner compose.Runner, i config.Installation, m preflight.Manifest, platform string) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 5*time.Minute)
|
||||
defer cancel()
|
||||
run := func(args ...string) (string, error) {
|
||||
result, err := runner.Run(ctx, args, nil)
|
||||
if err != nil || result.ExitCode != 0 {
|
||||
return "", errors.New("runtime identity initialization failed")
|
||||
}
|
||||
return result.Stdout, nil
|
||||
}
|
||||
oneShot := func(image, entrypoint string, tail ...string) ([]string, error) {
|
||||
name, err := compose.NewOneShotContainerName(i.ProjectName() + "-identity")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
args := []string{"run", "--rm", "--name", name, "--pull", "never", "--platform", platform, "--network", "none", "--read-only", "--user", "0:0", "--security-opt", "no-new-privileges", "--entrypoint", entrypoint}
|
||||
return append(append(args, image), tail...), nil
|
||||
}
|
||||
for _, account := range []struct{ role, user string }{{"core", "thoth"}, {"catalog", "postgres"}} {
|
||||
args, err := oneShot(m.Images[account.role][platform], "/bin/cat", "/etc/passwd")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
original, err := run(args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mapped, err := mapPasswd(original, account.user, os.Geteuid(), os.Getegid())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := publishIdentical(filepath.Join(i.ControlDirectory(), account.role+".passwd"), []byte(mapped), 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
args, err := oneShot(m.Images["core"][platform], "/opt/venv/bin/python", "-c", initializeVolumes, i.ProjectName(), strconv.Itoa(os.Geteuid()), strconv.Itoa(os.Getegid()))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Insert mounts before the image. The helper has only installation volumes, no host
|
||||
// secret binds, Docker socket, or network. Volume labels are checked before mounting.
|
||||
imageIndex := slices.Index(args, m.Images["core"][platform])
|
||||
mounts := []string{}
|
||||
seeds := map[string]string{}
|
||||
for _, volume := range ownedVolumes {
|
||||
name := i.ProjectName() + "_" + volume.name
|
||||
// Listing first distinguishes absence from an inspect/daemon failure.
|
||||
listed, err := run("volume", "ls", "--format", "{{.Name}}", "--filter", "name=^"+name+"$")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if strings.TrimSpace(listed) == "" {
|
||||
if _, err := run("volume", "create", "--label", "io.thothii.installation="+i.ProjectName(), "--label", "io.thothii.volume="+volume.name, name); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if strings.TrimSpace(listed) != name {
|
||||
return errors.New("unexpected volume identity")
|
||||
}
|
||||
inspected, err := run("volume", "inspect", "--format", "{{json .Labels}}", name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var labels map[string]string
|
||||
if json.Unmarshal([]byte(inspected), &labels) != nil || labels["io.thothii.installation"] != i.ProjectName() || labels["io.thothii.volume"] != volume.name {
|
||||
return errors.New("existing volume is not owned by this installation")
|
||||
}
|
||||
mounts = append(mounts, "--mount", "type=volume,src="+name+",dst=/bootstrap/"+volume.name+",volume-nocopy")
|
||||
seeds[volume.name] = volume.seed
|
||||
}
|
||||
payload, _ := json.Marshal(seeds)
|
||||
args = append(append(append([]string{}, args[:imageIndex]...), mounts...), args[imageIndex:]...)
|
||||
args = append(args, string(payload))
|
||||
_, err = run(args...)
|
||||
return err
|
||||
}
|
||||
|
||||
func mapPasswd(original, account string, uid, gid int) (string, error) {
|
||||
if uid <= 0 || gid < 0 {
|
||||
return "", errors.New("invalid runtime identity")
|
||||
}
|
||||
lines := strings.Split(strings.TrimSuffix(original, "\n"), "\n")
|
||||
found := false
|
||||
for n, line := range lines {
|
||||
fields := strings.Split(line, ":")
|
||||
if len(fields) != 7 {
|
||||
return "", errors.New("invalid image account database")
|
||||
}
|
||||
if fields[0] == account {
|
||||
if found {
|
||||
return "", errors.New("duplicate runtime account")
|
||||
}
|
||||
found = true
|
||||
fields[2], fields[3] = strconv.Itoa(uid), strconv.Itoa(gid)
|
||||
lines[n] = strings.Join(fields, ":")
|
||||
} else if fields[2] == strconv.Itoa(uid) {
|
||||
return "", errors.New("operator UID collides with an image account")
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return "", errors.New("image runtime account is missing")
|
||||
}
|
||||
return strings.Join(lines, "\n") + "\n", nil
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package installapply
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/compose"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/safeio"
|
||||
)
|
||||
|
||||
// Uses already-published images and Linux volume ownership even on Docker Desktop.
|
||||
// This proves runtime identity/PG init and retry; it is not OS installation acceptance.
|
||||
func TestPublishedImagesAcceptProtectedOperatorIdentity(t *testing.T) {
|
||||
if os.Getenv("THT_INSTALLATION_DOCKER_TEST") != "1" {
|
||||
t.Skip("set THT_INSTALLATION_DOCKER_TEST=1 with Docker and published images pulled")
|
||||
}
|
||||
_, plan := fixture(t)
|
||||
i := plan.Installation
|
||||
if err := safeio.EnsurePrivateDirectory(i.ProjectDirectory + "/.tht"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := safeio.EnsurePrivateDirectory(i.ControlDirectory()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := prepareIdentity(i); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
core := "docker.io/tylconsulting/thothii-core@sha256:7ac0b3362c93837c02d9f8d3153d3ab3441cc43594ee7786dafc845a69d5c956"
|
||||
catalog := "docker.io/library/postgres@sha256:45cd22f8d32e189d245403954882f88e7a8714301fda80dab6da90f1265b25a3"
|
||||
plan.Release.Images["core"][plan.Platform] = core
|
||||
plan.Release.Images["catalog"][plan.Platform] = catalog
|
||||
runner := compose.NewRunner("")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Minute)
|
||||
defer cancel()
|
||||
container := i.ProjectName() + "-pg-proof"
|
||||
t.Cleanup(func() {
|
||||
cleanup, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
defer cancel()
|
||||
_, _ = runner.Run(cleanup, []string{"rm", "-f", container}, nil)
|
||||
for _, volume := range ownedVolumes {
|
||||
_, _ = runner.Run(cleanup, []string{"volume", "rm", i.ProjectName() + "_" + volume.name}, nil)
|
||||
}
|
||||
})
|
||||
run := func(args ...string) string {
|
||||
t.Helper()
|
||||
result, err := runner.Run(ctx, args, nil)
|
||||
if err != nil || result.ExitCode != 0 {
|
||||
t.Fatalf("Docker proof failed: %v %s", err, result.Stderr)
|
||||
}
|
||||
return result.Stdout
|
||||
}
|
||||
if err := initializeIdentity(ctx, interruptedInitializer{runner}, i, plan.Release, plan.Platform); err == nil {
|
||||
t.Fatal("simulated interruption was ignored")
|
||||
}
|
||||
if err := initializeIdentity(ctx, runner, i, plan.Release, plan.Platform); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
user := fmt.Sprintf("%d:%d", os.Geteuid(), os.Getegid())
|
||||
// The password is created inside a Linux volume, so Desktop cannot mask UID/mode bugs.
|
||||
run("run", "--rm", "--pull", "never", "--platform", plan.Platform, "--network", "none", "--read-only", "--user", user,
|
||||
"--mount", "type=volume,src="+i.ProjectName()+"_auth-state,dst=/proof",
|
||||
"--mount", "type=volume,src="+i.ProjectName()+"_pi-state,dst=/home/thoth/.pi",
|
||||
"--mount", "type=volume,src="+i.ProjectName()+"_harness-pi,dst=/app/harness/.pi",
|
||||
"--mount", "type=bind,src="+i.ControlDirectory()+"/core.passwd,dst=/etc/passwd,readonly",
|
||||
"--entrypoint", "/usr/local/bin/node", core, "-e", `const fs=require('fs'),os=require('os'); if(os.userInfo().username!=='thoth')throw Error('identity'); fs.writeFileSync('/proof/password','test-only-password',{mode:0o600}); fs.writeFileSync('/home/thoth/.pi/agent/permission-proof','ok'); fs.writeFileSync('/app/harness/.pi/permission-proof','ok'); if(fs.statSync('/proof/password').uid!==Number(process.argv[1]))throw Error('owner');`, strconv.Itoa(os.Geteuid()))
|
||||
start := func() {
|
||||
run("run", "-d", "--name", container, "--pull", "never", "--platform", plan.Platform, "--network", "none", "--user", user,
|
||||
"--mount", "type=volume,src="+i.ProjectName()+"_catalog-data,dst=/var/lib/postgresql/data",
|
||||
"--mount", "type=volume,src="+i.ProjectName()+"_auth-state,dst=/proof,readonly",
|
||||
"--mount", "type=bind,src="+i.ControlDirectory()+"/catalog.passwd,dst=/etc/passwd,readonly",
|
||||
"-e", "PGDATA=/var/lib/postgresql/data/data", "-e", "POSTGRES_PASSWORD_FILE=/proof/password", catalog)
|
||||
deadline := time.Now().Add(45 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
value, err := runner.Run(ctx, []string{"exec", container, "pg_isready", "-h", "127.0.0.1", "-U", "postgres"}, nil)
|
||||
if err == nil && value.ExitCode == 0 {
|
||||
return
|
||||
}
|
||||
time.Sleep(250 * time.Millisecond)
|
||||
}
|
||||
t.Fatal("PostgreSQL did not become ready")
|
||||
}
|
||||
start()
|
||||
// Execute the real Catalog and Memory migration scripts using the generated
|
||||
// maintenance entrypoint, without inheriting Pi's image-owned home initialization.
|
||||
run("exec", container, "psql", "-U", "postgres", "-v", "ON_ERROR_STOP=1", "-c", "CREATE ROLE thothii_catalog_runtime LOGIN;")
|
||||
projection, err := os.ReadFile(i.LocalIdentityOverridePath())
|
||||
var overlay struct {
|
||||
Services map[string]struct {
|
||||
Entrypoint []string `json:"entrypoint"`
|
||||
} `json:"services"`
|
||||
}
|
||||
if err != nil || json.Unmarshal(projection, &overlay) != nil {
|
||||
t.Fatal("runtime override unavailable")
|
||||
}
|
||||
entry := overlay.Services["catalog-migrate"].Entrypoint
|
||||
if len(entry) == 0 {
|
||||
t.Fatal("migration entrypoint missing")
|
||||
}
|
||||
migrationArgs := []string{"run", "--rm", "--pull", "never", "--platform", plan.Platform, "--network", "container:" + container, "--user", user,
|
||||
"--mount", "type=volume,src=" + i.ProjectName() + "_auth-state,dst=/proof,readonly",
|
||||
"--mount", "type=bind,src=" + i.ControlDirectory() + "/core.passwd,dst=/etc/passwd,readonly",
|
||||
"-e", "THT_CATALOG_DB_HOST=127.0.0.1", "-e", "THT_CATALOG_DB_NAME=postgres",
|
||||
"-e", "THT_CATALOG_MIGRATOR_USER=postgres", "-e", "THT_CATALOG_MIGRATOR_PASSWORD_FILE=/proof/password",
|
||||
"--entrypoint", entry[0], core}
|
||||
migrationArgs = append(migrationArgs, entry[1:]...)
|
||||
migrationArgs = append(migrationArgs, "bash", "/app/docker/catalog-migrate.sh")
|
||||
run(migrationArgs...)
|
||||
run("exec", container, "psql", "-U", "postgres", "-v", "ON_ERROR_STOP=1", "-c", "CREATE TABLE installation_proof(value integer); INSERT INTO installation_proof VALUES (47);")
|
||||
run("stop", "--time", "10", container)
|
||||
run("rm", container)
|
||||
if err := initializeIdentity(ctx, runner, i, plan.Release, plan.Platform); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
start()
|
||||
if result := run("exec", container, "psql", "-U", "postgres", "-Atqc", "SELECT value FROM installation_proof"); strings.TrimSpace(result) != "47" {
|
||||
t.Fatal("retry lost existing catalog data")
|
||||
}
|
||||
}
|
||||
|
||||
type interruptedInitializer struct{ compose.Runner }
|
||||
|
||||
func (r interruptedInitializer) Run(ctx context.Context, args []string, input io.Reader) (compose.Result, error) {
|
||||
args = append([]string{}, args...)
|
||||
for n, value := range args {
|
||||
if value == initializeVolumes {
|
||||
args[n] = strings.ReplaceAll(value, `save(marker, dict(identity, status="ready"))`, `os._exit(47)`)
|
||||
}
|
||||
}
|
||||
return r.Runner.Run(ctx, args, input)
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package installapply
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/compose"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/preflight"
|
||||
)
|
||||
|
||||
func TestIdentityPreservesAccountsAndRefusesCollisions(t *testing.T) {
|
||||
original := "root:x:0:0:root:/root:/bin/bash\nthoth:x:10001:10001::/home/thoth:/bin/bash\n"
|
||||
got, err := mapPasswd(original, "thoth", 1000, 1000)
|
||||
if err != nil || got != strings.Replace(original, "10001:10001", "1000:1000", 1) {
|
||||
t.Fatalf("mapped account: %q %v", got, err)
|
||||
}
|
||||
for _, broken := range []string{original + "other:x:1000:1000::/:/bin/false\n", strings.ReplaceAll(original, "thoth:", "missing:"), original + "thoth:x:10002:10002::/:/bin/false\n"} {
|
||||
if _, err := mapPasswd(broken, "thoth", 1000, 1000); err == nil {
|
||||
t.Fatal("ambiguous identity accepted")
|
||||
}
|
||||
}
|
||||
if _, err := mapPasswd(original, "thoth", 0, 0); err == nil {
|
||||
t.Fatal("root runtime accepted")
|
||||
}
|
||||
}
|
||||
|
||||
type foreignVolume struct{ dockerFixture }
|
||||
|
||||
func (r *foreignVolume) Run(ctx context.Context, args []string, input io.Reader) (compose.Result, error) {
|
||||
if len(args) > 1 && args[0] == "volume" && args[1] == "inspect" {
|
||||
return compose.Result{Stdout: `{"io.thothii.installation":"someone-else"}`}, nil
|
||||
}
|
||||
return r.dockerFixture.Run(ctx, args, input)
|
||||
}
|
||||
|
||||
func TestForeignVolumesStopBeforeOwnershipOrServiceChanges(t *testing.T) {
|
||||
path, plan := fixture(t)
|
||||
r := &foreignVolume{}
|
||||
result, err := Run(context.Background(), Request{path, plan.Installation.Path}, r, func(context.Context, preflight.Plan) error { return nil })
|
||||
if err == nil || result.Stage != "runtime-identity" {
|
||||
t.Fatalf("foreign volume: %+v %v", result, err)
|
||||
}
|
||||
for _, line := range flatten(r.calls) {
|
||||
if strings.Contains(line, " up ") || strings.Contains(line, " -c "+initializeVolumes) {
|
||||
t.Fatal("changed foreign volume or started service")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeIdentityIsDurableAcrossOperatorCommands(t *testing.T) {
|
||||
path, plan := fixture(t)
|
||||
_, err := Run(context.Background(), Request{path, plan.Installation.Path}, &dockerFixture{}, func(context.Context, preflight.Plan) error { return nil })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err := os.ReadFile(plan.Installation.LocalIdentityOverridePath())
|
||||
var override struct {
|
||||
Services map[string]struct {
|
||||
User string `json:"user"`
|
||||
} `json:"services"`
|
||||
}
|
||||
if err != nil || json.Unmarshal(b, &override) != nil || override.Services["core"].User == "0:0" || override.Services["core"].User == "" {
|
||||
t.Fatal("non-root runtime identity missing")
|
||||
}
|
||||
if !strings.Contains(strings.Join(plan.Installation.ComposeArgs("start"), " "), plan.Installation.LocalIdentityOverridePath()) {
|
||||
t.Fatal("lifecycle loses runtime identity")
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(plan.Installation.ControlDirectory(), "core.passwd"), []byte("modified"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = Run(context.Background(), Request{path, plan.Installation.Path}, &dockerFixture{}, func(context.Context, preflight.Plan) error { return nil })
|
||||
if err == nil {
|
||||
t.Fatal("modified identity accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
// Fixed client executed inside the released core; protected input arrives only through stdin.
|
||||
const stopped = (code, runId) => Object.assign(new Error(code), { code, ...(runId ? { runId } : {}) });
|
||||
const jsonResponse = async (response, code) => {
|
||||
if (!response.ok) throw stopped(code);
|
||||
return response.json();
|
||||
};
|
||||
|
||||
export async function importBinding(request, entry, revision, pause = () => new Promise(resolve => setTimeout(resolve, 2000))) {
|
||||
for (let attempt = 0; attempt < 300; attempt++) {
|
||||
const response = await request("/installation/bindings", { ...entry, revision });
|
||||
if (response.status === 409) {
|
||||
const value = await response.json();
|
||||
if (value.code !== "installation_operation_pending") throw stopped("binding_reconciliation_required");
|
||||
const databases = await jsonResponse(await request("/catalog/databases"), "binding_import_failed");
|
||||
const active = databases.find(item => item.workspaceId === entry.configuration.workspaceId)?.activeSyncRun;
|
||||
if (active?.state === "awaiting_confirmation") throw stopped("schema_review_required", active.id);
|
||||
await pause(); continue;
|
||||
}
|
||||
if (response.status === 422) throw stopped("container_connection_failed");
|
||||
const value = await jsonResponse(response, "binding_import_failed");
|
||||
if (value.connectionStatus !== "reachable" || !["applied", "unchanged"].includes(value.status)) throw stopped("binding_import_failed");
|
||||
return;
|
||||
}
|
||||
throw stopped("binding_operation_pending");
|
||||
}
|
||||
|
||||
export async function prepareWorkspace(request, workspaceId, revision, pause = () => new Promise(resolve => setTimeout(resolve, 2000))) {
|
||||
const databases = await jsonResponse(await request("/catalog/databases"), "workspace_preparation_failed");
|
||||
const database = databases.find(item => item.workspaceId === workspaceId);
|
||||
if (!database || database.workspaceRevision?.commit !== revision) throw stopped("workspace_reconciliation_required");
|
||||
if (database.binding.transport === "ssh_tunnel") throw stopped("session_transport_unsupported");
|
||||
const runs = await jsonResponse(await request(`/catalog/databases/${database.id}/sync-runs`), "schema_sync_failed");
|
||||
let active = runs.find(run => ["queued", "running", "awaiting_confirmation", "applying"].includes(run.state));
|
||||
const interrupted = runs.find(run => ["interrupted", "failed"].includes(run.state) && run.requestedDatabaseVersion === database.version &&
|
||||
run.scope === "all" && (database.schemaSyncedVersion !== database.version || run.phase === "memory_cleanup"));
|
||||
if (!active && interrupted) {
|
||||
active = await jsonResponse(await request(`/catalog/sync-runs/${interrupted.id}/retry`, {}), "schema_sync_failed");
|
||||
}
|
||||
const waitForSync = async run => {
|
||||
for (let attempt = 0; attempt < 900; attempt++) {
|
||||
if (run.state === "awaiting_confirmation") throw stopped("schema_review_required", run.id);
|
||||
if (run.state === "succeeded") return;
|
||||
if (!["queued", "running", "applying"].includes(run.state)) throw stopped("schema_sync_failed", run.id);
|
||||
await pause();
|
||||
run = await jsonResponse(await request(`/catalog/sync-runs/${run.id}`), "schema_sync_failed");
|
||||
}
|
||||
throw stopped("schema_sync_pending", run.id);
|
||||
};
|
||||
if (active) await waitForSync(active);
|
||||
let current = active
|
||||
? await jsonResponse(await request(`/catalog/databases/${database.id}`), "schema_sync_failed") : database;
|
||||
if (current.version !== database.version) throw stopped("workspace_reconciliation_required");
|
||||
if (current.schemaSyncedVersion !== current.version) {
|
||||
active = await jsonResponse(await request(`/catalog/databases/${database.id}/sync-runs`, {
|
||||
version: database.version, scope: "all", tableIds: [],
|
||||
}), "schema_sync_failed");
|
||||
await waitForSync(active);
|
||||
current = await jsonResponse(await request(`/catalog/databases/${database.id}`), "schema_sync_failed");
|
||||
if (current.version !== database.version || current.schemaSyncedVersion !== current.version) throw stopped("workspace_reconciliation_required");
|
||||
}
|
||||
const path = `/workspaces/${encodeURIComponent(workspaceId)}/preprocessing`;
|
||||
let state = await jsonResponse(await request(path), "preprocessing_failed");
|
||||
let started = false;
|
||||
for (let attempt = 0; attempt < 900; attempt++) {
|
||||
if (state.state === "ready") return { workspaceId, state: "ready" };
|
||||
if (state.state === "blocked") throw stopped("preprocessing_blocked");
|
||||
if (state.state === "running" && attempt % 15 === 0) {
|
||||
const response = await request(path, { recoverInterrupted: true });
|
||||
if (response.status !== 409) await jsonResponse(response, "preprocessing_failed");
|
||||
started = true;
|
||||
} else
|
||||
if (["required", "failed"].includes(state.state) && !started) {
|
||||
started = true;
|
||||
await jsonResponse(await request(path, {}), "preprocessing_failed");
|
||||
} else if (state.state !== "running") throw stopped("preprocessing_failed");
|
||||
await pause();
|
||||
state = await jsonResponse(await request(path), "preprocessing_failed");
|
||||
}
|
||||
throw stopped("preprocessing_pending");
|
||||
}
|
||||
|
||||
const readinessCodes = new Set(["workspace_preparation_failed", "workspace_reconciliation_required", "session_transport_unsupported",
|
||||
"schema_review_required", "schema_sync_failed", "schema_sync_pending", "preprocessing_failed", "preprocessing_blocked", "preprocessing_pending",
|
||||
"binding_reconciliation_required", "container_connection_failed", "binding_import_failed", "binding_operation_pending"]);
|
||||
|
||||
export async function importPreparedBindings(base = "http://core:8787", mode = "bindings") {
|
||||
let cookie = "", csrf = "", origin = "", completed = 0, code = "authentication_required";
|
||||
let workspaceId, runId;
|
||||
const request = async (path, body) => fetch(base + path, {
|
||||
method: body === undefined ? "GET" : "POST", redirect: "error", signal: AbortSignal.timeout(mode === "workspaces" ? 1800000 : 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) {
|
||||
workspaceId = entry.configuration.workspaceId;
|
||||
if (mode === "workspaces") {
|
||||
workspaceId = entry.configuration.workspaceId;
|
||||
code = "workspace_preparation_failed";
|
||||
await prepareWorkspace(request, workspaceId, revision);
|
||||
completed++;
|
||||
continue;
|
||||
}
|
||||
code = "binding_import_failed";
|
||||
await importBinding(request, entry, revision);
|
||||
completed++;
|
||||
}
|
||||
workspaceId = undefined;
|
||||
code = mode === "workspaces" ? "workspaces_prepared" : "bindings_ready";
|
||||
} catch (error) {
|
||||
if (readinessCodes.has(error?.code)) {
|
||||
code = error.code;
|
||||
if (/^[a-f0-9-]{36}$/.test(error.runId ?? "")) runId = error.runId;
|
||||
}
|
||||
process.exitCode = 1;
|
||||
}
|
||||
finally {
|
||||
if (cookie && csrf) { try { await request("/auth/logout", {}); } catch {} }
|
||||
process.stdout.write(JSON.stringify({ ok: ["bindings_ready", "workspaces_prepared"].includes(code), code, completed, workspaceId, runId }));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
"""Seed only empty installation-owned volumes; resumed live data is never chowned."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sys
|
||||
|
||||
project, uid, gid, seeds = sys.argv[1:]
|
||||
uid, gid = int(uid), int(gid)
|
||||
assert uid > 0 and gid >= 0
|
||||
|
||||
def save(path, value):
|
||||
temporary = path.with_name(".thothii-initializing.tmp")
|
||||
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
|
||||
with os.fdopen(fd, "w") as stream:
|
||||
json.dump(value, stream)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, path)
|
||||
directory = os.open(path.parent, os.O_DIRECTORY)
|
||||
try:
|
||||
os.fsync(directory)
|
||||
finally:
|
||||
os.close(directory)
|
||||
|
||||
for name, source in json.loads(seeds).items():
|
||||
root = Path("/bootstrap") / name
|
||||
marker = root / ".thothii-volume.json"
|
||||
identity = {"project": project, "volume": name, "uid": uid, "gid": gid}
|
||||
if marker.exists():
|
||||
assert not marker.is_symlink()
|
||||
assert marker.stat().st_uid == 0 and marker.stat().st_nlink == 1
|
||||
state = json.loads(marker.read_text())
|
||||
assert all(state.get(k) == v for k, v in identity.items())
|
||||
assert state.get("status") in ("initializing", "ready")
|
||||
if state["status"] == "ready":
|
||||
current = root.stat()
|
||||
assert (current.st_uid, current.st_gid) == (uid, gid)
|
||||
continue
|
||||
else:
|
||||
# A leftover unpublished marker can result from interruption before rename.
|
||||
assert all(p.name == ".thothii-initializing.tmp" and p.is_file() and not p.is_symlink() for p in root.iterdir())
|
||||
save(marker, dict(identity, status="initializing"))
|
||||
# No application can have used an initializing volume: all volumes become ready
|
||||
# before catalog/services are started. Re-copying distributed files is repeatable.
|
||||
if source:
|
||||
shutil.copytree(source, root, dirs_exist_ok=True, symlinks=True)
|
||||
for parent, directories, files in os.walk(root, followlinks=False):
|
||||
for entry in directories + files:
|
||||
if Path(parent) == root and entry in (marker.name, ".thothii-initializing.tmp"):
|
||||
continue
|
||||
os.chown(Path(parent) / entry, uid, gid, follow_symlinks=False)
|
||||
os.chown(root, uid, gid)
|
||||
os.chmod(root, 0o700)
|
||||
save(marker, dict(identity, status="ready"))
|
||||
@@ -0,0 +1,340 @@
|
||||
// Package installapply applies a sealed installation plan without interactive input.
|
||||
package installapply
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/compose"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/config"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/lifecycle"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/modelprojection"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/preflight"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/safeio"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/service"
|
||||
)
|
||||
|
||||
type Request struct{ PlanPath, InstallationPath string }
|
||||
type RuntimeCheck struct {
|
||||
ID string `json:"id"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
type Result struct {
|
||||
Distribution string `json:"distribution"`
|
||||
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"`
|
||||
WorkspacePreparation *BindingReport `json:"workspace_preparation,omitempty"`
|
||||
RuntimeChecks []RuntimeCheck `json:"runtime_checks"`
|
||||
FunctionalAcceptance bool `json:"functional_acceptance"`
|
||||
Stage string `json:"stage"`
|
||||
Action string `json:"action"`
|
||||
Journal string `json:"journal,omitempty"`
|
||||
}
|
||||
type journal struct {
|
||||
Distribution string `json:"distribution,omitempty"`
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
Installation string `json:"installation"`
|
||||
ReleaseRevision string `json:"release_revision"`
|
||||
PlanSeal string `json:"plan_seal"`
|
||||
Stage string `json:"stage"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
func (r Result) NeedsReview() bool {
|
||||
return (r.WorkspacePreparation != nil && r.WorkspacePreparation.Code == "schema_review_required") ||
|
||||
(r.BindingImport != nil && r.BindingImport.Code == "schema_review_required")
|
||||
}
|
||||
|
||||
// Check must repeat document validation and live prerequisite probes at the public CLI boundary.
|
||||
// It is mandatory; historical success in the plan never authorizes skipping current checks.
|
||||
type Check func(context.Context, preflight.Plan) error
|
||||
|
||||
func Run(ctx context.Context, request Request, runner compose.Runner, check Check) (result Result, err error) {
|
||||
result = Result{SchemaVersion: 1, Stage: "plan", Action: "Produce a current plan from complete prepared documents."}
|
||||
for _, id := range []string{"workspace-test", "workflow-doctor", "pi-test"} {
|
||||
result.RuntimeChecks = append(result.RuntimeChecks, RuntimeCheck{ID: id, Status: "pending"})
|
||||
}
|
||||
fail := func(stage, action string) (Result, error) {
|
||||
result.Stage = stage
|
||||
result.Action = action
|
||||
return result, errors.New(action)
|
||||
}
|
||||
plan, err := preflight.ReadExecutionPlan(request.PlanPath)
|
||||
if err != nil || plan.Installation.Path != request.InstallationPath || plan.ManifestPath == "" || plan.BootstrapPath == "" || runner == nil || check == nil {
|
||||
return fail("plan", "Use a matching protected execution plan; older plans must be regenerated.")
|
||||
}
|
||||
installation, err := config.LoadPrepared(request.InstallationPath)
|
||||
if err != nil || !reflect.DeepEqual(installation, plan.Installation) || installation.Profile != "local" {
|
||||
return fail("plan", "Correct and validate the local installation documents before execution.")
|
||||
}
|
||||
manifest, err := preflight.LoadManifest(plan.ManifestPath)
|
||||
if err != nil || !reflect.DeepEqual(manifest, plan.Release) {
|
||||
return fail("release", "Restore the exact verified release bundle and generate a new plan if its identity changed.")
|
||||
}
|
||||
result.Distribution = manifest.Mode()
|
||||
if err := safeio.EnsurePrivateDirectory(filepath.Join(installation.ProjectDirectory, ".tht")); err != nil {
|
||||
return fail("lock", "The installation control directory must be private and canonical.")
|
||||
}
|
||||
if err := safeio.EnsurePrivateDirectory(installation.ControlDirectory()); err != nil {
|
||||
return fail("lock", "The installation control directory must be private and canonical.")
|
||||
}
|
||||
lock, err := lifecycle.Acquire(installation)
|
||||
if err != nil {
|
||||
return fail("lock", "Another lifecycle operation owns the installation lock; wait for it to finish. Inspect a stale owner after a terminated process before explicitly removing its lock.")
|
||||
}
|
||||
defer func() {
|
||||
if releaseErr := lock.Release(); releaseErr != nil {
|
||||
result.PlatformReady = false
|
||||
result.Stage = "lock"
|
||||
result.Action = "Installation lock ownership changed; inspect the private control directory."
|
||||
err = errors.New(result.Action)
|
||||
}
|
||||
}()
|
||||
if err := check(ctx, plan); err != nil {
|
||||
return fail("validation", "Current document or prerequisite checks failed; correct the documents and repeat planning. No platform operation was started.")
|
||||
}
|
||||
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, Distribution: manifest.Mode()}
|
||||
if _, err := os.Lstat(result.Journal); err == nil {
|
||||
data, readErr := safeio.ReadCanonicalPrivateRegular(result.Journal, 16<<10)
|
||||
var previous journal
|
||||
if readErr != nil || json.Unmarshal(data, &previous) != nil || previous.SchemaVersion != 1 || previous.Installation != installation.Path || previous.ReleaseRevision != plan.Release.Revision {
|
||||
return fail("journal", "The existing installation journal is invalid or belongs to another release; this command is not a product upgrade.")
|
||||
}
|
||||
previousMode := previous.Distribution
|
||||
if previousMode == "" {
|
||||
previousMode = "prebuilt"
|
||||
}
|
||||
if previousMode != manifest.Mode() {
|
||||
return fail("journal", "Changing between source and prebuilt requires an explicit upgrade or a separate installation.")
|
||||
}
|
||||
} else if !os.IsNotExist(err) {
|
||||
return fail("journal", "Cannot safely read the installation journal.")
|
||||
}
|
||||
persist := func() error {
|
||||
data, _ := json.MarshalIndent(state, "", " ")
|
||||
data = append(data, '\n')
|
||||
if _, err := os.Lstat(result.Journal); os.IsNotExist(err) {
|
||||
return safeio.PublishCanonicalNewFile(result.Journal, data, 0o600)
|
||||
}
|
||||
return safeio.ReplaceCanonicalRegular(result.Journal, data, 0o600)
|
||||
}
|
||||
operation := func(stage string, fn func() error) error {
|
||||
result.Stage = stage
|
||||
state.Stage = stage
|
||||
state.Status = "running"
|
||||
if err := persist(); err != nil {
|
||||
return errors.New("Cannot persist the private installation journal.")
|
||||
}
|
||||
if _, err := preflight.ReadExecutionPlan(request.PlanPath); err != nil {
|
||||
state.Status = "failed"
|
||||
_ = persist()
|
||||
return errors.New("Prepared inputs changed; correct the documents and produce a new plan.")
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
state.Status = "interrupted"
|
||||
_ = persist()
|
||||
return errors.New("Execution interrupted; repeat the same command to reconcile the existing platform.")
|
||||
}
|
||||
if err := fn(); err != nil {
|
||||
state.Status = "failed"
|
||||
if ctx.Err() != nil {
|
||||
state.Status = "interrupted"
|
||||
}
|
||||
if saveErr := persist(); saveErr != nil {
|
||||
return errors.New("Operation stopped and the private journal could not be updated.")
|
||||
}
|
||||
return fmt.Errorf("Stage %s failed; correct its prerequisites and repeat apply. No source build or volume reset was attempted.", stage)
|
||||
}
|
||||
state.Status = "complete"
|
||||
return persist()
|
||||
}
|
||||
docker := func(timeout time.Duration, command ...string) error {
|
||||
bound, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
value, err := runner.Run(bound, installation.ComposeArgs(command...), nil)
|
||||
if err != nil || value.ExitCode != 0 {
|
||||
return errors.New("Docker operation failed")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
stages := []struct {
|
||||
name string
|
||||
run func() error
|
||||
}{
|
||||
{"assets", func() error { return installAssets(installation, plan) }},
|
||||
{"configuration", func() error {
|
||||
if err := prepareIdentity(installation); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := modelprojection.Generate(installation); err != nil {
|
||||
return err
|
||||
}
|
||||
if !preflight.CheckInstalledCompose(ctx, runner, installation, plan.Release, plan.Platform).OK {
|
||||
return errors.New("Effective runtime configuration differs from the release")
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"pull", func() error {
|
||||
if manifest.Mode() == "source" {
|
||||
return docker(30*time.Minute, "pull", "--policy", "always", "catalog-db", "qdrant", "embedding", "embedding-model-init")
|
||||
}
|
||||
return docker(30*time.Minute, "--profile", "catalog-maintenance", "--profile", "workspace-maintenance", "pull", "--policy", "always")
|
||||
}},
|
||||
{"runtime-identity", func() error {
|
||||
return initializeIdentity(ctx, runner, installation, plan.Release, plan.Platform)
|
||||
}},
|
||||
{"catalog", func() error {
|
||||
return docker(5*time.Minute, "up", "-d", "--no-build", "--pull", "never", "--wait", "--wait-timeout", "240", "catalog-db")
|
||||
}},
|
||||
{"migrations", func() error {
|
||||
name, err := compose.NewOneShotContainerName(installation.ProjectName() + "-migrate")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return docker(5*time.Minute, "run", "--rm", "-T", "--no-deps", "--pull", "never", "--name", name, "catalog-migrate")
|
||||
}},
|
||||
{"services", func() error {
|
||||
return docker(30*time.Minute, "up", "-d", "--no-build", "--pull", "never", "--wait", "--wait-timeout", "1500", "core", "frontend", "qdrant", "embedding", "embedding-model-init")
|
||||
}},
|
||||
{"health", func() error {
|
||||
bound, cancel := context.WithTimeout(ctx, time.Minute)
|
||||
defer cancel()
|
||||
value, err := runner.Run(bound, installation.ComposeArgs("ps", "--all", "--format", "json"), nil)
|
||||
if err != nil || value.ExitCode != 0 {
|
||||
return errors.New("Cannot inspect services")
|
||||
}
|
||||
if err := service.Healthy(value.Stdout); err != nil {
|
||||
return err
|
||||
}
|
||||
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
|
||||
}},
|
||||
{"workspace-preparation", func() error {
|
||||
report, err := runPreparedClient(ctx, plan, runner, payload, true)
|
||||
result.WorkspacePreparation = &report
|
||||
return err
|
||||
}},
|
||||
}
|
||||
for index, check := range result.RuntimeChecks {
|
||||
action := check.ID
|
||||
stages = append(stages, struct {
|
||||
name string
|
||||
run func() error
|
||||
}{action, func() error {
|
||||
err := runtimeDiagnostic(ctx, plan, runner, action)
|
||||
result.RuntimeChecks[index].Status = "passed"
|
||||
if err != nil {
|
||||
result.RuntimeChecks[index].Status = "failed"
|
||||
}
|
||||
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.
|
||||
for _, stage := range stages {
|
||||
if err := operation(stage.name, stage.run); err != nil {
|
||||
if result.NeedsReview() {
|
||||
return fail(stage.name, "Review the pending schema synchronization in application Administration, then repeat apply. No destructive change was confirmed by the installer.")
|
||||
}
|
||||
return fail(stage.name, err.Error())
|
||||
}
|
||||
}
|
||||
result.PlatformReady = true
|
||||
result.WorkspaceReady = true
|
||||
result.Stage = "workspace-ready"
|
||||
result.Action = "Platform, workspace preparation and runtime checks passed. Open the application for the manual human-reviewed question."
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func runtimeDiagnostic(ctx context.Context, plan preflight.Plan, runner compose.Runner, action string) error {
|
||||
bound, cancel := context.WithTimeout(ctx, 5*time.Minute)
|
||||
defer cancel()
|
||||
name, err := compose.NewOneShotContainerName(plan.Installation.ProjectName() + "-readiness")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value, err := runner.Run(bound, plan.Installation.ComposeArgs("run", "--rm", "-T", "--no-deps", "--pull", "never", "--name", name,
|
||||
"--entrypoint", "node", "core", "/app/backend/dist/operator-command.js", action), nil)
|
||||
var report struct {
|
||||
Ready bool `json:"ready"`
|
||||
}
|
||||
if err != nil || value.ExitCode != 0 || json.Unmarshal([]byte(value.Stdout), &report) != nil || !report.Ready {
|
||||
return errors.New("Runtime diagnostic failed; inspect application diagnostics and correct the prepared configuration")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func installAssets(installation config.Installation, plan preflight.Plan) error {
|
||||
names := make([]string, 0, len(plan.Release.Files))
|
||||
for name := range plan.Release.Files {
|
||||
names = append(names, name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
for _, name := range names {
|
||||
source := filepath.Join(filepath.Dir(plan.ManifestPath), filepath.FromSlash(name))
|
||||
target := filepath.Join(installation.ProjectDirectory, filepath.FromSlash(name))
|
||||
data, err := safeio.ReadCanonicalRegular(source, 32<<20)
|
||||
if err != nil || fmt.Sprintf("%x", sha256.Sum256(data)) != plan.Release.Files[name] {
|
||||
return errors.New("Release asset changed")
|
||||
}
|
||||
if existing, err := safeio.ReadCanonicalRegular(target, 32<<20); err == nil {
|
||||
if fmt.Sprintf("%x", sha256.Sum256(existing)) != plan.Release.Files[name] {
|
||||
return errors.New("Existing release asset differs")
|
||||
}
|
||||
continue
|
||||
}
|
||||
if _, err := os.Lstat(target); !os.IsNotExist(err) {
|
||||
return errors.New("Existing release target is unsafe")
|
||||
}
|
||||
relative, _ := filepath.Rel(installation.ProjectDirectory, filepath.Dir(target))
|
||||
parent := installation.ProjectDirectory
|
||||
if relative != "." {
|
||||
for _, part := range strings.Split(relative, string(filepath.Separator)) {
|
||||
parent = filepath.Join(parent, part)
|
||||
if err := safeio.EnsurePrivateDirectory(parent); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := safeio.PublishCanonicalNewFile(target, data, 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
const runtimeCheck = `
|
||||
const base='http://127.0.0.1:8787';
|
||||
const health=await fetch(base+'/health',{signal:AbortSignal.timeout(10000)});
|
||||
const auth=await fetch(base+'/auth/config',{signal:AbortSignal.timeout(10000)});
|
||||
const protectedRoute=await fetch(base+'/workspaces',{signal:AbortSignal.timeout(10000)});
|
||||
if(!health.ok||!auth.ok||(await auth.json()).mode!=='local'||protectedRoute.status!==401)process.exit(1);
|
||||
console.log(JSON.stringify({ok:true}));
|
||||
`
|
||||
@@ -0,0 +1,321 @@
|
||||
package installapply
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/compose"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/config"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/lifecycle"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/preflight"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/preparation"
|
||||
)
|
||||
|
||||
func fixture(t *testing.T) (string, preflight.Plan) {
|
||||
t.Helper()
|
||||
root, _ := filepath.EvalSymlinks(t.TempDir())
|
||||
_ = os.Chmod(root, 0o700)
|
||||
dir := filepath.Join(root, "installation")
|
||||
if err := preparation.Prepare(dir); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := preparation.Credentials(context.Background(), dir); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
write := func(path, value string) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(path, []byte(value), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, name := range []string{"thothii-installation.yaml", "operator.env"} {
|
||||
p := filepath.Join(dir, name)
|
||||
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\n"} {
|
||||
write(filepath.Join(dir, "secrets", name), value)
|
||||
}
|
||||
installation, err := config.LoadPrepared(filepath.Join(dir, "thothii-installation.yaml"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
release := filepath.Join(root, "release")
|
||||
_ = os.Mkdir(release, 0o700)
|
||||
_ = os.Mkdir(filepath.Join(release, "deploy"), 0o700)
|
||||
m := 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", "deploy/compose.local.yaml"}}
|
||||
inputs := []string{installation.Path, installation.EnvFile, filepath.Join(dir, "secrets/secrets.env")}
|
||||
for _, role := range []string{"core", "frontend", "catalog", "qdrant", "embedding"} {
|
||||
m.Images[role] = map[string]string{"linux/amd64": "docker.io/example/" + role + "@sha256:" + strings.Repeat("a", 64)}
|
||||
}
|
||||
for _, name := range []string{"compose.yaml", "deploy/compose.local.yaml", "deploy/compose.git-https.yaml"} {
|
||||
data := "services: {}\n"
|
||||
path := filepath.Join(release, name)
|
||||
write(path, data)
|
||||
inputs = append(inputs, path)
|
||||
m.Files[name] = fmt.Sprintf("%x", sha256.Sum256([]byte(data)))
|
||||
}
|
||||
manifest := filepath.Join(release, "release-manifest.json")
|
||||
b, _ := json.Marshal(m)
|
||||
write(manifest, string(b))
|
||||
inputs = append(inputs, manifest)
|
||||
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)
|
||||
}
|
||||
return path, p
|
||||
}
|
||||
|
||||
type dockerFixture struct {
|
||||
calls [][]string
|
||||
fail string
|
||||
wrongImage bool
|
||||
source bool
|
||||
}
|
||||
|
||||
func (r *dockerFixture) Run(_ context.Context, args []string, input io.Reader) (compose.Result, error) {
|
||||
if input != nil {
|
||||
if args[len(args)-1] != bindingClient && args[len(args)-1] != readinessClient {
|
||||
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...))
|
||||
if args[len(args)-1] == readinessClient {
|
||||
if r.fail == "schema-review" {
|
||||
return compose.Result{ExitCode: 1, Stdout: `{"ok":false,"code":"schema_review_required","completed":0,"workspaceId":"chinook","runId":"e9ca48f6-0a09-49bd-a003-04f9d518d702"}`}, nil
|
||||
}
|
||||
return compose.Result{Stdout: `{"ok":true,"code":"workspaces_prepared","completed":1}`}, nil
|
||||
}
|
||||
return compose.Result{Stdout: `{"ok":true,"code":"bindings_ready","completed":1}`}, nil
|
||||
}
|
||||
r.calls = append(r.calls, append([]string{}, args...))
|
||||
line := strings.Join(args, " ")
|
||||
if strings.HasPrefix(line, "volume ls ") {
|
||||
return compose.Result{}, nil
|
||||
}
|
||||
if strings.HasPrefix(line, "volume inspect ") {
|
||||
name := args[len(args)-1]
|
||||
parts := strings.SplitN(name, "_", 2)
|
||||
data, _ := json.Marshal(map[string]string{"io.thothii.installation": parts[0], "io.thothii.volume": parts[1]})
|
||||
return compose.Result{Stdout: string(data)}, nil
|
||||
}
|
||||
if strings.HasSuffix(line, " /etc/passwd") {
|
||||
return compose.Result{Stdout: "root:x:0:0:root:/root:/bin/bash\nthoth:x:10001:10001::/home/thoth:/bin/bash\npostgres:x:999:999::/var/lib/postgresql:/bin/bash\n"}, nil
|
||||
}
|
||||
if r.fail != "" && strings.Contains(line, r.fail) {
|
||||
return compose.Result{Stderr: "PRIVATE_SENTINEL"}, fmt.Errorf("PRIVATE_SENTINEL")
|
||||
}
|
||||
if strings.Contains(line, " config ") {
|
||||
services := map[string]any{}
|
||||
for service, role := range map[string]string{"core": "core", "frontend": "frontend", "catalog-db": "catalog", "catalog-migrate": "core", "workspace-maintenance": "core", "qdrant": "qdrant", "embedding": "embedding", "embedding-model-init": "embedding"} {
|
||||
if (service == "catalog-migrate" && !strings.Contains(line, "--profile catalog-maintenance")) || (service == "workspace-maintenance" && !strings.Contains(line, "--profile workspace-maintenance")) {
|
||||
continue
|
||||
}
|
||||
services[service] = map[string]string{"image": "docker.io/example/" + role + "@sha256:" + strings.Repeat("a", 64)}
|
||||
if r.source && (role == "core" || role == "frontend") {
|
||||
services[service] = map[string]string{"image": "sha256:" + strings.Repeat("a", 64)}
|
||||
}
|
||||
}
|
||||
if r.wrongImage {
|
||||
services["core"] = map[string]string{"image": "unverified:latest"}
|
||||
}
|
||||
data, _ := json.Marshal(map[string]any{"services": services})
|
||||
return compose.Result{Stdout: string(data)}, nil
|
||||
}
|
||||
if strings.Contains(line, " ps ") {
|
||||
return compose.Result{Stdout: `[{"Service":"core","State":"running","Health":"healthy"},{"Service":"frontend","State":"running","Health":"healthy"},{"Service":"catalog-db","State":"running","Health":"healthy"},{"Service":"qdrant","State":"running","Health":"healthy"},{"Service":"embedding","State":"running","Health":"healthy"},{"Service":"embedding-model-init","State":"exited","ExitCode":0}]`}, nil
|
||||
}
|
||||
if strings.Contains(line, "/app/backend/dist/operator-command.js") {
|
||||
return compose.Result{Stdout: `{"ready":true}`}, nil
|
||||
}
|
||||
return compose.Result{Stdout: `{"ok":true}`}, nil
|
||||
}
|
||||
|
||||
func TestExplicitSourceApplySharesReadinessAndPullsOnlyUpstream(t *testing.T) {
|
||||
path, p := fixture(t)
|
||||
p.Release.Distribution = "source"
|
||||
for _, role := range []string{"core", "frontend"} {
|
||||
p.Release.Images[role][p.Platform] = "sha256:" + strings.Repeat("a", 64)
|
||||
}
|
||||
data, _ := json.Marshal(p.Release)
|
||||
if err := os.WriteFile(p.ManifestPath, data, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = os.Remove(path)
|
||||
_ = os.Remove(path + ".key")
|
||||
if err := preflight.WritePlan(path, &p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := &dockerFixture{source: true}
|
||||
result, err := Run(context.Background(), Request{PlanPath: path, InstallationPath: p.Installation.Path}, r, func(context.Context, preflight.Plan) error { return nil })
|
||||
if err != nil || !result.WorkspaceReady || result.Distribution != "source" {
|
||||
t.Fatalf("source apply: %+v %v", result, err)
|
||||
}
|
||||
for _, call := range flatten(r.calls) {
|
||||
if strings.Contains(call, " pull ") && !strings.Contains(call, "pull --policy always catalog-db qdrant embedding embedding-model-init") {
|
||||
t.Fatal("source application images pulled")
|
||||
}
|
||||
if strings.Contains(call, " build ") {
|
||||
t.Fatal("apply implicitly built source")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyRefusesUnreleasedEffectiveImageBeforePull(t *testing.T) {
|
||||
path, p := fixture(t)
|
||||
r := &dockerFixture{wrongImage: true}
|
||||
result, err := Run(context.Background(), Request{PlanPath: path, InstallationPath: p.Installation.Path}, r, func(context.Context, preflight.Plan) error { return nil })
|
||||
if err == nil || result.PlatformReady {
|
||||
t.Fatal("unreleased runtime configuration accepted")
|
||||
}
|
||||
if strings.Contains(strings.Join(flatten(r.calls), "\n"), " pull ") {
|
||||
t.Fatal("pull ran despite configuration failure")
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyReleasedPlanWithoutInputAndRepeatPreservesData(t *testing.T) {
|
||||
path, p := fixture(t)
|
||||
r := &dockerFixture{}
|
||||
checks := 0
|
||||
check := func(context.Context, preflight.Plan) error { checks++; return nil }
|
||||
for i := 0; i < 2; i++ {
|
||||
result, err := Run(context.Background(), Request{PlanPath: path, InstallationPath: p.Installation.Path}, r, check)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !result.PlatformReady || !result.WorkspaceReady || result.Stage != "workspace-ready" {
|
||||
t.Fatalf("wrong readiness: %+v", result)
|
||||
}
|
||||
}
|
||||
if checks != 2 {
|
||||
t.Fatal("live prerequisites not repeated")
|
||||
}
|
||||
journal, _ := os.ReadFile(filepath.Join(p.Installation.ControlDirectory(), "installation-apply.json"))
|
||||
if strings.Contains(string(journal), "PRIVATE_SENTINEL") || !strings.Contains(string(journal), `"status": "complete"`) {
|
||||
t.Fatalf("bad journal: %s", journal)
|
||||
}
|
||||
stages := strings.Join(flatten(r.calls), "\n")
|
||||
for _, required := range []string{"pull", "--no-build", "catalog-migrate", "--wait", "exec -T core"} {
|
||||
if !strings.Contains(stages, required) {
|
||||
t.Fatalf("missing %s", required)
|
||||
}
|
||||
}
|
||||
for _, forbidden := range []string{" build ", " down ", " rm -v", "--force-recreate"} {
|
||||
if strings.Contains(stages, forbidden) {
|
||||
t.Fatalf("destructive/source operation %s", forbidden)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkspaceReviewAndRuntimeFailureNeverClaimWorkspaceReady(t *testing.T) {
|
||||
for _, stage := range []string{"schema-review", "operator-command.js pi-test"} {
|
||||
t.Run(stage, func(t *testing.T) {
|
||||
path, p := fixture(t)
|
||||
r := &dockerFixture{fail: stage}
|
||||
result, err := Run(context.Background(), Request{PlanPath: path, InstallationPath: p.Installation.Path}, r, func(context.Context, preflight.Plan) error { return nil })
|
||||
if err == nil || !result.PlatformReady || !result.BindingsReady || result.WorkspaceReady {
|
||||
t.Fatalf("readiness failure hidden: %+v %v", result, err)
|
||||
}
|
||||
if stage == "schema-review" && (result.WorkspacePreparation == nil || result.WorkspacePreparation.Code != "schema_review_required") {
|
||||
t.Fatalf("human gate lost: %+v", result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func flatten(calls [][]string) []string {
|
||||
out := []string{}
|
||||
for _, c := range calls {
|
||||
out = append(out, strings.Join(c, " "))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestFailedPullIsPrivateAndRetryReconcilesWithoutReset(t *testing.T) {
|
||||
path, p := fixture(t)
|
||||
r := &dockerFixture{fail: " pull "}
|
||||
check := func(context.Context, preflight.Plan) error { return nil }
|
||||
result, err := Run(context.Background(), Request{PlanPath: path, InstallationPath: p.Installation.Path}, r, check)
|
||||
if err == nil || result.Stage != "pull" || result.PlatformReady || strings.Contains(err.Error(), "PRIVATE_SENTINEL") {
|
||||
t.Fatalf("bad pull failure: %+v %v", result, err)
|
||||
}
|
||||
for _, call := range flatten(r.calls) {
|
||||
if strings.Contains(call, " up ") || strings.Contains(call, " build ") {
|
||||
t.Fatal("pull failure started or built services")
|
||||
}
|
||||
}
|
||||
data, _ := os.ReadFile(result.Journal)
|
||||
if !strings.Contains(string(data), `"status": "failed"`) || strings.Contains(string(data), "PRIVATE_SENTINEL") {
|
||||
t.Fatal("unsafe failure journal")
|
||||
}
|
||||
r.fail = ""
|
||||
result, err = Run(context.Background(), Request{PlanPath: path, InstallationPath: p.Installation.Path}, r, check)
|
||||
if err != nil || !result.PlatformReady {
|
||||
t.Fatalf("retry: %+v %v", result, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyRefusesStaleInputLiveFailureAndConcurrentExecution(t *testing.T) {
|
||||
for _, failure := range []string{"changed-secret", "live-failure", "concurrent"} {
|
||||
t.Run(failure, func(t *testing.T) {
|
||||
path, p := fixture(t)
|
||||
r := &dockerFixture{}
|
||||
check := func(context.Context, preflight.Plan) error { return nil }
|
||||
switch failure {
|
||||
case "changed-secret":
|
||||
_ = os.WriteFile(filepath.Join(p.Installation.ProjectDirectory, "secrets/secrets.env"), []byte("OPENAI_API_KEY=rotated"), 0o600)
|
||||
case "live-failure":
|
||||
check = func(context.Context, preflight.Plan) error { return fmt.Errorf("PRIVATE_SENTINEL") }
|
||||
case "concurrent":
|
||||
lock, err := lifecycle.Acquire(p.Installation)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer lock.Release()
|
||||
}
|
||||
result, err := Run(context.Background(), Request{PlanPath: path, InstallationPath: p.Installation.Path}, r, check)
|
||||
if err == nil || result.PlatformReady || len(r.calls) != 0 || strings.Contains(err.Error(), "PRIVATE_SENTINEL") {
|
||||
t.Fatalf("unsafe failed admission: %+v %v", result, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyCancellationReleasesLockAndPreservesCompletedStageForRetry(t *testing.T) {
|
||||
path, p := fixture(t)
|
||||
r := &dockerFixture{}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
result, err := Run(ctx, Request{PlanPath: path, InstallationPath: p.Installation.Path}, r, func(context.Context, preflight.Plan) error { cancel(); return nil })
|
||||
if err == nil || result.PlatformReady || len(r.calls) != 0 {
|
||||
t.Fatal("cancelled execution ran Docker")
|
||||
}
|
||||
data, _ := os.ReadFile(result.Journal)
|
||||
if !strings.Contains(string(data), `"status": "interrupted"`) {
|
||||
t.Fatal("interruption not recorded")
|
||||
}
|
||||
result, err = Run(context.Background(), Request{PlanPath: path, InstallationPath: p.Installation.Path}, r, func(context.Context, preflight.Plan) error { return nil })
|
||||
if err != nil || !result.PlatformReady {
|
||||
t.Fatalf("retry: %+v %v", result, err)
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,17 @@ func CheckCompose(ctx context.Context, runner Runner, installation config.Instal
|
||||
}
|
||||
args = append(args, "-f", path)
|
||||
}
|
||||
args = append(args, "config", "--format", "json")
|
||||
args = append(args, "--profile", "catalog-maintenance", "--profile", "workspace-maintenance", "config", "--format", "json")
|
||||
return checkResolvedCompose(ctx, runner, args, m, platform)
|
||||
}
|
||||
|
||||
// CheckInstalledCompose includes generated projections and any durable image override.
|
||||
func CheckInstalledCompose(ctx context.Context, runner Runner, installation config.Installation, m Manifest, platform string) Report {
|
||||
return checkResolvedCompose(ctx, runner, installation.ComposeArgs("--profile", "catalog-maintenance", "--profile", "workspace-maintenance", "config", "--format", "json"), m, platform)
|
||||
}
|
||||
|
||||
func checkResolvedCompose(ctx context.Context, runner Runner, args []string, m Manifest, platform string) Report {
|
||||
r := NewReport()
|
||||
result, err := docker(ctx, runner, args...)
|
||||
var effective struct {
|
||||
Services map[string]struct {
|
||||
|
||||
@@ -28,6 +28,8 @@ type Plan struct {
|
||||
Platform string `json:"platform"`
|
||||
WorkspaceDirectory string `json:"workspace_directory"`
|
||||
WorkspaceRevision string `json:"workspace_revision"`
|
||||
ManifestPath string `json:"manifest_path,omitempty"`
|
||||
BootstrapPath string `json:"bootstrap_path,omitempty"`
|
||||
Inputs []string `json:"inputs"`
|
||||
AbsentInputs []string `json:"absent_inputs"`
|
||||
InputSeal string `json:"input_seal"`
|
||||
@@ -62,10 +64,16 @@ func CaptureInputs(paths []string, workspace string, absent ...string) (func() b
|
||||
|
||||
// A separate owner-only random key prevents public/offline guessing of low-entropy secrets.
|
||||
// Live prerequisites must still be rechecked immediately before any execution or resumption.
|
||||
func seal(plan Plan, key []byte) (string, error) {
|
||||
func seal(plan Plan, key []byte, materialized ...bool) (string, error) {
|
||||
for _, path := range plan.AbsentInputs {
|
||||
if _, err := os.Lstat(path); !errors.Is(err, os.ErrNotExist) {
|
||||
return "", invalidPlan()
|
||||
name := "deploy/" + filepath.Base(path)
|
||||
allowed := len(materialized) > 0 && materialized[0] && (name == "deploy/compose.git-https.yaml" || name == "deploy/compose.git-ssh.yaml") && path == filepath.Join(plan.Installation.ProjectDirectory, filepath.FromSlash(name))
|
||||
data, readErr := safeio.ReadCanonicalRegular(path, 32<<20)
|
||||
sum := sha256.Sum256(data)
|
||||
if !allowed || readErr != nil || hex.EncodeToString(sum[:]) != plan.Release.Files[name] {
|
||||
return "", invalidPlan()
|
||||
}
|
||||
}
|
||||
}
|
||||
mac := hmac.New(sha256.New, key)
|
||||
@@ -138,35 +146,44 @@ func WritePlan(path string, plan *Plan, guards ...func() bool) error {
|
||||
return nil
|
||||
}
|
||||
func VerifyPlanInputs(path string) error {
|
||||
_, err := readPlan(path, false)
|
||||
return err
|
||||
}
|
||||
|
||||
// ReadExecutionPlan permits only exact release-owned overlays installed by a prior attempt.
|
||||
// The authored documents, credentials, bundle and private seal must otherwise remain unchanged.
|
||||
func ReadExecutionPlan(path string) (Plan, error) { return readPlan(path, true) }
|
||||
|
||||
func readPlan(path string, materialized bool) (Plan, error) {
|
||||
data, err := safeio.ReadCanonicalPrivateRegular(path, 4<<20)
|
||||
if err != nil {
|
||||
return invalidPlan()
|
||||
return Plan{}, invalidPlan()
|
||||
}
|
||||
key, err := safeio.ReadCanonicalPrivateRegular(path+".key", 32)
|
||||
if err != nil || len(key) != 32 {
|
||||
return invalidPlan()
|
||||
return Plan{}, invalidPlan()
|
||||
}
|
||||
var plan Plan
|
||||
if json.Unmarshal(data, &plan) != nil || plan.SchemaVersion != 1 || plan.ValidatorProtocol != Protocol || !plan.Report.OK || len(plan.Inputs) == 0 || len(plan.Inputs) > 10000 {
|
||||
return invalidPlan()
|
||||
return Plan{}, invalidPlan()
|
||||
}
|
||||
actual, err := seal(plan, key)
|
||||
actual, err := seal(plan, key, materialized)
|
||||
if err != nil || !hmac.Equal([]byte(actual), []byte(plan.InputSeal)) {
|
||||
return invalidPlan()
|
||||
return Plan{}, invalidPlan()
|
||||
}
|
||||
// Detect added or removed workspace files as well as changes to known file bytes.
|
||||
if plan.WorkspaceDirectory != "" {
|
||||
files, err := treeFiles(plan.WorkspaceDirectory, true)
|
||||
if err != nil {
|
||||
return invalidPlan()
|
||||
return Plan{}, invalidPlan()
|
||||
}
|
||||
for _, file := range files {
|
||||
if !slices.Contains(plan.Inputs, file) {
|
||||
return invalidPlan()
|
||||
return Plan{}, invalidPlan()
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return plan, nil
|
||||
}
|
||||
func treeFiles(root string, skipGit bool) ([]string, error) {
|
||||
paths := []string{}
|
||||
@@ -220,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"`
|
||||
@@ -228,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 {
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package preflight
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/config"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/safeio"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -8,6 +11,32 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestExecutionPlanAcceptsOnlyExactReleaseOwnedMaterialization(t *testing.T) {
|
||||
root, _ := filepath.EvalSymlinks(t.TempDir())
|
||||
_ = os.Chmod(root, 0o700)
|
||||
_ = os.Mkdir(filepath.Join(root, "deploy"), 0o700)
|
||||
input := filepath.Join(root, "input")
|
||||
_ = os.WriteFile(input, []byte("prepared"), 0o600)
|
||||
overlay := filepath.Join(root, "deploy", "compose.git-https.yaml")
|
||||
data := []byte("services: {}\n")
|
||||
plan := Plan{SchemaVersion: 1, ValidatorProtocol: Protocol, Installation: config.Installation{ProjectDirectory: root}, Inputs: []string{input}, AbsentInputs: []string{overlay}, Report: NewReport(), Release: Manifest{Files: map[string]string{"deploy/compose.git-https.yaml": fmt.Sprintf("%x", sha256.Sum256(data))}}}
|
||||
path := filepath.Join(root, "plan.json")
|
||||
if err := WritePlan(path, &plan); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = os.WriteFile(overlay, data, 0o600)
|
||||
if _, err := ReadExecutionPlan(path); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if VerifyPlanInputs(path) == nil {
|
||||
t.Fatal("ordinary validation must still detect new files")
|
||||
}
|
||||
_ = os.WriteFile(overlay, []byte("changed"), 0o600)
|
||||
if _, err := ReadExecutionPlan(path); err == nil {
|
||||
t.Fatal("modified materialization accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlanBindsInputsAndDetectsCredentialRotationWithoutPublicSecretHashes(t *testing.T) {
|
||||
root, _ := filepath.EvalSymlinks(t.TempDir())
|
||||
if err := safeio.ProtectPrivateDirectory(root); err != nil {
|
||||
|
||||
@@ -29,7 +29,16 @@ func (f *fakeDocker) Run(_ context.Context, args []string, _ io.Reader) (compose
|
||||
case "compose":
|
||||
if args[len(args)-1] == "json" {
|
||||
if f.effective != "" {
|
||||
return compose.Result{Stdout: f.effective}, nil
|
||||
var resolved map[string]map[string]any
|
||||
_ = json.Unmarshal([]byte(f.effective), &resolved)
|
||||
line := strings.Join(args, " ")
|
||||
for service, profile := range map[string]string{"catalog-migrate": "catalog-maintenance", "workspace-maintenance": "workspace-maintenance"} {
|
||||
if !strings.Contains(line, "--profile "+profile) {
|
||||
delete(resolved["services"], service)
|
||||
}
|
||||
}
|
||||
data, _ := json.Marshal(resolved)
|
||||
return compose.Result{Stdout: string(data)}, nil
|
||||
}
|
||||
return compose.Result{Stdout: `{"services":{"core":{"image":"example/core:latest"}}}`}, nil
|
||||
}
|
||||
@@ -40,6 +49,19 @@ func (f *fakeDocker) Run(_ context.Context, args []string, _ io.Reader) (compose
|
||||
return compose.Result{}, errors.New("unexpected command")
|
||||
}
|
||||
|
||||
func TestComposeIncludesInactiveMaintenanceProfilesBeforeInstallation(t *testing.T) {
|
||||
m := Manifest{Images: map[string]map[string]string{}, Compose: []string{"compose.yaml"}}
|
||||
services := map[string]map[string]string{}
|
||||
for service, role := range map[string]string{"core": "core", "frontend": "frontend", "catalog-db": "catalog", "catalog-migrate": "core", "workspace-maintenance": "core", "qdrant": "qdrant", "embedding": "embedding", "embedding-model-init": "embedding"} {
|
||||
m.Images[role] = map[string]string{"linux/amd64": "docker.io/example/" + role + "@sha256:" + strings.Repeat("a", 64)}
|
||||
services[service] = map[string]string{"image": m.Images[role]["linux/amd64"]}
|
||||
}
|
||||
data, _ := json.Marshal(map[string]any{"services": services})
|
||||
if r := CheckCompose(context.Background(), &fakeDocker{effective: string(data)}, config.Installation{}, m, "/release/manifest.json", "linux/amd64"); !r.OK {
|
||||
t.Fatalf("maintenance profiles missing: %+v", r)
|
||||
}
|
||||
}
|
||||
|
||||
func TestComposeRejectsIncompleteMutableServiceSet(t *testing.T) {
|
||||
r := CheckCompose(context.Background(), &fakeDocker{}, config.Installation{ProjectDirectory: "/private", EnvFile: "/private/operator.env"}, Manifest{Compose: []string{"compose.yaml"}}, "/release/manifest.json", "linux/amd64")
|
||||
if r.OK {
|
||||
|
||||
@@ -19,6 +19,7 @@ import (
|
||||
// Manifest is the publication/consumer contract. Each platform maps to a single-image digest,
|
||||
// not a mutable tag or multi-platform index. Maintenance roles use Images["core"].
|
||||
type Manifest struct {
|
||||
Distribution string `json:"distribution,omitempty"`
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
Version string `json:"version"`
|
||||
Revision string `json:"revision"`
|
||||
@@ -30,6 +31,13 @@ type Manifest struct {
|
||||
Compose []string `json:"compose"`
|
||||
}
|
||||
|
||||
func (m Manifest) Mode() string {
|
||||
if m.Distribution == "source" {
|
||||
return "source"
|
||||
}
|
||||
return "prebuilt"
|
||||
}
|
||||
|
||||
var hex256 = regexp.MustCompile(`^[a-f0-9]{64}$`)
|
||||
var imageReference = regexp.MustCompile(`^docker\.io/[a-z0-9][a-z0-9._/-]*@sha256:[a-f0-9]{64}$`)
|
||||
|
||||
@@ -37,6 +45,9 @@ func invalidRelease() error {
|
||||
return errors.New("release manifest or packaged files are incomplete, incompatible or invalid")
|
||||
}
|
||||
func (m Manifest) Validate() error {
|
||||
if m.Distribution != "" && m.Distribution != "prebuilt" && m.Distribution != "source" {
|
||||
return invalidRelease()
|
||||
}
|
||||
if m.SchemaVersion != 1 || m.ValidatorProtocol != Protocol || !regexp.MustCompile(`^[0-9]+\.[0-9]+\.[0-9]+(?:-[A-Za-z0-9.-]+)?$`).MatchString(m.Version) || !regexp.MustCompile(`^[a-f0-9]{40}$`).MatchString(m.Revision) {
|
||||
return invalidRelease()
|
||||
}
|
||||
@@ -56,7 +67,11 @@ func (m Manifest) Validate() error {
|
||||
return invalidRelease()
|
||||
}
|
||||
for platform, ref := range m.Images[service] {
|
||||
if (platform != "linux/amd64" && platform != "linux/arm64") || !imageReference.MatchString(ref) {
|
||||
valid := imageReference.MatchString(ref)
|
||||
if m.Mode() == "source" && (service == "core" || service == "frontend") {
|
||||
valid = strings.HasPrefix(ref, "sha256:") && hex256.MatchString(strings.TrimPrefix(ref, "sha256:"))
|
||||
}
|
||||
if (platform != "linux/amd64" && platform != "linux/arm64") || !valid {
|
||||
return invalidRelease()
|
||||
}
|
||||
}
|
||||
@@ -110,6 +125,25 @@ func CheckImages(ctx context.Context, runner Runner, m Manifest, platform string
|
||||
r.Add("image-"+service, "error", "release.images."+service, "Publish the selected Linux architecture before producing an executable plan.")
|
||||
continue
|
||||
}
|
||||
if m.Mode() == "source" && (service == "core" || service == "frontend") {
|
||||
result, err := docker(ctx, runner, "image", "inspect", "--format", "{{json .}}", ref)
|
||||
var image struct {
|
||||
ID string `json:"Id"`
|
||||
OS string `json:"Os"`
|
||||
Architecture string `json:"Architecture"`
|
||||
Config struct {
|
||||
Labels map[string]string `json:"Labels"`
|
||||
} `json:"Config"`
|
||||
}
|
||||
good := err == nil && result.ExitCode == 0 && json.Unmarshal([]byte(result.Stdout), &image) == nil && image.ID == ref &&
|
||||
image.OS+"/"+image.Architecture == platform && image.Config.Labels["org.opencontainers.image.revision"] == m.Revision && image.Config.Labels["org.opencontainers.image.version"] == m.Version
|
||||
outcome := "passed"
|
||||
if !good {
|
||||
outcome = "error"
|
||||
}
|
||||
r.Add("image-"+service, outcome, "release.images."+service, "Require the explicitly built local image, matching source revision, version and architecture; rebuild the selected source bundle if it is missing.")
|
||||
continue
|
||||
}
|
||||
result, err := docker(ctx, runner, "manifest", "inspect", "--verbose", ref)
|
||||
var manifest struct {
|
||||
Descriptor struct {
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package preflight
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/compose"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type localDocker struct {
|
||||
fakeDocker
|
||||
wrong bool
|
||||
}
|
||||
|
||||
func (d *localDocker) Run(ctx context.Context, args []string, input io.Reader) (compose.Result, error) {
|
||||
if args[0] != "image" {
|
||||
return d.fakeDocker.Run(ctx, args, input)
|
||||
}
|
||||
revision := strings.Repeat("b", 40)
|
||||
if d.wrong {
|
||||
revision = strings.Repeat("c", 40)
|
||||
}
|
||||
value, _ := json.Marshal(map[string]any{"Id": args[len(args)-1], "Os": "linux", "Architecture": "amd64", "Config": map[string]any{"Labels": map[string]string{"org.opencontainers.image.revision": revision, "org.opencontainers.image.version": "1.0.0"}}})
|
||||
return compose.Result{Stdout: string(value)}, nil
|
||||
}
|
||||
func TestSourceImagesNeedExplicitDistributionAndMatchingLocalIdentity(t *testing.T) {
|
||||
m := Manifest{Distribution: "source", Revision: strings.Repeat("b", 40), Version: "1.0.0", Images: map[string]map[string]string{}}
|
||||
for _, role := range []string{"core", "frontend", "catalog", "qdrant", "embedding"} {
|
||||
ref := "docker.io/example/" + role + "@sha256:" + strings.Repeat("a", 64)
|
||||
if role == "core" || role == "frontend" {
|
||||
ref = "sha256:" + strings.Repeat("a", 64)
|
||||
}
|
||||
m.Images[role] = map[string]string{"linux/amd64": ref}
|
||||
}
|
||||
if !CheckImages(context.Background(), &localDocker{}, m, "linux/amd64").OK {
|
||||
t.Fatal("explicit local images rejected")
|
||||
}
|
||||
if CheckImages(context.Background(), &localDocker{wrong: true}, m, "linux/amd64").OK {
|
||||
t.Fatal("different source accepted")
|
||||
}
|
||||
m.Distribution = ""
|
||||
if CheckImages(context.Background(), &localDocker{}, m, "linux/amd64").OK {
|
||||
t.Fatal("implicit source fallback accepted")
|
||||
}
|
||||
}
|
||||
@@ -66,7 +66,7 @@ func Credentials(ctx context.Context, directory string) error {
|
||||
return nil
|
||||
}
|
||||
installation := config.Installation{Authentication: config.Authentication{ConfigDirectory: authDirectory}}
|
||||
if authconfig.Run(ctx, installation, []string{"configure", "--mode", "local", "--public-url", "http://localhost:8080", "--admin-user", "admin", "--password-file", filepath.Join(secrets, "admin-password")}, strings.NewReader(""), io.Discard, io.Discard) != 0 {
|
||||
if authconfig.Run(ctx, installation, []string{"configure", "--mode", "local", "--public-url", "http://127.0.0.1:8080", "--admin-user", "admin", "--password-file", filepath.Join(secrets, "admin-password")}, strings.NewReader(""), io.Discard, io.Discard) != 0 {
|
||||
return fmt.Errorf("cannot prepare local administrator; inspect protected auth files and retry without replacing existing credentials")
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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})
|
||||
@@ -186,6 +213,8 @@ func Validate(path string) (config.Installation, Report) {
|
||||
auth, users, err := authconfig.Load(installation.AuthenticationDirectory())
|
||||
if err != nil {
|
||||
report.Add("auth/auth.yaml", "$", "authentication_invalid", "Prepare and validate local authentication documents before setup, including the initial administrator.")
|
||||
} else if !authconfig.ValidPublicURL(auth.PublicURL) {
|
||||
report.Add("auth/auth.yaml", "publicUrl", "authentication_origin_invalid", "Use HTTPS or a canonical literal loopback HTTP origin, for example http://127.0.0.1:8080; localhost names are not accepted by the runtime.")
|
||||
} else if auth.Mode == "local" {
|
||||
admin := false
|
||||
for _, user := range users.Users {
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package safeio
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// PublishCanonicalNewFile durably publishes complete bytes without replacing an existing
|
||||
// target. A crash before publication can leave a private temporary file, never a partial target.
|
||||
func PublishCanonicalNewFile(path string, contents []byte, mode os.FileMode) error {
|
||||
if ValidateCanonicalPath(path) != nil || ValidatePrivateDirectory(filepath.Dir(path)) != nil || (mode != 0o600 && mode != 0o644) {
|
||||
return ErrUnsafeFile
|
||||
}
|
||||
return publishCanonicalNewFile(path, contents, mode)
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package safeio
|
||||
|
||||
import "golang.org/x/sys/unix"
|
||||
|
||||
func publishNoReplace(directory int, source, target string) error {
|
||||
return unix.RenameatxNp(directory, source, directory, target, unix.RENAME_EXCL)
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
//go:build linux || darwin
|
||||
|
||||
package safeio
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
func TestPublicationWriteFailureLeavesNoTarget(t *testing.T) {
|
||||
if path := os.Getenv("THT_SAFEIO_WRITE_FAILURE_PATH"); path != "" {
|
||||
signal.Ignore(syscall.SIGXFSZ)
|
||||
if err := unix.Setrlimit(unix.RLIMIT_FSIZE, &unix.Rlimit{Cur: 1, Max: 1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if PublishCanonicalNewFile(path, bytes.Repeat([]byte("x"), 4096), 0o600) == nil {
|
||||
t.Fatal("short write published")
|
||||
}
|
||||
if _, err := os.Lstat(path); !os.IsNotExist(err) {
|
||||
t.Fatal("failed write exposed target")
|
||||
}
|
||||
return
|
||||
}
|
||||
root, _ := filepath.EvalSymlinks(t.TempDir())
|
||||
if err := os.Chmod(root, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cmd := exec.Command(os.Args[0], "-test.run=^TestPublicationWriteFailureLeavesNoTarget$")
|
||||
cmd.Env = append(os.Environ(), "THT_SAFEIO_WRITE_FAILURE_PATH="+filepath.Join(root, "asset"))
|
||||
if output, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("write fault proof: %v %s", err, output)
|
||||
}
|
||||
entries, _ := os.ReadDir(root)
|
||||
if len(entries) != 0 {
|
||||
t.Fatal("failed write leaked temporary file")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package safeio
|
||||
|
||||
import "golang.org/x/sys/unix"
|
||||
|
||||
func publishNoReplace(directory int, source, target string) error {
|
||||
return unix.Renameat2(directory, source, directory, target, unix.RENAME_NOREPLACE)
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
//go:build !linux && !darwin && !windows
|
||||
|
||||
package safeio
|
||||
|
||||
import "os"
|
||||
|
||||
func publishCanonicalNewFile(string, []byte, os.FileMode) error { return ErrUnsafeFile }
|
||||
@@ -0,0 +1,66 @@
|
||||
package safeio
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPublishNewFileExposesOnlyCompleteWinner(t *testing.T) {
|
||||
root, err := filepath.EvalSymlinks(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Chmod(root, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := filepath.Join(root, "asset")
|
||||
a, b := bytes.Repeat([]byte("a"), 2<<20), bytes.Repeat([]byte("b"), 2<<20)
|
||||
start := make(chan struct{})
|
||||
results := make(chan error, 2)
|
||||
var writers sync.WaitGroup
|
||||
for _, value := range [][]byte{a, b} {
|
||||
writers.Add(1)
|
||||
go func(value []byte) {
|
||||
defer writers.Done()
|
||||
<-start
|
||||
results <- PublishCanonicalNewFile(path, value, 0o600)
|
||||
}(value)
|
||||
}
|
||||
done := make(chan struct{})
|
||||
go func() { writers.Wait(); close(done) }()
|
||||
close(start)
|
||||
for {
|
||||
contents, err := os.ReadFile(path)
|
||||
if err == nil && !bytes.Equal(contents, a) && !bytes.Equal(contents, b) {
|
||||
t.Fatal("partial publication observed")
|
||||
}
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case <-done:
|
||||
goto finished
|
||||
default:
|
||||
}
|
||||
}
|
||||
finished:
|
||||
first, second := <-results, <-results
|
||||
if (first == nil) == (second == nil) {
|
||||
t.Fatal("exactly one writer must publish")
|
||||
}
|
||||
before, _ := os.ReadFile(path)
|
||||
if PublishCanonicalNewFile(path, []byte("replacement"), 0o600) == nil {
|
||||
t.Fatal("existing publication overwritten")
|
||||
}
|
||||
after, _ := os.ReadFile(path)
|
||||
if !bytes.Equal(before, after) {
|
||||
t.Fatal("failed publication changed target")
|
||||
}
|
||||
entries, _ := os.ReadDir(root)
|
||||
if len(entries) != 1 {
|
||||
t.Fatal("temporary files leaked")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
//go:build linux || darwin
|
||||
|
||||
package safeio
|
||||
|
||||
import (
|
||||
"golang.org/x/sys/unix"
|
||||
"os"
|
||||
)
|
||||
|
||||
func publishCanonicalNewFile(path string, contents []byte, mode os.FileMode) error {
|
||||
directory, target, err := openCanonicalParentDirectory(path)
|
||||
if err != nil {
|
||||
return ErrUnsafeFile
|
||||
}
|
||||
defer unix.Close(directory)
|
||||
temporary, err := writePrivateTemporaryAt(directory, contents)
|
||||
if err != nil {
|
||||
return ErrUnsafeFile
|
||||
}
|
||||
defer func() {
|
||||
if temporary != "" {
|
||||
_ = unix.Unlinkat(directory, temporary, 0)
|
||||
}
|
||||
}()
|
||||
fd, err := unix.Openat(directory, temporary, unix.O_RDONLY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0)
|
||||
if err != nil {
|
||||
return ErrUnsafeFile
|
||||
}
|
||||
err = unix.Fchmod(fd, uint32(mode))
|
||||
if err == nil {
|
||||
err = unix.Fsync(fd)
|
||||
}
|
||||
_ = unix.Close(fd)
|
||||
if err != nil {
|
||||
return ErrUnsafeFile
|
||||
}
|
||||
if err := publishNoReplace(directory, temporary, target); err != nil {
|
||||
return ErrUnsafeFile
|
||||
}
|
||||
temporary = ""
|
||||
if unix.Fsync(directory) != nil {
|
||||
return ErrUnsafeFile
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package safeio
|
||||
|
||||
import (
|
||||
"golang.org/x/sys/windows"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
func publishCanonicalNewFile(path string, contents []byte, mode os.FileMode) error {
|
||||
parents, target, err := openCanonicalWindowsParent(path)
|
||||
if err != nil {
|
||||
return ErrUnsafeFile
|
||||
}
|
||||
defer parents.Close()
|
||||
if len(parents.handles) == 0 || validateOwnerOnlyDACL(parents.handles[len(parents.handles)-1]) != nil {
|
||||
return ErrUnsafeFile
|
||||
}
|
||||
temporary, err := writePrivateTemporary(parents.directory, contents)
|
||||
if err != nil {
|
||||
return ErrUnsafeFile
|
||||
}
|
||||
defer os.Remove(temporary)
|
||||
from, err := windows.UTF16PtrFromString(temporary)
|
||||
if err != nil {
|
||||
return ErrUnsafeFile
|
||||
}
|
||||
to, err := windows.UTF16PtrFromString(filepath.Join(parents.directory, target))
|
||||
if err != nil {
|
||||
return ErrUnsafeFile
|
||||
}
|
||||
if windows.MoveFileEx(from, to, windows.MOVEFILE_WRITE_THROUGH) != nil {
|
||||
return ErrUnsafeFile
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -116,7 +116,8 @@ func writePrivateTemporaryAt(directory int, contents []byte) (string, error) {
|
||||
unix.Close(descriptor)
|
||||
return "", ErrUnsafeFile
|
||||
}
|
||||
if err := file.Chmod(0o600); err == nil {
|
||||
err = file.Chmod(0o600)
|
||||
if err == nil {
|
||||
var written int
|
||||
written, err = file.Write(contents)
|
||||
if err == nil && written != len(contents) {
|
||||
|
||||
Reference in New Issue
Block a user