Track latest stage attempt diagnostics
This commit is contained in:
199
internal/fileops/attempt_views.go
Normal file
199
internal/fileops/attempt_views.go
Normal file
@@ -0,0 +1,199 @@
|
||||
package fileops
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/pathsafe"
|
||||
)
|
||||
|
||||
// AttemptViews records previous managed targets so a stage that self-skips can
|
||||
// restore its navigation views without touching unrelated workspace content.
|
||||
type AttemptViews struct {
|
||||
root, runID, name string
|
||||
previous map[string]*string
|
||||
}
|
||||
|
||||
// EnsureWorkspaceDirectoryUnderRoot creates real directories beneath an
|
||||
// existing root and rejects symlink components instead of following them.
|
||||
func EnsureWorkspaceDirectoryUnderRoot(rootPath, relative string) error {
|
||||
if _, err := pathsafe.NormalizeRelativeDestination(relative); err != nil {
|
||||
return err
|
||||
}
|
||||
root, err := os.OpenRoot(rootPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer root.Close()
|
||||
return ensureAttemptDirectory(root, relative)
|
||||
}
|
||||
|
||||
func ensureAttemptDirectory(root *os.Root, relative string) error {
|
||||
current := ""
|
||||
for _, component := range strings.Split(filepath.ToSlash(relative), "/") {
|
||||
if component == "" || component == "." || component == ".." {
|
||||
return fmt.Errorf("invalid directory component %q", component)
|
||||
}
|
||||
current = filepath.Join(current, component)
|
||||
info, err := root.Lstat(current)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
if err := root.Mkdir(current, WorkspaceDirectoryMode.Perm()); err != nil && !errors.Is(err, os.ErrExist) {
|
||||
return err
|
||||
}
|
||||
info, err = root.Lstat(current)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
|
||||
return fmt.Errorf("workspace directory %q is not a real directory", current)
|
||||
}
|
||||
if err := root.Chmod(current, WorkspaceDirectoryMode); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// BeginAttemptViews creates actual diagnostics directories and atomically
|
||||
// advances each managed relative link. It accepts no arbitrary link targets.
|
||||
func BeginAttemptViews(sessionRoot, runID, name string) (*AttemptViews, error) {
|
||||
if err := pathsafe.ValidateOpaqueSegment(runID); err != nil {
|
||||
return nil, fmt.Errorf("run identity: %w", err)
|
||||
}
|
||||
if runID == ".preflight" || runID == ".validation" {
|
||||
return nil, fmt.Errorf("run identity %q is reserved for probes", runID)
|
||||
}
|
||||
if err := pathsafe.ValidateOpaqueSegment(name); err != nil {
|
||||
return nil, fmt.Errorf("diagnostic name: %w", err)
|
||||
}
|
||||
root, err := os.OpenRoot(sessionRoot)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer root.Close()
|
||||
for _, relative := range []string{filepath.Join("runs", runID, name, "logs"), filepath.Join("runs", runID, name, "debug"), "logs", "debug"} {
|
||||
if err := ensureAttemptDirectory(root, relative); err != nil {
|
||||
return nil, fmt.Errorf("prepare attempt directory %q: %w", relative, err)
|
||||
}
|
||||
}
|
||||
views := &AttemptViews{root: sessionRoot, runID: runID, name: name, previous: map[string]*string{}}
|
||||
for _, category := range []string{"logs", "debug"} {
|
||||
parent, err := root.OpenRoot(category)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
previous, err := existingManagedView(parent, name, category)
|
||||
_ = parent.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
views.previous[category] = previous
|
||||
}
|
||||
var updated []string
|
||||
for _, category := range []string{"logs", "debug"} {
|
||||
parent, err := root.OpenRoot(category)
|
||||
if err != nil {
|
||||
return nil, errors.Join(err, views.revertCategories(updated))
|
||||
}
|
||||
target := attemptTarget(runID, name, category)
|
||||
err = replaceManagedView(parent, name, category, target)
|
||||
_ = parent.Close()
|
||||
if err != nil {
|
||||
return nil, errors.Join(err, views.revertCategories(updated))
|
||||
}
|
||||
updated = append(updated, category)
|
||||
}
|
||||
return views, nil
|
||||
}
|
||||
|
||||
func attemptTarget(runID, name, category string) string {
|
||||
return "../runs/" + runID + "/" + name + "/" + category
|
||||
}
|
||||
|
||||
func existingManagedView(parent *os.Root, name, category string) (*string, error) {
|
||||
info, err := parent.Lstat(name)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if info.Mode()&os.ModeSymlink == 0 {
|
||||
return nil, fmt.Errorf("managed %s view %q conflicts with existing content", category, name)
|
||||
}
|
||||
target, err := parent.Readlink(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
parts := strings.Split(target, "/")
|
||||
if len(parts) != 5 || parts[0] != ".." || parts[1] != "runs" || parts[3] != name || parts[4] != category || parts[2] == ".preflight" || parts[2] == ".validation" || pathsafe.ValidateOpaqueSegment(parts[2]) != nil {
|
||||
return nil, fmt.Errorf("managed %s view %q has an unexpected target %q", category, name, target)
|
||||
}
|
||||
return &target, nil
|
||||
}
|
||||
|
||||
func replaceManagedView(parent *os.Root, name, category, target string) error {
|
||||
if _, err := existingManagedView(parent, name, category); err != nil {
|
||||
return err
|
||||
}
|
||||
var random [16]byte
|
||||
if _, err := rand.Read(random[:]); err != nil {
|
||||
return err
|
||||
}
|
||||
temporary := "." + name + "." + hex.EncodeToString(random[:]) + ".link"
|
||||
if err := parent.Symlink(target, temporary); err != nil {
|
||||
return fmt.Errorf("create managed %s view: %w", category, err)
|
||||
}
|
||||
defer parent.Remove(temporary)
|
||||
if _, err := existingManagedView(parent, name, category); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := parent.Rename(temporary, name); err != nil {
|
||||
return fmt.Errorf("install managed %s view: %w", category, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Revert restores prior links only if they still point to this attempt.
|
||||
func (v *AttemptViews) Revert() error {
|
||||
if v == nil {
|
||||
return nil
|
||||
}
|
||||
return v.revertCategories([]string{"logs", "debug"})
|
||||
}
|
||||
|
||||
func (v *AttemptViews) revertCategories(categories []string) error {
|
||||
root, err := os.OpenRoot(v.root)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer root.Close()
|
||||
for _, category := range categories {
|
||||
parent, err := root.OpenRoot(category)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
current, err := existingManagedView(parent, v.name, category)
|
||||
if err == nil && (current == nil || *current != attemptTarget(v.runID, v.name, category)) {
|
||||
err = fmt.Errorf("managed %s view changed during attempt", category)
|
||||
}
|
||||
if err == nil {
|
||||
if previous := v.previous[category]; previous != nil {
|
||||
err = replaceManagedView(parent, v.name, category, *previous)
|
||||
} else {
|
||||
err = parent.Remove(v.name)
|
||||
}
|
||||
}
|
||||
_ = parent.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
134
internal/fileops/attempt_views_test.go
Normal file
134
internal/fileops/attempt_views_test.go
Normal file
@@ -0,0 +1,134 @@
|
||||
package fileops
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAttemptViewsAdvanceAndRestoreManagedTargets(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
first, err := BeginAttemptViews(root, "run-one", "polish")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = first
|
||||
for _, category := range []string{"logs", "debug"} {
|
||||
link := filepath.Join(root, category, "polish")
|
||||
target, err := os.Readlink(link)
|
||||
if err != nil || target != "../runs/run-one/polish/"+category {
|
||||
t.Fatalf("%s target = %q, %v", category, target, err)
|
||||
}
|
||||
info, err := os.Stat(link)
|
||||
if err != nil || !info.IsDir() {
|
||||
t.Fatalf("%s destination = %#v, %v", category, info, err)
|
||||
}
|
||||
}
|
||||
second, err := BeginAttemptViews(root, "run-two", "polish")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if target, err := os.Readlink(filepath.Join(root, "debug", "polish")); err != nil || !strings.Contains(target, "run-two") {
|
||||
t.Fatalf("second target = %q, %v", target, err)
|
||||
}
|
||||
if err := second.Revert(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, category := range []string{"logs", "debug"} {
|
||||
target, err := os.Readlink(filepath.Join(root, category, "polish"))
|
||||
if err != nil || target != "../runs/run-one/polish/"+category {
|
||||
t.Fatalf("restored %s target = %q, %v", category, target, err)
|
||||
}
|
||||
}
|
||||
other, err := BeginAttemptViews(root, "run-three", "extract")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := other.Revert(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Lstat(filepath.Join(root, "logs", "extract")); !os.IsNotExist(err) {
|
||||
t.Fatalf("new skipped view exists: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttemptViewsRejectConflictingAndUnsafePaths(t *testing.T) {
|
||||
for _, kind := range []string{"file", "directory", "foreign link", "symlink ancestor"} {
|
||||
t.Run(kind, func(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
if err := os.MkdirAll(filepath.Join(root, "logs"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
conflict := filepath.Join(root, "logs", "polish")
|
||||
switch kind {
|
||||
case "file":
|
||||
if err := os.WriteFile(conflict, []byte("keep"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case "directory":
|
||||
if err := os.Mkdir(conflict, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case "foreign link":
|
||||
if err := os.Symlink("../../outside", conflict); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case "symlink ancestor":
|
||||
if err := os.Symlink(t.TempDir(), filepath.Join(root, "runs")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := BeginAttemptViews(root, "run-one", "polish"); err == nil {
|
||||
t.Fatal("unsafe conflict accepted")
|
||||
}
|
||||
if kind == "file" {
|
||||
data, err := os.ReadFile(conflict)
|
||||
if err != nil || string(data) != "keep" {
|
||||
t.Fatalf("conflict changed: %q, %v", data, err)
|
||||
}
|
||||
}
|
||||
if kind == "foreign link" {
|
||||
target, err := os.Readlink(conflict)
|
||||
if err != nil || target != "../../outside" {
|
||||
t.Fatalf("link changed: %q, %v", target, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttemptViewsRejectUnsafeIdentities(t *testing.T) {
|
||||
for _, pair := range [][2]string{{"../escape", "polish"}, {"run", "../outside"}, {"run", ""}, {".preflight", "polish"}} {
|
||||
if _, err := BeginAttemptViews(t.TempDir(), pair[0], pair[1]); err == nil {
|
||||
t.Fatalf("accepted identities %q", pair)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttemptViewsLeavePriorLinksOnDirectoryFailure(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
if _, err := BeginAttemptViews(root, "first", "polish"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stageRoot := filepath.Join(root, "runs", "second", "polish")
|
||||
if err := os.MkdirAll(stageRoot, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(stageRoot, "debug"), []byte("keep"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := BeginAttemptViews(root, "second", "polish"); err == nil {
|
||||
t.Fatal("file accepted as debug directory")
|
||||
}
|
||||
for _, category := range []string{"logs", "debug"} {
|
||||
target, err := os.Readlink(filepath.Join(root, category, "polish"))
|
||||
if err != nil || target != "../runs/first/polish/"+category {
|
||||
t.Fatalf("prior %s view = %q, %v", category, target, err)
|
||||
}
|
||||
}
|
||||
data, err := os.ReadFile(filepath.Join(stageRoot, "debug"))
|
||||
if err != nil || string(data) != "keep" {
|
||||
t.Fatalf("conflict changed: %q, %v", data, err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user