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

322 lines
14 KiB
Go

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)
}
}