Files
ThothII/tools/tht/internal/installapply/identity.go
T

178 lines
6.8 KiB
Go

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
}