feat: import prepared Catalog bindings through authenticated services

This commit is contained in:
Codex
2026-10-06 18:04:07 +02:00
parent d720da721b
commit af4c7b5df9
29 changed files with 835 additions and 35 deletions
@@ -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 {
@@ -79,7 +79,7 @@ func TestNativeInstallationPlanBeforeContainersExist(t *testing.T) {
for name, data := range map[string][]byte{"secrets.env": []byte("OPENAI_API_KEY=PRIVATE_PROVIDER_VALUE\n"), "database-password": []byte("PRIVATE_DATABASE_VALUE"), "git-credentials": {}, "git-ca.pem": pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: git.Certificate().Raw})} {
write(filepath.Join(installation, "secrets", name), data)
}
write(filepath.Join(installation, "database-bootstrap.yaml"), []byte(fmt.Sprintf("schemaVersion: 1\ndatabases:\n - workspaceId: practice\n engine: postgres\n databaseName: practice\n schema: public\n binding: {transport: rest_api, baseUrl: %q, restPath: /health, restAuth: bearer}\n secretFiles: {apiKey: %q}\n", database.URL, filepath.Join(installation, "secrets/database-password"))))
write(filepath.Join(installation, "database-bootstrap.yaml"), []byte(fmt.Sprintf("schemaVersion: 1\nauthentication: {username: admin, passwordFile: %q}\ndatabases:\n - workspaceId: practice\n engine: postgres\n databaseName: practice\n schema: public\n binding: {transport: rest_api, baseUrl: %q, restPath: /health, restAuth: bearer}\n secretFiles: {apiKey: %q}\n", filepath.Join(installation, "secrets/admin-password"), database.URL, filepath.Join(installation, "secrets/database-password"))))
manifest := preflight.Manifest{SchemaVersion: 1, Version: "1.0.0", Revision: strings.Repeat("b", 40), ValidatorProtocol: 1, Requirements: preflight.DefaultRequirements(), Components: []string{"pi", "catalog-migrations", "workspace-maintenance"}, Images: map[string]map[string]string{}, Files: map[string]string{}, Compose: []string{"compose.yaml"}}
code, identityJSON := command("version")
var identity version.Info
@@ -111,6 +111,7 @@ run) case "$*" in *'/etc/passwd') printf 'root:x:0:0:root:/root:/bin/bash\nthoth
container) :;;
*) exit 1;;`, 1)
script = strings.Replace(script, "else printf '%s\\n'", `elif case "$*" in *' ps '*) true;; *) false;; esac; then printf '%s\n' '[{"Service":"core","State":"running","Health":"healthy"},{"Service":"frontend","State":"running","Health":"healthy"},{"Service":"qdrant","State":"running","Health":"healthy"},{"Service":"embedding","State":"running","Health":"healthy"},{"Service":"embedding-model-init","State":"exited","ExitCode":0}]'; else printf '%s\n'`, 1)
script = strings.Replace(script, "else printf '%s\\n'", `elif case "$*" in *'protected input arrives only through stdin'*) true;; *) false;; esac; then while IFS= read -r line; do :; done; printf '%s\n' '{"ok":true,"code":"bindings_ready","completed":1}'; else printf '%s\n'`, 1)
write(filepath.Join(root, "docker"), []byte(script))
_ = os.Chmod(filepath.Join(root, "docker"), 0o700)
planPath := filepath.Join(installation, "plan.json")
+141
View File
@@ -0,0 +1,141 @@
package installapply
import (
"bytes"
"context"
"crypto/sha256"
_ "embed"
"encoding/json"
"errors"
"fmt"
"path/filepath"
"slices"
"strings"
"time"
"github.com/aritmolab/thothii/tools/tht/internal/authconfig"
"github.com/aritmolab/thothii/tools/tht/internal/compose"
"github.com/aritmolab/thothii/tools/tht/internal/preflight"
"github.com/aritmolab/thothii/tools/tht/internal/safeio"
"gopkg.in/yaml.v3"
)
//go:embed import-bindings.mjs
var bindingClientModule string
var bindingClient = bindingClientModule + "\nawait importPreparedBindings();\n"
type BindingReport struct {
OK bool `json:"ok"`
Code string `json:"code"`
Completed int `json:"completed"`
}
// Secrets travel only over the child pipe; they never enter argv, generated assets or journals.
func bindingPayload(plan preflight.Plan) ([]byte, error) {
failure := errors.New("Prepare authentication.username and authentication.passwordFile in the protected database bootstrap document, validate and produce a new plan.")
data, err := safeio.ReadCanonicalPrivateRegular(plan.BootstrapPath, 1<<20)
if err != nil {
return nil, failure
}
var doc struct {
SchemaVersion int `yaml:"schemaVersion"`
Authentication struct {
Username string `yaml:"username"`
PasswordFile string `yaml:"passwordFile"`
} `yaml:"authentication"`
Databases []map[string]any `yaml:"databases"`
}
if yaml.Unmarshal(data, &doc) != nil || doc.SchemaVersion != 1 || doc.Authentication.Username == "" || len(doc.Databases) == 0 {
return nil, failure
}
readSecret := func(path string) (string, error) {
if !slices.Contains(plan.Inputs, path) {
return "", failure
}
value, err := safeio.ReadCanonicalPrivateRegular(path, 64<<10)
if err != nil || len(value) == 0 {
return "", failure
}
return string(value), nil
}
password, err := readSecret(doc.Authentication.PasswordFile)
if err != nil {
return nil, failure
}
auth, _, err := authconfig.Load(plan.Installation.AuthenticationDirectory())
if err != nil || auth.Mode != "local" {
return nil, failure
}
files := map[string]string{}
for _, path := range plan.Inputs {
rel, err := filepath.Rel(plan.WorkspaceDirectory, path)
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || filepath.IsAbs(rel) {
continue
}
parts := strings.Split(filepath.ToSlash(rel), "/")
if slices.Contains(parts, ".git") {
continue
}
value, err := safeio.ReadCanonicalRegular(path, 32<<20)
if err != nil {
return nil, failure
}
files[filepath.ToSlash(rel)] = fmt.Sprintf("%x", sha256.Sum256(value))
}
if len(files) == 0 {
return nil, failure
}
databases := []map[string]any{}
for _, entry := range doc.Databases {
values := map[string]any{}
for _, pair := range [][2]string{{"secretFiles", "secrets"}, {"evidenceSecretFiles", "evidenceSecrets"}} {
secrets := map[string]string{}
if refs, ok := entry[pair[0]].(map[string]any); ok {
for name, reference := range refs {
path, ok := reference.(string)
if !ok {
return nil, failure
}
secret, err := readSecret(path)
if err != nil {
return nil, failure
}
// Match file-based preflight adapters for scalar credentials; preserve PEM/known-host files.
if name != "sshPrivateKey" && name != "sshKnownHosts" && name != "tlsCa" {
secret = strings.TrimSpace(secret)
}
secrets[name] = secret
}
}
delete(entry, pair[0])
values[pair[1]] = secrets
}
values["schemaVersion"] = 1
values["configuration"] = entry
databases = append(databases, values)
}
return json.Marshal(map[string]any{"username": doc.Authentication.Username, "password": strings.TrimSpace(password),
"origin": strings.TrimSuffix(auth.PublicURL, "/"), "databases": databases,
"source": map[string]any{"remote": plan.Installation.WorkspaceRepository.Remote, "branch": plan.Installation.WorkspaceRepository.Branch,
"revision": plan.WorkspaceRevision, "files": files}})
}
func importBindings(ctx context.Context, plan preflight.Plan, runner compose.Runner, payload []byte) (BindingReport, error) {
bound, cancel := context.WithTimeout(ctx, 15*time.Minute)
defer cancel()
name, err := compose.NewOneShotContainerName(plan.Installation.ProjectName() + "-bindings")
if err != nil {
return BindingReport{Code: "binding_import_failed"}, err
}
result, err := runner.Run(bound, plan.Installation.ComposeArgs("run", "--rm", "-T", "--no-deps", "--pull", "never", "--name", name,
"--entrypoint", "node", "core", "--input-type=module", "-e", bindingClient), bytes.NewReader(payload))
var report BindingReport
if json.Unmarshal([]byte(result.Stdout), &report) != nil || !slices.Contains([]string{"bindings_ready", "authentication_required", "workspace_reconciliation_required", "binding_reconciliation_required", "container_connection_failed", "binding_import_failed"}, report.Code) {
return BindingReport{Code: "binding_import_failed"}, errors.New("Binding import did not return a valid report")
}
if err != nil || result.ExitCode != 0 || !report.OK || report.Code != "bindings_ready" || report.Completed < 1 {
return report, errors.New("Binding import stopped; reconcile the prepared documents with application administration and repeat planning")
}
return report, nil
}
@@ -0,0 +1,40 @@
// Fixed client executed inside the released core; protected input arrives only through stdin.
export async function importPreparedBindings(base = "http://core:8787") {
let cookie = "", csrf = "", origin = "", completed = 0, code = "authentication_required";
const request = async (path, body) => fetch(base + path, {
method: body === undefined ? "GET" : "POST", redirect: "error", signal: AbortSignal.timeout(180000),
headers: { "content-type": "application/json", origin, ...(cookie ? { cookie } : {}), ...(csrf ? { "x-thothii-csrf": csrf } : {}) },
...(body === undefined ? {} : { body: JSON.stringify(body) }),
});
try {
let input = "";
for await (const chunk of process.stdin) { input += chunk; if (Buffer.byteLength(input) > 16 * 1024 * 1024) throw Error(); }
const prepared = JSON.parse(input); input = ""; origin = prepared.origin;
const login = await request("/auth/local/login", { username: prepared.username, password: prepared.password, remember: false });
prepared.password = "";
if (!login.ok) throw Error();
cookie = login.headers.get("set-cookie")?.split(";")[0] ?? "";
if (!cookie) throw Error();
const me = await request("/me"); if (!me.ok) throw Error();
csrf = (await me.json()).csrfToken; if (!csrf) throw Error();
code = "workspace_reconciliation_required";
const source = await request("/installation/workspace-source", prepared.source);
if (!source.ok) throw Error();
const { revision } = await source.json();
for (const entry of prepared.databases) {
code = "binding_import_failed";
const response = await request("/installation/bindings", { ...entry, revision });
if (response.status === 409) code = "binding_reconciliation_required";
if (response.status === 422) code = "container_connection_failed";
if (!response.ok) throw Error();
const value = await response.json();
if (value.connectionStatus !== "reachable" || !["applied", "unchanged"].includes(value.status)) throw Error();
completed++;
}
code = "bindings_ready";
} catch { process.exitCode = 1; }
finally {
if (cookie && csrf) { try { await request("/auth/logout", {}); } catch {} }
process.stdout.write(JSON.stringify({ ok: code === "bindings_ready", code, completed }));
}
}
+22 -8
View File
@@ -25,12 +25,14 @@ import (
type Request struct{ PlanPath, InstallationPath string }
type Result struct {
SchemaVersion int `json:"schema_version"`
PlatformReady bool `json:"platform_ready"`
WorkspaceReady bool `json:"workspace_ready"`
Stage string `json:"stage"`
Action string `json:"action"`
Journal string `json:"journal,omitempty"`
SchemaVersion int `json:"schema_version"`
PlatformReady bool `json:"platform_ready"`
WorkspaceReady bool `json:"workspace_ready"`
BindingsReady bool `json:"bindings_ready"`
BindingImport *BindingReport `json:"binding_import,omitempty"`
Stage string `json:"stage"`
Action string `json:"action"`
Journal string `json:"journal,omitempty"`
}
type journal struct {
SchemaVersion int `json:"schema_version"`
@@ -88,6 +90,11 @@ func Run(ctx context.Context, request Request, runner compose.Runner, check Chec
if _, err := preflight.ReadExecutionPlan(request.PlanPath); err != nil {
return fail("validation", "Inputs changed during checks; repeat planning before execution.")
}
payload, err := bindingPayload(plan)
if err != nil {
return fail("bootstrap-input", err.Error())
}
defer clear(payload)
result.Journal = filepath.Join(installation.ControlDirectory(), "installation-apply.json")
state := journal{SchemaVersion: 1, Installation: installation.Path, ReleaseRevision: plan.Release.Revision, PlanSeal: plan.InputSeal}
if _, err := os.Lstat(result.Journal); err == nil {
@@ -194,6 +201,13 @@ func Run(ctx context.Context, request Request, runner compose.Runner, check Chec
}
return docker(time.Minute, "exec", "-T", "core", "node", "--input-type=module", "-e", runtimeCheck)
}},
{"bindings", func() error {
result.PlatformReady = true
report, err := importBindings(ctx, plan, runner, payload)
result.BindingImport = &report
result.BindingsReady = err == nil
return err
}},
}
// Reconcile each idempotent stage against Docker/migration authority on every retry.
// A journal entry alone is never proof that a container or migration still exists.
@@ -203,8 +217,8 @@ func Run(ctx context.Context, request Request, runner compose.Runner, check Chec
}
}
result.PlatformReady = true
result.Stage = "platform-ready"
result.Action = "Platform is running. Import prepared database bindings and complete workspace readiness before a human-reviewed question."
result.Stage = "bindings-ready"
result.Action = "Platform and prepared database bindings are ready. Complete workspace readiness before a human-reviewed question."
return result, nil
}
+22 -3
View File
@@ -40,7 +40,7 @@ func fixture(t *testing.T) (string, preflight.Plan) {
b, _ := os.ReadFile(p)
write(p, strings.ReplaceAll(string(b), "https://CHANGE_ME/workspaces.git", "https://example.com/workspaces.git"))
}
for name, value := range map[string]string{"secrets.env": "OPENAI_API_KEY=PRIVATE_SENTINEL\n", "git-credentials": "", "git-ca.pem": "", "database-password": "PRIVATE_SENTINEL"} {
for name, value := range map[string]string{"secrets.env": "OPENAI_API_KEY=PRIVATE_SENTINEL\n", "git-credentials": "", "git-ca.pem": "", "database-password": "PRIVATE_SENTINEL\n"} {
write(filepath.Join(dir, "secrets", name), value)
}
installation, err := config.LoadPrepared(filepath.Join(dir, "thothii-installation.yaml"))
@@ -66,7 +66,11 @@ func fixture(t *testing.T) (string, preflight.Plan) {
b, _ := json.Marshal(m)
write(manifest, string(b))
inputs = append(inputs, manifest)
p := preflight.Plan{SchemaVersion: 1, ValidatorProtocol: 1, Installation: installation, Release: m, ManifestPath: manifest, BootstrapPath: filepath.Join(dir, "database-bootstrap.yaml"), Platform: "linux/amd64", Inputs: inputs, AbsentInputs: preflight.AbsentOverrides(installation), Report: preflight.NewReport()}
workspace := filepath.Join(root, "workspaces")
_ = os.Mkdir(workspace, 0o700)
write(filepath.Join(workspace, "thoth-workspaces.yaml"), "schema_version: 1\nworkspaces: []\n")
inputs = append(inputs, filepath.Join(workspace, "thoth-workspaces.yaml"), filepath.Join(dir, "secrets/admin-password"), filepath.Join(dir, "secrets/database-password"), filepath.Join(dir, "database-bootstrap.yaml"))
p := preflight.Plan{SchemaVersion: 1, ValidatorProtocol: 1, Installation: installation, Release: m, ManifestPath: manifest, BootstrapPath: filepath.Join(dir, "database-bootstrap.yaml"), WorkspaceDirectory: workspace, WorkspaceRevision: "content-snapshot", Platform: "linux/amd64", Inputs: inputs, AbsentInputs: preflight.AbsentOverrides(installation), Report: preflight.NewReport()}
path := filepath.Join(dir, "plan.json")
if err := preflight.WritePlan(path, &p); err != nil {
t.Fatal(err)
@@ -82,7 +86,22 @@ type dockerFixture struct {
func (r *dockerFixture) Run(_ context.Context, args []string, input io.Reader) (compose.Result, error) {
if input != nil {
return compose.Result{}, fmt.Errorf("unexpected interactive input")
if args[len(args)-1] != bindingClient {
return compose.Result{}, fmt.Errorf("unexpected interactive input")
}
command := strings.Join(args, " ")
if !strings.Contains(command, " run --rm -T --no-deps --pull never --name ") || !strings.Contains(command, " --entrypoint node core ") {
return compose.Result{}, fmt.Errorf("import must use a named one-shot for cancellation cleanup")
}
data, err := io.ReadAll(input)
if err != nil || !strings.Contains(string(data), "PRIVATE_SENTINEL") || strings.Contains(strings.Join(args, " "), "PRIVATE_SENTINEL") {
return compose.Result{}, fmt.Errorf("invalid protected pipe")
}
if strings.Contains(string(data), `PRIVATE_SENTINEL\n`) {
return compose.Result{}, fmt.Errorf("file newline leaked into scalar credential")
}
r.calls = append(r.calls, append([]string{}, args...))
return compose.Result{Stdout: `{"ok":true,"code":"bindings_ready","completed":1}`}, nil
}
r.calls = append(r.calls, append([]string{}, args...))
line := strings.Join(args, " ")
+6
View File
@@ -237,6 +237,9 @@ func CollectInputs(installation config.Installation, workspace, bootstrap, manif
return nil, "", invalidPlan()
}
var bindings struct {
Authentication struct {
PasswordFile string `yaml:"passwordFile"`
} `yaml:"authentication"`
Databases []struct {
SecretFiles map[string]string `yaml:"secretFiles"`
EvidenceSecretFiles map[string]string `yaml:"evidenceSecretFiles"`
@@ -245,6 +248,9 @@ func CollectInputs(installation config.Installation, workspace, bootstrap, manif
if yaml.Unmarshal(data, &bindings) != nil {
return nil, "", invalidPlan()
}
if bindings.Authentication.PasswordFile != "" {
paths = append(paths, bindings.Authentication.PasswordFile)
}
for _, entry := range bindings.Databases {
for _, values := range []map[string]string{entry.SecretFiles, entry.EvidenceSecretFiles} {
for _, path := range values {
+4 -1
View File
@@ -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})