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"} { 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) 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()} 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 } 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") } 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"} { services[service] = map[string]string{"image": "docker.io/example/" + role + "@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 } return compose.Result{Stdout: `{"ok":true}`}, nil } 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 { 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 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) } }