feat: apply sealed installation plans without interactive setup
This commit is contained in:
@@ -97,6 +97,35 @@ THT_INSTALLATION_TEST_CLI=/absolute/path/dist/workspace-tools/darwin-arm64/tht \
|
||||
go test ./cmd/tht -run TestNativeInstallationPlanBeforeContainersExist -count=1
|
||||
```
|
||||
|
||||
## Non-interactive platform apply (issue #47)
|
||||
|
||||
With the matching released operator and a fresh sealed plan:
|
||||
|
||||
```sh
|
||||
tht --installation /absolute/path/thothii-installation.yaml \
|
||||
installation apply --plan /absolute/path/installation-plan.json --json
|
||||
```
|
||||
|
||||
The command repeats checks, pulls immutable images, initializes local runtime identity
|
||||
and volumes, migrates Catalog/Memory and starts the platform without stdin prompts.
|
||||
It preserves original protected authentication files and uses the non-root preparing
|
||||
operator's UID. Retry reconciles services and preserves existing data. Platform success
|
||||
does not claim workspace readiness. See the IT/EN guides for recovery and limitations.
|
||||
|
||||
The native fixture test above also exercises apply and retry with closed stdin and
|
||||
without host Node/Python/Bun. An additional opt-in proof uses the already-published
|
||||
preview images to test Linux volume ownership, interrupted initialization, PostgreSQL
|
||||
startup with a private password file and data preservation across restart:
|
||||
|
||||
```sh
|
||||
cd tools/tht
|
||||
THT_INSTALLATION_DOCKER_TEST=1 go test ./internal/installapply \
|
||||
-run TestPublishedImagesAcceptProtectedOperatorIdentity -count=1 -v
|
||||
```
|
||||
|
||||
This proof needs the pinned amd64 images pulled locally. Emulation on another CPU is
|
||||
a runtime compatibility check, not platform certification.
|
||||
|
||||
## Shell configuration
|
||||
|
||||
The schema-v2 `thothii-installation.yaml` accepts this optional section:
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/compose"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/installapply"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/preflight"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/version"
|
||||
)
|
||||
|
||||
func installationApplyCommand(ctx context.Context, installationPath string, args []string, stdout io.Writer) int {
|
||||
structured := slices.Contains(args, "--json")
|
||||
write := func(result installapply.Result) {
|
||||
if structured {
|
||||
_ = json.NewEncoder(stdout).Encode(result)
|
||||
} else {
|
||||
fmt.Fprintf(stdout, "%s: %s\n", result.Stage, result.Action)
|
||||
}
|
||||
}
|
||||
var planPath string
|
||||
valid := len(args) > 0 && args[0] == "apply" && filepath.IsAbs(installationPath)
|
||||
seenJSON := false
|
||||
for index := 1; index < len(args); index++ {
|
||||
switch args[index] {
|
||||
case "--json":
|
||||
if seenJSON {
|
||||
valid = false
|
||||
}
|
||||
seenJSON = true
|
||||
case "--plan":
|
||||
if planPath != "" || index+1 >= len(args) {
|
||||
valid = false
|
||||
} else {
|
||||
index++
|
||||
planPath = args[index]
|
||||
}
|
||||
default:
|
||||
valid = false
|
||||
}
|
||||
}
|
||||
if !valid || !filepath.IsAbs(planPath) {
|
||||
write(installapply.Result{SchemaVersion: 1, Stage: "usage", Action: "Use --installation ABS_PATH installation apply --plan ABS_PLAN [--json]."})
|
||||
return 2
|
||||
}
|
||||
runner := compose.NewRunnerWithEnvironment("", installationDockerEnvironment())
|
||||
check := func(ctx context.Context, p preflight.Plan) error {
|
||||
if version.Current().Commit != p.Release.Revision || version.Current().Version != p.Release.Version {
|
||||
return errors.New("use the operator supplied with this release")
|
||||
}
|
||||
var documents bytes.Buffer
|
||||
if installationDocumentsCommand(ctx, installationPath, []string{"validate", "--workspaces", p.WorkspaceDirectory, "--bootstrap", p.BootstrapPath, "--json"}, &documents) != 0 {
|
||||
return errors.New("prepared documents failed validation")
|
||||
}
|
||||
host, err := preflight.InspectHost(p.Installation.ProjectDirectory)
|
||||
if err != nil || "linux/"+host.Arch != p.Platform {
|
||||
return errors.New("host platform differs from plan")
|
||||
}
|
||||
report := preflight.CheckHost(ctx, runner, host, p.Release.Requirements)
|
||||
if report.OK {
|
||||
report.Merge(preflight.CheckImages(ctx, runner, p.Release, p.Platform))
|
||||
}
|
||||
if report.OK {
|
||||
report.Merge(preflight.CheckCompose(ctx, runner, p.Installation, p.Release, p.ManifestPath, p.Platform))
|
||||
}
|
||||
if report.OK {
|
||||
report.Merge(preflight.CheckExternal(ctx, p.Installation))
|
||||
}
|
||||
if report.OK {
|
||||
var out, discarded bytes.Buffer
|
||||
bound, cancel := context.WithTimeout(ctx, 60*time.Second)
|
||||
defer cancel()
|
||||
code := workspaceDocumentsCommand(bound, []string{"probe", "--directory", p.WorkspaceDirectory, "--bootstrap", p.BootstrapPath, "--json"}, &out, &discarded)
|
||||
var probes preflight.Report
|
||||
if code != 0 || json.Unmarshal(out.Bytes(), &probes) != nil || !probes.OK || len(probes.Checks) == 0 {
|
||||
return errors.New("current database/evidence probes failed")
|
||||
}
|
||||
}
|
||||
if !report.OK {
|
||||
return errors.New("current prerequisites failed")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
result, err := installapply.Run(ctx, installapply.Request{PlanPath: planPath, InstallationPath: installationPath}, runner, check)
|
||||
write(result)
|
||||
if err != nil {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -129,14 +129,7 @@ func installationPreflightCommand(ctx context.Context, installationPath string,
|
||||
}
|
||||
// Docker connection/trust and executable discovery remain host-owned. Compose parameters
|
||||
// are exclusively read from the authored env file, not inherited shell overrides.
|
||||
dockerEnvironment := []string{}
|
||||
for _, entry := range os.Environ() {
|
||||
key, _, _ := strings.Cut(entry, "=")
|
||||
if slices.Contains([]string{"PATH", "HOME", "USERPROFILE", "SystemRoot", "SYSTEMROOT", "TEMP", "TMP", "TMPDIR", "DOCKER_HOST", "DOCKER_CONTEXT", "DOCKER_CONFIG", "DOCKER_TLS_VERIFY", "DOCKER_CERT_PATH", "HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "no_proxy"}, key) {
|
||||
dockerEnvironment = append(dockerEnvironment, entry)
|
||||
}
|
||||
}
|
||||
runner := compose.NewRunnerWithEnvironment("", dockerEnvironment)
|
||||
runner := compose.NewRunnerWithEnvironment("", installationDockerEnvironment())
|
||||
if report.OK {
|
||||
report.Merge(preflight.CheckHost(ctx, runner, host, minimum))
|
||||
}
|
||||
@@ -166,6 +159,7 @@ func installationPreflightCommand(ctx context.Context, installationPath string,
|
||||
} else {
|
||||
preflight.AddRuntimeObligations(&report)
|
||||
plan := preflight.Plan{SchemaVersion: 1, ValidatorProtocol: preflight.Protocol, Validator: version.Current(), Installation: installation, Release: manifest, Platform: platform, WorkspaceDirectory: options["--workspaces"], WorkspaceRevision: revision, Inputs: inputs, AbsentInputs: absent, Report: report}
|
||||
plan.ManifestPath, plan.BootstrapPath = options["--release"], options["--bootstrap"]
|
||||
if err := preflight.WritePlan(options["--output"], &plan, unchanged); err != nil {
|
||||
report.Add("plan-output", "error", "output", "Choose a new filename in a private canonical directory; existing plans and key files are never overwritten.")
|
||||
}
|
||||
@@ -181,6 +175,17 @@ func installationPreflightCommand(ctx context.Context, installationPath string,
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
func installationDockerEnvironment() []string {
|
||||
environment := []string{}
|
||||
for _, entry := range os.Environ() {
|
||||
key, _, _ := strings.Cut(entry, "=")
|
||||
if slices.Contains([]string{"PATH", "HOME", "USERPROFILE", "SystemRoot", "SYSTEMROOT", "TEMP", "TMP", "TMPDIR", "DOCKER_HOST", "DOCKER_CONTEXT", "DOCKER_CONFIG", "DOCKER_TLS_VERIFY", "DOCKER_CERT_PATH", "HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "no_proxy"}, key) {
|
||||
environment = append(environment, entry)
|
||||
}
|
||||
}
|
||||
return environment
|
||||
}
|
||||
func writePreflight(stdout io.Writer, report preflight.Report, structured bool) {
|
||||
if structured {
|
||||
_ = json.NewEncoder(stdout).Encode(report)
|
||||
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/preflight"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/version"
|
||||
)
|
||||
|
||||
func TestNativeInstallationPlanBeforeContainersExist(t *testing.T) {
|
||||
@@ -80,6 +81,12 @@ func TestNativeInstallationPlanBeforeContainersExist(t *testing.T) {
|
||||
}
|
||||
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"))))
|
||||
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
|
||||
if code != 0 || json.Unmarshal([]byte(identityJSON), &identity) != nil {
|
||||
t.Fatal("compiled operator identity unavailable")
|
||||
}
|
||||
manifest.Version, manifest.Revision = identity.Version, identity.Commit
|
||||
platform := "linux/" + runtime.GOARCH
|
||||
services := map[string]map[string]string{}
|
||||
for _, role := range []string{"core", "frontend", "catalog", "qdrant", "embedding"} {
|
||||
@@ -89,7 +96,7 @@ func TestNativeInstallationPlanBeforeContainersExist(t *testing.T) {
|
||||
services[service] = map[string]string{"image": manifest.Images[role][platform]}
|
||||
}
|
||||
_ = os.Mkdir(filepath.Join(release, "deploy"), 0o700)
|
||||
for name, contents := range map[string]string{"compose.yaml": "services: {}\n", "deploy/compose.git-https.yaml": "services: {}\n"} {
|
||||
for name, contents := range map[string]string{"compose.yaml": "services: {}\n", "deploy/compose.local.yaml": "services: {}\n", "deploy/compose.git-https.yaml": "services: {}\n"} {
|
||||
write(filepath.Join(release, filepath.FromSlash(name)), []byte(contents))
|
||||
sum := sha256.Sum256([]byte(contents))
|
||||
manifest.Files[name] = hex.EncodeToString(sum[:])
|
||||
@@ -99,6 +106,11 @@ func TestNativeInstallationPlanBeforeContainersExist(t *testing.T) {
|
||||
write(manifestPath, manifestJSON)
|
||||
effective, _ := json.Marshal(map[string]any{"services": services})
|
||||
script := fmt.Sprintf("#!/bin/sh\ncase \"$1\" in\ninfo) printf '%%s\\n' '{\"OSType\":\"linux\",\"Architecture\":\"%s\",\"NCPU\":4,\"MemTotal\":17179869184}';;\ncompose) if [ \"$2\" = version ]; then printf '2.39.0\\n'; else printf '%%s\\n' '%s'; fi;;\nmanifest) printf '%%s\\n' '{\"Descriptor\":{\"digest\":\"sha256:%s\",\"platform\":{\"os\":\"linux\",\"architecture\":\"%s\"}}}';;\n*) exit 1;;\nesac\n", runtime.GOARCH, effective, strings.Repeat("a", 64), runtime.GOARCH)
|
||||
script = strings.Replace(script, "*) exit 1;;", `volume) if [ "$2" = inspect ]; then for last in "$@"; do :; done; printf '{"io.thothii.installation":"%s","io.thothii.volume":"%s"}\n' "${last%%_*}" "${last#*_}"; fi;;
|
||||
run) case "$*" in *'/etc/passwd') printf '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';; esac;;
|
||||
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)
|
||||
write(filepath.Join(root, "docker"), []byte(script))
|
||||
_ = os.Chmod(filepath.Join(root, "docker"), 0o700)
|
||||
planPath := filepath.Join(installation, "plan.json")
|
||||
@@ -124,6 +136,16 @@ func TestNativeInstallationPlanBeforeContainersExist(t *testing.T) {
|
||||
if err := preflight.VerifyPlanInputs(planPath); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for attempt := 0; attempt < 2; attempt++ {
|
||||
code, text := command("--installation", descriptor, "installation", "apply", "--plan", planPath)
|
||||
var result struct {
|
||||
PlatformReady bool `json:"platform_ready"`
|
||||
WorkspaceReady bool `json:"workspace_ready"`
|
||||
}
|
||||
if code != 0 || json.Unmarshal([]byte(text), &result) != nil || !result.PlatformReady || result.WorkspaceReady || strings.Contains(text, "PRIVATE_") {
|
||||
t.Fatalf("noninteractive apply attempt %d: %s", attempt, text)
|
||||
}
|
||||
}
|
||||
write(filepath.Join(installation, "secrets/database-password"), []byte("rotated-invalid"))
|
||||
if preflight.VerifyPlanInputs(planPath) == nil {
|
||||
t.Fatal("rotation did not invalidate plan")
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
@@ -53,6 +54,8 @@ Commands:
|
||||
Check host prerequisites and optionally the published release, without a stack.
|
||||
installation plan --workspaces PATH --release MANIFEST --output NEW_PLAN [--bootstrap PATH] [--json]
|
||||
Validate documents and live dependencies, then seal a private plan; requires --installation.
|
||||
installation apply --plan ABS_PLAN [--json]
|
||||
Recheck and apply the released plan without prompts; workspace readiness remains separate.
|
||||
installation migrate --output PATH --session-default PROVIDER/MODEL
|
||||
--embedding-id PROVIDER/MODEL --embedding-dimensions N
|
||||
Create a review-only schema-v2 candidate from all three legacy model sources.
|
||||
@@ -148,6 +151,11 @@ func run(ctx context.Context, args []string, stdout, stderr io.Writer) int {
|
||||
return versionCommand(commandArgs, stdout, stderr)
|
||||
}
|
||||
if command == "installation" {
|
||||
if len(commandArgs) > 0 && commandArgs[0] == "apply" {
|
||||
bound, stop := signal.NotifyContext(ctx, os.Interrupt)
|
||||
defer stop()
|
||||
return installationApplyCommand(bound, installationPath, commandArgs, stdout)
|
||||
}
|
||||
if len(commandArgs) > 0 && (commandArgs[0] == "preflight" || commandArgs[0] == "plan") {
|
||||
return installationPreflightCommand(ctx, installationPath, commandArgs, stdout)
|
||||
}
|
||||
|
||||
@@ -452,6 +452,9 @@ func (i Installation) ComposeFiles() []string {
|
||||
}
|
||||
files = append(files, i.Overrides...)
|
||||
files = append(files, i.ModelProjectionComposePath())
|
||||
if info, err := os.Lstat(i.LocalIdentityOverridePath()); err == nil && info.Mode().IsRegular() {
|
||||
files = append(files, i.LocalIdentityOverridePath())
|
||||
}
|
||||
if i.HasRuntimeAuthProjection() {
|
||||
files = append(files, i.runtimeAuthProjectionComposePath())
|
||||
}
|
||||
@@ -501,6 +504,11 @@ func (i Installation) CurrentImageOverridePath() string {
|
||||
return filepath.Join(i.ControlDirectory(), "current-image.yaml")
|
||||
}
|
||||
|
||||
// LocalIdentityOverridePath is generated only by document-first standalone apply.
|
||||
func (i Installation) LocalIdentityOverridePath() string {
|
||||
return filepath.Join(i.ControlDirectory(), "compose.local-identity.yaml")
|
||||
}
|
||||
|
||||
func (i Installation) UpdateStatePath() string {
|
||||
return filepath.Join(i.ControlDirectory(), "update-state.json")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
package installapply
|
||||
|
||||
import (
|
||||
"context"
|
||||
_ "embed"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/compose"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/config"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/preflight"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/safeio"
|
||||
)
|
||||
|
||||
// The original protected host files remain authoritative, including atomic auth updates.
|
||||
// Standalone services therefore run as the preparing operator, never as root. This does
|
||||
// not change the default image user or the server authentication projection protocol.
|
||||
func prepareIdentity(i config.Installation) error {
|
||||
uid, gid := os.Geteuid(), os.Getegid()
|
||||
if uid <= 0 || gid < 0 {
|
||||
return errors.New("standalone installation requires a non-root Unix operator")
|
||||
}
|
||||
services := map[string]any{}
|
||||
for _, service := range []string{"core", "catalog-migrate", "workspace-maintenance", "catalog-db"} {
|
||||
account := "core"
|
||||
if service == "catalog-db" {
|
||||
account = "catalog"
|
||||
}
|
||||
services[service] = map[string]any{
|
||||
"user": fmt.Sprintf("%d:%d", uid, gid),
|
||||
"volumes": []any{map[string]any{"type": "bind", "source": filepath.Join(i.ControlDirectory(), account+".passwd"), "target": "/etc/passwd", "read_only": true, "bind": map[string]any{"create_host_path": false}}},
|
||||
}
|
||||
}
|
||||
core := services["core"].(map[string]any)
|
||||
core["volumes"] = append(core["volumes"].([]any), map[string]any{"type": "volume", "source": "harness-pi", "target": "/app/harness/.pi"})
|
||||
services["catalog-db"].(map[string]any)["environment"] = map[string]string{"PGDATA": "/var/lib/postgresql/data/data"}
|
||||
volumes := map[string]any{}
|
||||
for _, v := range ownedVolumes {
|
||||
volumes[v.name] = map[string]any{"name": i.ProjectName() + "_" + v.name, "external": true}
|
||||
}
|
||||
b, err := json.MarshalIndent(map[string]any{"services": services, "volumes": volumes}, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return publishIdentical(i.LocalIdentityOverridePath(), b, 0o600)
|
||||
}
|
||||
|
||||
func publishIdentical(path string, b []byte, mode os.FileMode) error {
|
||||
if old, err := safeio.ReadCanonicalRegular(path, 4<<20); err == nil {
|
||||
if string(old) == string(b) {
|
||||
return nil
|
||||
}
|
||||
return errors.New("existing runtime identity differs; use the original operator and release")
|
||||
}
|
||||
return safeio.PublishCanonicalNewFile(path, b, mode)
|
||||
}
|
||||
|
||||
var ownedVolumes = []struct{ name, seed string }{
|
||||
{"settings", "/data/settings"}, {"pi-state", "/home/thoth/.pi"},
|
||||
{"harness-pi", "/app/harness/.pi"}, {"workspace-registry", "/data/workspace-registry"},
|
||||
{"workspace-secrets", "/data/workspace-secrets"}, {"sessions", "/data/sessions"},
|
||||
{"auth-state", "/data/auth"}, {"catalog-data", ""},
|
||||
}
|
||||
|
||||
//go:embed initialize-volumes.py
|
||||
var initializeVolumes string
|
||||
|
||||
func initializeIdentity(ctx context.Context, runner compose.Runner, i config.Installation, m preflight.Manifest, platform string) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 5*time.Minute)
|
||||
defer cancel()
|
||||
run := func(args ...string) (string, error) {
|
||||
result, err := runner.Run(ctx, args, nil)
|
||||
if err != nil || result.ExitCode != 0 {
|
||||
return "", errors.New("runtime identity initialization failed")
|
||||
}
|
||||
return result.Stdout, nil
|
||||
}
|
||||
oneShot := func(image, entrypoint string, tail ...string) ([]string, error) {
|
||||
name, err := compose.NewOneShotContainerName(i.ProjectName() + "-identity")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
args := []string{"run", "--rm", "--name", name, "--pull", "never", "--platform", platform, "--network", "none", "--read-only", "--user", "0:0", "--security-opt", "no-new-privileges", "--entrypoint", entrypoint}
|
||||
return append(append(args, image), tail...), nil
|
||||
}
|
||||
for _, account := range []struct{ role, user string }{{"core", "thoth"}, {"catalog", "postgres"}} {
|
||||
args, err := oneShot(m.Images[account.role][platform], "/bin/cat", "/etc/passwd")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
original, err := run(args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mapped, err := mapPasswd(original, account.user, os.Geteuid(), os.Getegid())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := publishIdentical(filepath.Join(i.ControlDirectory(), account.role+".passwd"), []byte(mapped), 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
args, err := oneShot(m.Images["core"][platform], "/opt/venv/bin/python", "-c", initializeVolumes, i.ProjectName(), strconv.Itoa(os.Geteuid()), strconv.Itoa(os.Getegid()))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Insert mounts before the image. The helper has only installation volumes, no host
|
||||
// secret binds, Docker socket, or network. Volume labels are checked before mounting.
|
||||
imageIndex := slices.Index(args, m.Images["core"][platform])
|
||||
mounts := []string{}
|
||||
seeds := map[string]string{}
|
||||
for _, volume := range ownedVolumes {
|
||||
name := i.ProjectName() + "_" + volume.name
|
||||
// Listing first distinguishes absence from an inspect/daemon failure.
|
||||
listed, err := run("volume", "ls", "--format", "{{.Name}}", "--filter", "name=^"+name+"$")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if strings.TrimSpace(listed) == "" {
|
||||
if _, err := run("volume", "create", "--label", "io.thothii.installation="+i.ProjectName(), "--label", "io.thothii.volume="+volume.name, name); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if strings.TrimSpace(listed) != name {
|
||||
return errors.New("unexpected volume identity")
|
||||
}
|
||||
inspected, err := run("volume", "inspect", "--format", "{{json .Labels}}", name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var labels map[string]string
|
||||
if json.Unmarshal([]byte(inspected), &labels) != nil || labels["io.thothii.installation"] != i.ProjectName() || labels["io.thothii.volume"] != volume.name {
|
||||
return errors.New("existing volume is not owned by this installation")
|
||||
}
|
||||
mounts = append(mounts, "--mount", "type=volume,src="+name+",dst=/bootstrap/"+volume.name+",volume-nocopy")
|
||||
seeds[volume.name] = volume.seed
|
||||
}
|
||||
payload, _ := json.Marshal(seeds)
|
||||
args = append(append(append([]string{}, args[:imageIndex]...), mounts...), args[imageIndex:]...)
|
||||
args = append(args, string(payload))
|
||||
_, err = run(args...)
|
||||
return err
|
||||
}
|
||||
|
||||
func mapPasswd(original, account string, uid, gid int) (string, error) {
|
||||
if uid <= 0 || gid < 0 {
|
||||
return "", errors.New("invalid runtime identity")
|
||||
}
|
||||
lines := strings.Split(strings.TrimSuffix(original, "\n"), "\n")
|
||||
found := false
|
||||
for n, line := range lines {
|
||||
fields := strings.Split(line, ":")
|
||||
if len(fields) != 7 {
|
||||
return "", errors.New("invalid image account database")
|
||||
}
|
||||
if fields[0] == account {
|
||||
if found {
|
||||
return "", errors.New("duplicate runtime account")
|
||||
}
|
||||
found = true
|
||||
fields[2], fields[3] = strconv.Itoa(uid), strconv.Itoa(gid)
|
||||
lines[n] = strings.Join(fields, ":")
|
||||
} else if fields[2] == strconv.Itoa(uid) {
|
||||
return "", errors.New("operator UID collides with an image account")
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return "", errors.New("image runtime account is missing")
|
||||
}
|
||||
return strings.Join(lines, "\n") + "\n", nil
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package installapply
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/compose"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/safeio"
|
||||
)
|
||||
|
||||
// Uses already-published images and Linux volume ownership even on Docker Desktop.
|
||||
// This proves runtime identity/PG init and retry; it is not OS installation acceptance.
|
||||
func TestPublishedImagesAcceptProtectedOperatorIdentity(t *testing.T) {
|
||||
if os.Getenv("THT_INSTALLATION_DOCKER_TEST") != "1" {
|
||||
t.Skip("set THT_INSTALLATION_DOCKER_TEST=1 with Docker and published images pulled")
|
||||
}
|
||||
_, plan := fixture(t)
|
||||
i := plan.Installation
|
||||
if err := safeio.EnsurePrivateDirectory(i.ProjectDirectory + "/.tht"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := safeio.EnsurePrivateDirectory(i.ControlDirectory()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := prepareIdentity(i); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
core := "docker.io/tylconsulting/thothii-core@sha256:7ac0b3362c93837c02d9f8d3153d3ab3441cc43594ee7786dafc845a69d5c956"
|
||||
catalog := "docker.io/library/postgres@sha256:45cd22f8d32e189d245403954882f88e7a8714301fda80dab6da90f1265b25a3"
|
||||
plan.Release.Images["core"][plan.Platform] = core
|
||||
plan.Release.Images["catalog"][plan.Platform] = catalog
|
||||
runner := compose.NewRunner("")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Minute)
|
||||
defer cancel()
|
||||
container := i.ProjectName() + "-pg-proof"
|
||||
t.Cleanup(func() {
|
||||
cleanup, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
defer cancel()
|
||||
_, _ = runner.Run(cleanup, []string{"rm", "-f", container}, nil)
|
||||
for _, volume := range ownedVolumes {
|
||||
_, _ = runner.Run(cleanup, []string{"volume", "rm", i.ProjectName() + "_" + volume.name}, nil)
|
||||
}
|
||||
})
|
||||
run := func(args ...string) string {
|
||||
t.Helper()
|
||||
result, err := runner.Run(ctx, args, nil)
|
||||
if err != nil || result.ExitCode != 0 {
|
||||
t.Fatalf("Docker proof failed: %v %s", err, result.Stderr)
|
||||
}
|
||||
return result.Stdout
|
||||
}
|
||||
if err := initializeIdentity(ctx, interruptedInitializer{runner}, i, plan.Release, plan.Platform); err == nil {
|
||||
t.Fatal("simulated interruption was ignored")
|
||||
}
|
||||
if err := initializeIdentity(ctx, runner, i, plan.Release, plan.Platform); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
user := fmt.Sprintf("%d:%d", os.Geteuid(), os.Getegid())
|
||||
// The password is created inside a Linux volume, so Desktop cannot mask UID/mode bugs.
|
||||
run("run", "--rm", "--pull", "never", "--platform", plan.Platform, "--network", "none", "--read-only", "--user", user,
|
||||
"--mount", "type=volume,src="+i.ProjectName()+"_auth-state,dst=/proof",
|
||||
"--mount", "type=volume,src="+i.ProjectName()+"_pi-state,dst=/home/thoth/.pi",
|
||||
"--mount", "type=volume,src="+i.ProjectName()+"_harness-pi,dst=/app/harness/.pi",
|
||||
"--mount", "type=bind,src="+i.ControlDirectory()+"/core.passwd,dst=/etc/passwd,readonly",
|
||||
"--entrypoint", "/usr/local/bin/node", core, "-e", `const fs=require('fs'),os=require('os'); if(os.userInfo().username!=='thoth')throw Error('identity'); fs.writeFileSync('/proof/password','test-only-password',{mode:0o600}); fs.writeFileSync('/home/thoth/.pi/agent/permission-proof','ok'); fs.writeFileSync('/app/harness/.pi/permission-proof','ok'); if(fs.statSync('/proof/password').uid!==Number(process.argv[1]))throw Error('owner');`, strconv.Itoa(os.Geteuid()))
|
||||
start := func() {
|
||||
run("run", "-d", "--name", container, "--pull", "never", "--platform", plan.Platform, "--network", "none", "--user", user,
|
||||
"--mount", "type=volume,src="+i.ProjectName()+"_catalog-data,dst=/var/lib/postgresql/data",
|
||||
"--mount", "type=volume,src="+i.ProjectName()+"_auth-state,dst=/proof,readonly",
|
||||
"--mount", "type=bind,src="+i.ControlDirectory()+"/catalog.passwd,dst=/etc/passwd,readonly",
|
||||
"-e", "PGDATA=/var/lib/postgresql/data/data", "-e", "POSTGRES_PASSWORD_FILE=/proof/password", catalog)
|
||||
deadline := time.Now().Add(45 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
value, err := runner.Run(ctx, []string{"exec", container, "pg_isready", "-h", "127.0.0.1", "-U", "postgres"}, nil)
|
||||
if err == nil && value.ExitCode == 0 {
|
||||
return
|
||||
}
|
||||
time.Sleep(250 * time.Millisecond)
|
||||
}
|
||||
t.Fatal("PostgreSQL did not become ready")
|
||||
}
|
||||
start()
|
||||
run("exec", container, "psql", "-U", "postgres", "-v", "ON_ERROR_STOP=1", "-c", "CREATE TABLE installation_proof(value integer); INSERT INTO installation_proof VALUES (47);")
|
||||
run("stop", "--time", "10", container)
|
||||
run("rm", container)
|
||||
if err := initializeIdentity(ctx, runner, i, plan.Release, plan.Platform); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
start()
|
||||
if result := run("exec", container, "psql", "-U", "postgres", "-Atqc", "SELECT value FROM installation_proof"); strings.TrimSpace(result) != "47" {
|
||||
t.Fatal("retry lost existing catalog data")
|
||||
}
|
||||
}
|
||||
|
||||
type interruptedInitializer struct{ compose.Runner }
|
||||
|
||||
func (r interruptedInitializer) Run(ctx context.Context, args []string, input io.Reader) (compose.Result, error) {
|
||||
args = append([]string{}, args...)
|
||||
for n, value := range args {
|
||||
if value == initializeVolumes {
|
||||
args[n] = strings.ReplaceAll(value, `save(marker, dict(identity, status="ready"))`, `os._exit(47)`)
|
||||
}
|
||||
}
|
||||
return r.Runner.Run(ctx, args, input)
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package installapply
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/compose"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/preflight"
|
||||
)
|
||||
|
||||
func TestIdentityPreservesAccountsAndRefusesCollisions(t *testing.T) {
|
||||
original := "root:x:0:0:root:/root:/bin/bash\nthoth:x:10001:10001::/home/thoth:/bin/bash\n"
|
||||
got, err := mapPasswd(original, "thoth", 1000, 1000)
|
||||
if err != nil || got != strings.Replace(original, "10001:10001", "1000:1000", 1) {
|
||||
t.Fatalf("mapped account: %q %v", got, err)
|
||||
}
|
||||
for _, broken := range []string{original + "other:x:1000:1000::/:/bin/false\n", strings.ReplaceAll(original, "thoth:", "missing:"), original + "thoth:x:10002:10002::/:/bin/false\n"} {
|
||||
if _, err := mapPasswd(broken, "thoth", 1000, 1000); err == nil {
|
||||
t.Fatal("ambiguous identity accepted")
|
||||
}
|
||||
}
|
||||
if _, err := mapPasswd(original, "thoth", 0, 0); err == nil {
|
||||
t.Fatal("root runtime accepted")
|
||||
}
|
||||
}
|
||||
|
||||
type foreignVolume struct{ dockerFixture }
|
||||
|
||||
func (r *foreignVolume) Run(ctx context.Context, args []string, input io.Reader) (compose.Result, error) {
|
||||
if len(args) > 1 && args[0] == "volume" && args[1] == "inspect" {
|
||||
return compose.Result{Stdout: `{"io.thothii.installation":"someone-else"}`}, nil
|
||||
}
|
||||
return r.dockerFixture.Run(ctx, args, input)
|
||||
}
|
||||
|
||||
func TestForeignVolumesStopBeforeOwnershipOrServiceChanges(t *testing.T) {
|
||||
path, plan := fixture(t)
|
||||
r := &foreignVolume{}
|
||||
result, err := Run(context.Background(), Request{path, plan.Installation.Path}, r, func(context.Context, preflight.Plan) error { return nil })
|
||||
if err == nil || result.Stage != "runtime-identity" {
|
||||
t.Fatalf("foreign volume: %+v %v", result, err)
|
||||
}
|
||||
for _, line := range flatten(r.calls) {
|
||||
if strings.Contains(line, " up ") || strings.Contains(line, " -c "+initializeVolumes) {
|
||||
t.Fatal("changed foreign volume or started service")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeIdentityIsDurableAcrossOperatorCommands(t *testing.T) {
|
||||
path, plan := fixture(t)
|
||||
_, err := Run(context.Background(), Request{path, plan.Installation.Path}, &dockerFixture{}, func(context.Context, preflight.Plan) error { return nil })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err := os.ReadFile(plan.Installation.LocalIdentityOverridePath())
|
||||
var override struct {
|
||||
Services map[string]struct {
|
||||
User string `json:"user"`
|
||||
} `json:"services"`
|
||||
}
|
||||
if err != nil || json.Unmarshal(b, &override) != nil || override.Services["core"].User == "0:0" || override.Services["core"].User == "" {
|
||||
t.Fatal("non-root runtime identity missing")
|
||||
}
|
||||
if !strings.Contains(strings.Join(plan.Installation.ComposeArgs("start"), " "), plan.Installation.LocalIdentityOverridePath()) {
|
||||
t.Fatal("lifecycle loses runtime identity")
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(plan.Installation.ControlDirectory(), "core.passwd"), []byte("modified"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = Run(context.Background(), Request{path, plan.Installation.Path}, &dockerFixture{}, func(context.Context, preflight.Plan) error { return nil })
|
||||
if err == nil {
|
||||
t.Fatal("modified identity accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
"""Seed only empty installation-owned volumes; resumed live data is never chowned."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sys
|
||||
|
||||
project, uid, gid, seeds = sys.argv[1:]
|
||||
uid, gid = int(uid), int(gid)
|
||||
assert uid > 0 and gid >= 0
|
||||
|
||||
def save(path, value):
|
||||
temporary = path.with_name(".thothii-initializing.tmp")
|
||||
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
|
||||
with os.fdopen(fd, "w") as stream:
|
||||
json.dump(value, stream)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, path)
|
||||
directory = os.open(path.parent, os.O_DIRECTORY)
|
||||
try:
|
||||
os.fsync(directory)
|
||||
finally:
|
||||
os.close(directory)
|
||||
|
||||
for name, source in json.loads(seeds).items():
|
||||
root = Path("/bootstrap") / name
|
||||
marker = root / ".thothii-volume.json"
|
||||
identity = {"project": project, "volume": name, "uid": uid, "gid": gid}
|
||||
if marker.exists():
|
||||
assert not marker.is_symlink()
|
||||
assert marker.stat().st_uid == 0 and marker.stat().st_nlink == 1
|
||||
state = json.loads(marker.read_text())
|
||||
assert all(state.get(k) == v for k, v in identity.items())
|
||||
assert state.get("status") in ("initializing", "ready")
|
||||
if state["status"] == "ready":
|
||||
current = root.stat()
|
||||
assert (current.st_uid, current.st_gid) == (uid, gid)
|
||||
continue
|
||||
else:
|
||||
# A leftover unpublished marker can result from interruption before rename.
|
||||
assert all(p.name == ".thothii-initializing.tmp" and p.is_file() and not p.is_symlink() for p in root.iterdir())
|
||||
save(marker, dict(identity, status="initializing"))
|
||||
# No application can have used an initializing volume: all volumes become ready
|
||||
# before catalog/services are started. Re-copying distributed files is repeatable.
|
||||
if source:
|
||||
shutil.copytree(source, root, dirs_exist_ok=True, symlinks=True)
|
||||
for parent, directories, files in os.walk(root, followlinks=False):
|
||||
for entry in directories + files:
|
||||
if Path(parent) == root and entry in (marker.name, ".thothii-initializing.tmp"):
|
||||
continue
|
||||
os.chown(Path(parent) / entry, uid, gid, follow_symlinks=False)
|
||||
os.chown(root, uid, gid)
|
||||
os.chmod(root, 0o700)
|
||||
save(marker, dict(identity, status="ready"))
|
||||
@@ -0,0 +1,257 @@
|
||||
// Package installapply applies a sealed installation plan without interactive input.
|
||||
package installapply
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"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/modelprojection"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/preflight"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/safeio"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/service"
|
||||
)
|
||||
|
||||
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"`
|
||||
}
|
||||
type journal struct {
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
Installation string `json:"installation"`
|
||||
ReleaseRevision string `json:"release_revision"`
|
||||
PlanSeal string `json:"plan_seal"`
|
||||
Stage string `json:"stage"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
// Check must repeat document validation and live prerequisite probes at the public CLI boundary.
|
||||
// It is mandatory; historical success in the plan never authorizes skipping current checks.
|
||||
type Check func(context.Context, preflight.Plan) error
|
||||
|
||||
func Run(ctx context.Context, request Request, runner compose.Runner, check Check) (result Result, err error) {
|
||||
result = Result{SchemaVersion: 1, Stage: "plan", Action: "Produce a current plan from complete prepared documents."}
|
||||
fail := func(stage, action string) (Result, error) {
|
||||
result.Stage = stage
|
||||
result.Action = action
|
||||
return result, errors.New(action)
|
||||
}
|
||||
plan, err := preflight.ReadExecutionPlan(request.PlanPath)
|
||||
if err != nil || plan.Installation.Path != request.InstallationPath || plan.ManifestPath == "" || plan.BootstrapPath == "" || runner == nil || check == nil {
|
||||
return fail("plan", "Use a matching protected execution plan; older plans must be regenerated.")
|
||||
}
|
||||
installation, err := config.LoadPrepared(request.InstallationPath)
|
||||
if err != nil || !reflect.DeepEqual(installation, plan.Installation) || installation.Profile != "local" {
|
||||
return fail("plan", "Correct and validate the local installation documents before execution.")
|
||||
}
|
||||
manifest, err := preflight.LoadManifest(plan.ManifestPath)
|
||||
if err != nil || !reflect.DeepEqual(manifest, plan.Release) {
|
||||
return fail("release", "Restore the exact verified release bundle and generate a new plan if its identity changed.")
|
||||
}
|
||||
if err := safeio.EnsurePrivateDirectory(filepath.Join(installation.ProjectDirectory, ".tht")); err != nil {
|
||||
return fail("lock", "The installation control directory must be private and canonical.")
|
||||
}
|
||||
if err := safeio.EnsurePrivateDirectory(installation.ControlDirectory()); err != nil {
|
||||
return fail("lock", "The installation control directory must be private and canonical.")
|
||||
}
|
||||
lock, err := lifecycle.Acquire(installation)
|
||||
if err != nil {
|
||||
return fail("lock", "Another lifecycle operation owns the installation lock; wait for it to finish. Inspect a stale owner after a terminated process before explicitly removing its lock.")
|
||||
}
|
||||
defer func() {
|
||||
if releaseErr := lock.Release(); releaseErr != nil {
|
||||
result.PlatformReady = false
|
||||
result.Stage = "lock"
|
||||
result.Action = "Installation lock ownership changed; inspect the private control directory."
|
||||
err = errors.New(result.Action)
|
||||
}
|
||||
}()
|
||||
if err := check(ctx, plan); err != nil {
|
||||
return fail("validation", "Current document or prerequisite checks failed; correct the documents and repeat planning. No platform operation was started.")
|
||||
}
|
||||
if _, err := preflight.ReadExecutionPlan(request.PlanPath); err != nil {
|
||||
return fail("validation", "Inputs changed during checks; repeat planning before execution.")
|
||||
}
|
||||
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 {
|
||||
data, readErr := safeio.ReadCanonicalPrivateRegular(result.Journal, 16<<10)
|
||||
var previous journal
|
||||
if readErr != nil || json.Unmarshal(data, &previous) != nil || previous.SchemaVersion != 1 || previous.Installation != installation.Path || previous.ReleaseRevision != plan.Release.Revision {
|
||||
return fail("journal", "The existing installation journal is invalid or belongs to another release; this command is not a product upgrade.")
|
||||
}
|
||||
} else if !os.IsNotExist(err) {
|
||||
return fail("journal", "Cannot safely read the installation journal.")
|
||||
}
|
||||
persist := func() error {
|
||||
data, _ := json.MarshalIndent(state, "", " ")
|
||||
data = append(data, '\n')
|
||||
if _, err := os.Lstat(result.Journal); os.IsNotExist(err) {
|
||||
return safeio.PublishCanonicalNewFile(result.Journal, data, 0o600)
|
||||
}
|
||||
return safeio.ReplaceCanonicalRegular(result.Journal, data, 0o600)
|
||||
}
|
||||
operation := func(stage string, fn func() error) error {
|
||||
result.Stage = stage
|
||||
state.Stage = stage
|
||||
state.Status = "running"
|
||||
if err := persist(); err != nil {
|
||||
return errors.New("Cannot persist the private installation journal.")
|
||||
}
|
||||
if _, err := preflight.ReadExecutionPlan(request.PlanPath); err != nil {
|
||||
state.Status = "failed"
|
||||
_ = persist()
|
||||
return errors.New("Prepared inputs changed; correct the documents and produce a new plan.")
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
state.Status = "interrupted"
|
||||
_ = persist()
|
||||
return errors.New("Execution interrupted; repeat the same command to reconcile the existing platform.")
|
||||
}
|
||||
if err := fn(); err != nil {
|
||||
state.Status = "failed"
|
||||
if ctx.Err() != nil {
|
||||
state.Status = "interrupted"
|
||||
}
|
||||
if saveErr := persist(); saveErr != nil {
|
||||
return errors.New("Operation stopped and the private journal could not be updated.")
|
||||
}
|
||||
return fmt.Errorf("Stage %s failed; correct its prerequisites and repeat apply. No source build or volume reset was attempted.", stage)
|
||||
}
|
||||
state.Status = "complete"
|
||||
return persist()
|
||||
}
|
||||
docker := func(timeout time.Duration, command ...string) error {
|
||||
bound, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
value, err := runner.Run(bound, installation.ComposeArgs(command...), nil)
|
||||
if err != nil || value.ExitCode != 0 {
|
||||
return errors.New("Docker operation failed")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
stages := []struct {
|
||||
name string
|
||||
run func() error
|
||||
}{
|
||||
{"assets", func() error { return installAssets(installation, plan) }},
|
||||
{"configuration", func() error {
|
||||
if err := prepareIdentity(installation); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := modelprojection.Generate(installation); err != nil {
|
||||
return err
|
||||
}
|
||||
if !preflight.CheckInstalledCompose(ctx, runner, installation, plan.Release, plan.Platform).OK {
|
||||
return errors.New("Effective runtime configuration differs from the release")
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"pull", func() error {
|
||||
return docker(30*time.Minute, "--profile", "catalog-maintenance", "--profile", "workspace-maintenance", "pull", "--policy", "always")
|
||||
}},
|
||||
{"runtime-identity", func() error {
|
||||
return initializeIdentity(ctx, runner, installation, plan.Release, plan.Platform)
|
||||
}},
|
||||
{"catalog", func() error {
|
||||
return docker(5*time.Minute, "up", "-d", "--no-build", "--pull", "never", "--wait", "--wait-timeout", "240", "catalog-db")
|
||||
}},
|
||||
{"migrations", func() error {
|
||||
name, err := compose.NewOneShotContainerName(installation.ProjectName() + "-migrate")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return docker(5*time.Minute, "run", "--rm", "-T", "--no-deps", "--pull", "never", "--name", name, "catalog-migrate")
|
||||
}},
|
||||
{"services", func() error {
|
||||
return docker(30*time.Minute, "up", "-d", "--no-build", "--pull", "never", "--wait", "--wait-timeout", "1500", "core", "frontend", "qdrant", "embedding", "embedding-model-init")
|
||||
}},
|
||||
{"health", func() error {
|
||||
bound, cancel := context.WithTimeout(ctx, time.Minute)
|
||||
defer cancel()
|
||||
value, err := runner.Run(bound, installation.ComposeArgs("ps", "--all", "--format", "json"), nil)
|
||||
if err != nil || value.ExitCode != 0 {
|
||||
return errors.New("Cannot inspect services")
|
||||
}
|
||||
if err := service.Healthy(value.Stdout); err != nil {
|
||||
return err
|
||||
}
|
||||
return docker(time.Minute, "exec", "-T", "core", "node", "--input-type=module", "-e", runtimeCheck)
|
||||
}},
|
||||
}
|
||||
// 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.
|
||||
for _, stage := range stages {
|
||||
if err := operation(stage.name, stage.run); err != nil {
|
||||
return fail(stage.name, err.Error())
|
||||
}
|
||||
}
|
||||
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."
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func installAssets(installation config.Installation, plan preflight.Plan) error {
|
||||
names := make([]string, 0, len(plan.Release.Files))
|
||||
for name := range plan.Release.Files {
|
||||
names = append(names, name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
for _, name := range names {
|
||||
source := filepath.Join(filepath.Dir(plan.ManifestPath), filepath.FromSlash(name))
|
||||
target := filepath.Join(installation.ProjectDirectory, filepath.FromSlash(name))
|
||||
data, err := safeio.ReadCanonicalRegular(source, 32<<20)
|
||||
if err != nil || fmt.Sprintf("%x", sha256.Sum256(data)) != plan.Release.Files[name] {
|
||||
return errors.New("Release asset changed")
|
||||
}
|
||||
if existing, err := safeio.ReadCanonicalRegular(target, 32<<20); err == nil {
|
||||
if fmt.Sprintf("%x", sha256.Sum256(existing)) != plan.Release.Files[name] {
|
||||
return errors.New("Existing release asset differs")
|
||||
}
|
||||
continue
|
||||
}
|
||||
if _, err := os.Lstat(target); !os.IsNotExist(err) {
|
||||
return errors.New("Existing release target is unsafe")
|
||||
}
|
||||
relative, _ := filepath.Rel(installation.ProjectDirectory, filepath.Dir(target))
|
||||
parent := installation.ProjectDirectory
|
||||
if relative != "." {
|
||||
for _, part := range strings.Split(relative, string(filepath.Separator)) {
|
||||
parent = filepath.Join(parent, part)
|
||||
if err := safeio.EnsurePrivateDirectory(parent); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := safeio.PublishCanonicalNewFile(target, data, 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
const runtimeCheck = `
|
||||
const base='http://127.0.0.1:8787';
|
||||
const health=await fetch(base+'/health',{signal:AbortSignal.timeout(10000)});
|
||||
const auth=await fetch(base+'/auth/config',{signal:AbortSignal.timeout(10000)});
|
||||
const protectedRoute=await fetch(base+'/workspaces',{signal:AbortSignal.timeout(10000)});
|
||||
if(!health.ok||!auth.ok||(await auth.json()).mode!=='local'||protectedRoute.status!==401)process.exit(1);
|
||||
console.log(JSON.stringify({ok:true}));
|
||||
`
|
||||
@@ -0,0 +1,240 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,16 @@ func CheckCompose(ctx context.Context, runner Runner, installation config.Instal
|
||||
args = append(args, "-f", path)
|
||||
}
|
||||
args = append(args, "config", "--format", "json")
|
||||
return checkResolvedCompose(ctx, runner, args, m, platform)
|
||||
}
|
||||
|
||||
// CheckInstalledCompose includes generated projections and any durable image override.
|
||||
func CheckInstalledCompose(ctx context.Context, runner Runner, installation config.Installation, m Manifest, platform string) Report {
|
||||
return checkResolvedCompose(ctx, runner, installation.ComposeArgs("config", "--format", "json"), m, platform)
|
||||
}
|
||||
|
||||
func checkResolvedCompose(ctx context.Context, runner Runner, args []string, m Manifest, platform string) Report {
|
||||
r := NewReport()
|
||||
result, err := docker(ctx, runner, args...)
|
||||
var effective struct {
|
||||
Services map[string]struct {
|
||||
|
||||
@@ -28,6 +28,8 @@ type Plan struct {
|
||||
Platform string `json:"platform"`
|
||||
WorkspaceDirectory string `json:"workspace_directory"`
|
||||
WorkspaceRevision string `json:"workspace_revision"`
|
||||
ManifestPath string `json:"manifest_path,omitempty"`
|
||||
BootstrapPath string `json:"bootstrap_path,omitempty"`
|
||||
Inputs []string `json:"inputs"`
|
||||
AbsentInputs []string `json:"absent_inputs"`
|
||||
InputSeal string `json:"input_seal"`
|
||||
@@ -62,10 +64,16 @@ func CaptureInputs(paths []string, workspace string, absent ...string) (func() b
|
||||
|
||||
// A separate owner-only random key prevents public/offline guessing of low-entropy secrets.
|
||||
// Live prerequisites must still be rechecked immediately before any execution or resumption.
|
||||
func seal(plan Plan, key []byte) (string, error) {
|
||||
func seal(plan Plan, key []byte, materialized ...bool) (string, error) {
|
||||
for _, path := range plan.AbsentInputs {
|
||||
if _, err := os.Lstat(path); !errors.Is(err, os.ErrNotExist) {
|
||||
return "", invalidPlan()
|
||||
name := "deploy/" + filepath.Base(path)
|
||||
allowed := len(materialized) > 0 && materialized[0] && (name == "deploy/compose.git-https.yaml" || name == "deploy/compose.git-ssh.yaml") && path == filepath.Join(plan.Installation.ProjectDirectory, filepath.FromSlash(name))
|
||||
data, readErr := safeio.ReadCanonicalRegular(path, 32<<20)
|
||||
sum := sha256.Sum256(data)
|
||||
if !allowed || readErr != nil || hex.EncodeToString(sum[:]) != plan.Release.Files[name] {
|
||||
return "", invalidPlan()
|
||||
}
|
||||
}
|
||||
}
|
||||
mac := hmac.New(sha256.New, key)
|
||||
@@ -138,35 +146,44 @@ func WritePlan(path string, plan *Plan, guards ...func() bool) error {
|
||||
return nil
|
||||
}
|
||||
func VerifyPlanInputs(path string) error {
|
||||
_, err := readPlan(path, false)
|
||||
return err
|
||||
}
|
||||
|
||||
// ReadExecutionPlan permits only exact release-owned overlays installed by a prior attempt.
|
||||
// The authored documents, credentials, bundle and private seal must otherwise remain unchanged.
|
||||
func ReadExecutionPlan(path string) (Plan, error) { return readPlan(path, true) }
|
||||
|
||||
func readPlan(path string, materialized bool) (Plan, error) {
|
||||
data, err := safeio.ReadCanonicalPrivateRegular(path, 4<<20)
|
||||
if err != nil {
|
||||
return invalidPlan()
|
||||
return Plan{}, invalidPlan()
|
||||
}
|
||||
key, err := safeio.ReadCanonicalPrivateRegular(path+".key", 32)
|
||||
if err != nil || len(key) != 32 {
|
||||
return invalidPlan()
|
||||
return Plan{}, invalidPlan()
|
||||
}
|
||||
var plan Plan
|
||||
if json.Unmarshal(data, &plan) != nil || plan.SchemaVersion != 1 || plan.ValidatorProtocol != Protocol || !plan.Report.OK || len(plan.Inputs) == 0 || len(plan.Inputs) > 10000 {
|
||||
return invalidPlan()
|
||||
return Plan{}, invalidPlan()
|
||||
}
|
||||
actual, err := seal(plan, key)
|
||||
actual, err := seal(plan, key, materialized)
|
||||
if err != nil || !hmac.Equal([]byte(actual), []byte(plan.InputSeal)) {
|
||||
return invalidPlan()
|
||||
return Plan{}, invalidPlan()
|
||||
}
|
||||
// Detect added or removed workspace files as well as changes to known file bytes.
|
||||
if plan.WorkspaceDirectory != "" {
|
||||
files, err := treeFiles(plan.WorkspaceDirectory, true)
|
||||
if err != nil {
|
||||
return invalidPlan()
|
||||
return Plan{}, invalidPlan()
|
||||
}
|
||||
for _, file := range files {
|
||||
if !slices.Contains(plan.Inputs, file) {
|
||||
return invalidPlan()
|
||||
return Plan{}, invalidPlan()
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return plan, nil
|
||||
}
|
||||
func treeFiles(root string, skipGit bool) ([]string, error) {
|
||||
paths := []string{}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package preflight
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/config"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/safeio"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -8,6 +11,32 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestExecutionPlanAcceptsOnlyExactReleaseOwnedMaterialization(t *testing.T) {
|
||||
root, _ := filepath.EvalSymlinks(t.TempDir())
|
||||
_ = os.Chmod(root, 0o700)
|
||||
_ = os.Mkdir(filepath.Join(root, "deploy"), 0o700)
|
||||
input := filepath.Join(root, "input")
|
||||
_ = os.WriteFile(input, []byte("prepared"), 0o600)
|
||||
overlay := filepath.Join(root, "deploy", "compose.git-https.yaml")
|
||||
data := []byte("services: {}\n")
|
||||
plan := Plan{SchemaVersion: 1, ValidatorProtocol: Protocol, Installation: config.Installation{ProjectDirectory: root}, Inputs: []string{input}, AbsentInputs: []string{overlay}, Report: NewReport(), Release: Manifest{Files: map[string]string{"deploy/compose.git-https.yaml": fmt.Sprintf("%x", sha256.Sum256(data))}}}
|
||||
path := filepath.Join(root, "plan.json")
|
||||
if err := WritePlan(path, &plan); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = os.WriteFile(overlay, data, 0o600)
|
||||
if _, err := ReadExecutionPlan(path); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if VerifyPlanInputs(path) == nil {
|
||||
t.Fatal("ordinary validation must still detect new files")
|
||||
}
|
||||
_ = os.WriteFile(overlay, []byte("changed"), 0o600)
|
||||
if _, err := ReadExecutionPlan(path); err == nil {
|
||||
t.Fatal("modified materialization accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlanBindsInputsAndDetectsCredentialRotationWithoutPublicSecretHashes(t *testing.T) {
|
||||
root, _ := filepath.EvalSymlinks(t.TempDir())
|
||||
if err := safeio.ProtectPrivateDirectory(root); err != nil {
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package safeio
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// PublishCanonicalNewFile durably publishes complete bytes without replacing an existing
|
||||
// target. A crash before publication can leave a private temporary file, never a partial target.
|
||||
func PublishCanonicalNewFile(path string, contents []byte, mode os.FileMode) error {
|
||||
if ValidateCanonicalPath(path) != nil || ValidatePrivateDirectory(filepath.Dir(path)) != nil || (mode != 0o600 && mode != 0o644) {
|
||||
return ErrUnsafeFile
|
||||
}
|
||||
return publishCanonicalNewFile(path, contents, mode)
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package safeio
|
||||
|
||||
import "golang.org/x/sys/unix"
|
||||
|
||||
func publishNoReplace(directory int, source, target string) error {
|
||||
return unix.RenameatxNp(directory, source, directory, target, unix.RENAME_EXCL)
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
//go:build linux || darwin
|
||||
|
||||
package safeio
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
func TestPublicationWriteFailureLeavesNoTarget(t *testing.T) {
|
||||
if path := os.Getenv("THT_SAFEIO_WRITE_FAILURE_PATH"); path != "" {
|
||||
signal.Ignore(syscall.SIGXFSZ)
|
||||
if err := unix.Setrlimit(unix.RLIMIT_FSIZE, &unix.Rlimit{Cur: 1, Max: 1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if PublishCanonicalNewFile(path, bytes.Repeat([]byte("x"), 4096), 0o600) == nil {
|
||||
t.Fatal("short write published")
|
||||
}
|
||||
if _, err := os.Lstat(path); !os.IsNotExist(err) {
|
||||
t.Fatal("failed write exposed target")
|
||||
}
|
||||
return
|
||||
}
|
||||
root, _ := filepath.EvalSymlinks(t.TempDir())
|
||||
if err := os.Chmod(root, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cmd := exec.Command(os.Args[0], "-test.run=^TestPublicationWriteFailureLeavesNoTarget$")
|
||||
cmd.Env = append(os.Environ(), "THT_SAFEIO_WRITE_FAILURE_PATH="+filepath.Join(root, "asset"))
|
||||
if output, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("write fault proof: %v %s", err, output)
|
||||
}
|
||||
entries, _ := os.ReadDir(root)
|
||||
if len(entries) != 0 {
|
||||
t.Fatal("failed write leaked temporary file")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package safeio
|
||||
|
||||
import "golang.org/x/sys/unix"
|
||||
|
||||
func publishNoReplace(directory int, source, target string) error {
|
||||
return unix.Renameat2(directory, source, directory, target, unix.RENAME_NOREPLACE)
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
//go:build !linux && !darwin && !windows
|
||||
|
||||
package safeio
|
||||
|
||||
import "os"
|
||||
|
||||
func publishCanonicalNewFile(string, []byte, os.FileMode) error { return ErrUnsafeFile }
|
||||
@@ -0,0 +1,66 @@
|
||||
package safeio
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPublishNewFileExposesOnlyCompleteWinner(t *testing.T) {
|
||||
root, err := filepath.EvalSymlinks(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Chmod(root, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := filepath.Join(root, "asset")
|
||||
a, b := bytes.Repeat([]byte("a"), 2<<20), bytes.Repeat([]byte("b"), 2<<20)
|
||||
start := make(chan struct{})
|
||||
results := make(chan error, 2)
|
||||
var writers sync.WaitGroup
|
||||
for _, value := range [][]byte{a, b} {
|
||||
writers.Add(1)
|
||||
go func(value []byte) {
|
||||
defer writers.Done()
|
||||
<-start
|
||||
results <- PublishCanonicalNewFile(path, value, 0o600)
|
||||
}(value)
|
||||
}
|
||||
done := make(chan struct{})
|
||||
go func() { writers.Wait(); close(done) }()
|
||||
close(start)
|
||||
for {
|
||||
contents, err := os.ReadFile(path)
|
||||
if err == nil && !bytes.Equal(contents, a) && !bytes.Equal(contents, b) {
|
||||
t.Fatal("partial publication observed")
|
||||
}
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case <-done:
|
||||
goto finished
|
||||
default:
|
||||
}
|
||||
}
|
||||
finished:
|
||||
first, second := <-results, <-results
|
||||
if (first == nil) == (second == nil) {
|
||||
t.Fatal("exactly one writer must publish")
|
||||
}
|
||||
before, _ := os.ReadFile(path)
|
||||
if PublishCanonicalNewFile(path, []byte("replacement"), 0o600) == nil {
|
||||
t.Fatal("existing publication overwritten")
|
||||
}
|
||||
after, _ := os.ReadFile(path)
|
||||
if !bytes.Equal(before, after) {
|
||||
t.Fatal("failed publication changed target")
|
||||
}
|
||||
entries, _ := os.ReadDir(root)
|
||||
if len(entries) != 1 {
|
||||
t.Fatal("temporary files leaked")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
//go:build linux || darwin
|
||||
|
||||
package safeio
|
||||
|
||||
import (
|
||||
"golang.org/x/sys/unix"
|
||||
"os"
|
||||
)
|
||||
|
||||
func publishCanonicalNewFile(path string, contents []byte, mode os.FileMode) error {
|
||||
directory, target, err := openCanonicalParentDirectory(path)
|
||||
if err != nil {
|
||||
return ErrUnsafeFile
|
||||
}
|
||||
defer unix.Close(directory)
|
||||
temporary, err := writePrivateTemporaryAt(directory, contents)
|
||||
if err != nil {
|
||||
return ErrUnsafeFile
|
||||
}
|
||||
defer func() {
|
||||
if temporary != "" {
|
||||
_ = unix.Unlinkat(directory, temporary, 0)
|
||||
}
|
||||
}()
|
||||
fd, err := unix.Openat(directory, temporary, unix.O_RDONLY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0)
|
||||
if err != nil {
|
||||
return ErrUnsafeFile
|
||||
}
|
||||
err = unix.Fchmod(fd, uint32(mode))
|
||||
if err == nil {
|
||||
err = unix.Fsync(fd)
|
||||
}
|
||||
_ = unix.Close(fd)
|
||||
if err != nil {
|
||||
return ErrUnsafeFile
|
||||
}
|
||||
if err := publishNoReplace(directory, temporary, target); err != nil {
|
||||
return ErrUnsafeFile
|
||||
}
|
||||
temporary = ""
|
||||
if unix.Fsync(directory) != nil {
|
||||
return ErrUnsafeFile
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package safeio
|
||||
|
||||
import (
|
||||
"golang.org/x/sys/windows"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
func publishCanonicalNewFile(path string, contents []byte, mode os.FileMode) error {
|
||||
parents, target, err := openCanonicalWindowsParent(path)
|
||||
if err != nil {
|
||||
return ErrUnsafeFile
|
||||
}
|
||||
defer parents.Close()
|
||||
if len(parents.handles) == 0 || validateOwnerOnlyDACL(parents.handles[len(parents.handles)-1]) != nil {
|
||||
return ErrUnsafeFile
|
||||
}
|
||||
temporary, err := writePrivateTemporary(parents.directory, contents)
|
||||
if err != nil {
|
||||
return ErrUnsafeFile
|
||||
}
|
||||
defer os.Remove(temporary)
|
||||
from, err := windows.UTF16PtrFromString(temporary)
|
||||
if err != nil {
|
||||
return ErrUnsafeFile
|
||||
}
|
||||
to, err := windows.UTF16PtrFromString(filepath.Join(parents.directory, target))
|
||||
if err != nil {
|
||||
return ErrUnsafeFile
|
||||
}
|
||||
if windows.MoveFileEx(from, to, windows.MOVEFILE_WRITE_THROUGH) != nil {
|
||||
return ErrUnsafeFile
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -116,7 +116,8 @@ func writePrivateTemporaryAt(directory int, contents []byte) (string, error) {
|
||||
unix.Close(descriptor)
|
||||
return "", ErrUnsafeFile
|
||||
}
|
||||
if err := file.Chmod(0o600); err == nil {
|
||||
err = file.Chmod(0o600)
|
||||
if err == nil {
|
||||
var written int
|
||||
written, err = file.Write(contents)
|
||||
if err == nil && written != len(contents) {
|
||||
|
||||
Reference in New Issue
Block a user