Files
ThothII/tools/tht/internal/installapply/bindings.go

155 lines
6.1 KiB
Go

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
}