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
+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, " ")