Move attempt views to workspace path ownership

This commit is contained in:
2026-12-02 21:36:30 +00:00
parent 3d09745a79
commit 106036cf5b
14 changed files with 470 additions and 424 deletions

View File

@@ -19,9 +19,8 @@ Directory bundles are not promoted by `internal/fileops`; extraction keeps
the original bundle in its run until cleanup and promotes individual validated the original bundle in its run until cleanup and promotes individual validated
products. products.
Fileops updates, inspects and removes recognized managed latest-attempt links The workspace path owner manages latest-attempt links; fileops provides confined
without following their targets, including dangling links. Unrelated entries are directory creation and removal mechanics.
left alone and conflicting managed names are rejected.
## Cleanup Contract ## Cleanup Contract

View File

@@ -24,5 +24,5 @@ publish. See [operations](../operations.md#cleanup).
## Implementation And Tests ## Implementation And Tests
`internal/stage/cleanup_plan.go`, `cleanup.go`, `internal/fileops/cleanup.go`, `internal/stage/cleanup_plan.go`, `cleanup.go`, `internal/fileops/cleanup.go`,
`attempt_views.go`, and their tests own authorization, inspection, managed view `internal/artifacts/attempt_views.go`, and their tests own authorization, inspection, managed view
removal and confined deletion. removal and confined deletion.

View File

@@ -33,7 +33,7 @@ previous-session cache paths remain session-durable and are never redirected
into run-local output space. into run-local output space.
Polish and extraction write to actual run-local output, log, and debug paths. Polish and extraction write to actual run-local output, log, and debug paths.
Each attempt advances managed relative `logs/<stage>` and `debug/<stage>` links; The artifact path owner advances managed relative `logs/<stage>` and `debug/<stage>` links;
skips do not rotate them. Restore has its own diagnostic attempt. Extraction skips do not rotate them. Restore has its own diagnostic attempt. Extraction
promotes validated lanes to flat artifacts; the original bundle remains in promotes validated lanes to flat artifacts; the original bundle remains in
the producing run until cleanup. See [Operations](../operations.md#local-state-layout). the producing run until cleanup. See [Operations](../operations.md#local-state-layout).
@@ -97,7 +97,7 @@ syntax and exact deletion scope belong in [CLI](../cli.md#session-clean) and
## Implementation And Tests ## Implementation And Tests
- Path model and local store: `internal/artifacts/paths.go`, - Path model and local store: `internal/artifacts/paths.go`,
`internal/artifacts/local.go` `internal/artifacts/local.go`, `internal/artifacts/attempt_views.go`
- Run-local materialization: `internal/stage/run_local.go` - Run-local materialization: `internal/stage/run_local.go`
- Bundle validation and product promotion: `internal/stage/extract.go` - Bundle validation and product promotion: `internal/stage/extract.go`
- Workspace modes: `internal/fileops/modes.go` - Workspace modes: `internal/fileops/modes.go`

View File

@@ -41,10 +41,10 @@ their scope. Unless assigned otherwise, a finding remains independent audit
remediation. Shared code does not make a refactoring a prerequisite or assign remediation. Shared code does not make a refactoring a prerequisite or assign
the whole finding to a roadmap. the whole finding to a roadmap.
Thirty-three entries are closed by the safety, transfer, audio discovery, S3 Thirty-four entries are closed by the safety, transfer, audio discovery, S3
planning, prerequisite-history, publication-import, CLI classification, planning, prerequisite-history, publication-import, CLI classification,
inspection aggregation, test maintenance, dead-code removal, and associated inspection aggregation, test maintenance, dead-code removal, and associated
documentation work; 10 remain open. **Planned** identifies documentation work; 9 remain open. **Planned** identifies
an agreed remedy awaiting implementation. **Potentially eliminated** requires verification that the offending an agreed remedy awaiting implementation. **Potentially eliminated** requires verification that the offending
lifecycle is removed. **Coordinate** identifies shared changes, not a commitment lifecycle is removed. **Coordinate** identifies shared changes, not a commitment
that a related feature implements the entire finding. Findings close only after their that a related feature implements the entire finding. Findings close only after their
@@ -742,7 +742,10 @@ Related: [CAT-16](#cat-16--p3-flatten-inspection-error-aggregation).
### CAT-26 — P3: Place diagnostic-view layout grammar with canonical workspace paths ### CAT-26 — P3: Place diagnostic-view layout grammar with canonical workspace paths
Status: Open Status: Closed
**Closure.** Managed attempt views now use the artifact workspace path owner;
fileops retains confined directory mechanics. View, cleanup, stage and app tests pass.
Original findings: [BN-01](11-boundaries.md#bn-01--p3-diagnostic-view-layout-policy-is-embedded-in-file-operation-mechanics). Original findings: [BN-01](11-boundaries.md#bn-01--p3-diagnostic-view-layout-policy-is-embedded-in-file-operation-mechanics).

View File

@@ -446,7 +446,7 @@ Validation: `go test ./internal/contracts ./internal/adapters/seriatim ./interna
## Stage 15: Move Attempt Views To The Workspace Path Owner ## Stage 15: Move Attempt Views To The Workspace Path Owner
CAT IDs: CAT-26. Status: Pending. CAT IDs: CAT-26. Status: Complete.
Read [BN-01](audit/11-boundaries.md#bn-01--p3-diagnostic-view-layout-policy-is-embedded-in-file-operation-mechanics). Read [BN-01](audit/11-boundaries.md#bn-01--p3-diagnostic-view-layout-policy-is-embedded-in-file-operation-mechanics).

View File

@@ -14,7 +14,6 @@ import (
"gitea.maximumdirect.net/eric/narratio/internal/adapters/storage" "gitea.maximumdirect.net/eric/narratio/internal/adapters/storage"
"gitea.maximumdirect.net/eric/narratio/internal/artifacts" "gitea.maximumdirect.net/eric/narratio/internal/artifacts"
"gitea.maximumdirect.net/eric/narratio/internal/config" "gitea.maximumdirect.net/eric/narratio/internal/config"
"gitea.maximumdirect.net/eric/narratio/internal/fileops"
"gitea.maximumdirect.net/eric/narratio/internal/manifest" "gitea.maximumdirect.net/eric/narratio/internal/manifest"
"gitea.maximumdirect.net/eric/narratio/internal/stage" "gitea.maximumdirect.net/eric/narratio/internal/stage"
) )
@@ -319,7 +318,7 @@ func TestCleanupLifecycleReusesCleanStateAndRemovesLaterAttempts(t *testing.T) {
t.Fatalf("reused execution = %#v", summary) t.Fatalf("reused execution = %#v", summary)
} }
checkClean() checkClean()
if _, err := fileops.BeginAttemptViews(paths.Root, "later-run", "extract"); err != nil { if _, err := artifacts.BeginAttemptViews(paths.Root, "later-run", "extract"); err != nil {
t.Fatal(err) t.Fatal(err)
} }
cleanupOnly := BoundedPlan{stages: []stage.Stage{selectedCleanupStage(t)}} cleanupOnly := BoundedPlan{stages: []stage.Stage{selectedCleanupStage(t)}}

View File

@@ -8,7 +8,6 @@ import (
"gitea.maximumdirect.net/eric/narratio/internal/artifacts" "gitea.maximumdirect.net/eric/narratio/internal/artifacts"
"gitea.maximumdirect.net/eric/narratio/internal/config" "gitea.maximumdirect.net/eric/narratio/internal/config"
"gitea.maximumdirect.net/eric/narratio/internal/fileops"
"gitea.maximumdirect.net/eric/narratio/internal/manifest" "gitea.maximumdirect.net/eric/narratio/internal/manifest"
"go.maximumdirect.net/commandkit" "go.maximumdirect.net/commandkit"
) )
@@ -131,7 +130,7 @@ func restoreSessionState(ctx context.Context, cfg *config.Config, opts RestorePl
return diagnostic, fmt.Errorf("restore: generate diagnostic run id: %w", err) return diagnostic, fmt.Errorf("restore: generate diagnostic run id: %w", err)
} }
sessionPaths := artifactStore.SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID) sessionPaths := artifactStore.SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
if _, err := fileops.BeginAttemptViews(sessionPaths.Root, restoreRunID, "restore"); err != nil { if _, err := artifacts.BeginAttemptViews(sessionPaths.Root, restoreRunID, "restore"); err != nil {
return diagnostic, fmt.Errorf("restore: prepare diagnostic views: %w", err) return diagnostic, fmt.Errorf("restore: prepare diagnostic views: %w", err)
} }
report.reportPathRel = filepath.ToSlash(filepath.Join("runs", restoreRunID, "restore", "logs", "restore.json")) report.reportPathRel = filepath.ToSlash(filepath.Join("runs", restoreRunID, "restore", "logs", "restore.json"))

View File

@@ -4,7 +4,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"gitea.maximumdirect.net/eric/narratio/internal/fileops" "gitea.maximumdirect.net/eric/narratio/internal/artifacts"
"gitea.maximumdirect.net/eric/narratio/internal/stage" "gitea.maximumdirect.net/eric/narratio/internal/stage"
) )
@@ -97,9 +97,9 @@ func executeSelectedStage(runtime *invocationRuntime, selected stage.Stage) (out
return outcome, operationErr return outcome, operationErr
} }
env.Debug("manifest saved", "stage", selected.Name(), "transition", "running", "path", runtime.manifestPath) env.Debug("manifest saved", "stage", selected.Name(), "transition", "running", "path", runtime.manifestPath)
var views *fileops.AttemptViews var views *artifacts.AttemptViews
if needsAttemptViews(selected, env) { if needsAttemptViews(selected, env) {
views, err = fileops.BeginAttemptViews(runtime.paths.Root, runtime.identity.RunID, selected.Name()) views, err = artifacts.BeginAttemptViews(runtime.paths.Root, runtime.identity.RunID, selected.Name())
if err != nil { if err != nil {
return outcome, fmt.Errorf("prepare latest-attempt views for %q: %w", selected.Name(), err) return outcome, fmt.Errorf("prepare latest-attempt views for %q: %w", selected.Name(), err)
} }

View File

@@ -0,0 +1,237 @@
package artifacts
import (
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"gitea.maximumdirect.net/eric/narratio/internal/fileops"
"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
}
// 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()
paths := buildSessionPathsFromRoot("", "", "", sessionRoot)
for _, dir := range []string{SessionRunLogsDir(paths, runID, name), SessionRunDebugDir(paths, runID, name), paths.LogsDir, paths.DebugDir} {
relative, err := filepath.Rel(sessionRoot, dir)
if err != nil {
return nil, err
}
if err := fileops.EnsureWorkspaceDirectoryUnderRoot(sessionRoot, 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, sessionRoot, 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(sessionRoot, runID, name, category)
err = replaceManagedView(parent, sessionRoot, 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(sessionRoot, runID, name, category string) string {
paths := buildSessionPathsFromRoot("", "", "", sessionRoot)
view, destination := SessionLatestLogsPath(paths, name), SessionRunLogsDir(paths, runID, name)
if category == "debug" {
view, destination = SessionLatestDebugPath(paths, name), SessionRunDebugDir(paths, runID, name)
}
relative, _ := filepath.Rel(filepath.Dir(view), destination)
return filepath.ToSlash(relative)
}
func existingManagedView(parent *os.Root, sessionRoot, 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
}
paths := buildSessionPathsFromRoot("", "", "", sessionRoot)
view := SessionLatestLogsPath(paths, name)
if category == "debug" {
view = SessionLatestDebugPath(paths, name)
}
resolved := filepath.Clean(filepath.Join(filepath.Dir(view), filepath.FromSlash(target)))
relative, err := filepath.Rel(paths.RunsDir, resolved)
parts := strings.Split(filepath.ToSlash(relative), "/")
if err != nil || len(parts) != 3 || parts[1] != name || parts[2] != category || parts[0] == ".preflight" || parts[0] == ".validation" || pathsafe.ValidateOpaqueSegment(parts[0]) != nil || target != attemptTarget(sessionRoot, parts[0], name, category) {
return nil, fmt.Errorf("managed %s view %q has an unexpected target %q", category, name, target)
}
return &target, nil
}
// InspectManagedAttemptViews reports whether any recognized managed view exists.
// Dangling links count as present; their targets are never followed.
func InspectManagedAttemptViews(sessionRoot string, names []string) (bool, error) {
return visitManagedAttemptViews(sessionRoot, names, false)
}
// RemoveManagedAttemptViews removes recognized managed links without following them.
func RemoveManagedAttemptViews(sessionRoot string, names []string) error {
_, err := visitManagedAttemptViews(sessionRoot, names, true)
return err
}
func visitManagedAttemptViews(sessionRoot string, names []string, remove bool) (bool, error) {
for _, name := range names {
if err := pathsafe.ValidateOpaqueSegment(name); err != nil {
return false, fmt.Errorf("invalid managed view %q: %w", name, err)
}
}
root, err := os.OpenRoot(sessionRoot)
if err != nil {
return false, err
}
defer root.Close()
found := false
for _, category := range []string{"logs", "debug"} {
info, err := root.Lstat(category)
if errors.Is(err, os.ErrNotExist) {
continue
}
if err != nil {
return false, err
}
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return false, fmt.Errorf("managed %s directory is unsafe", category)
}
parent, err := root.OpenRoot(category)
if err != nil {
return false, err
}
for _, name := range names {
target, err := existingManagedView(parent, sessionRoot, name, category)
if err == nil && target != nil {
found = true
if remove {
err = parent.Remove(name)
if errors.Is(err, os.ErrNotExist) {
err = nil
}
}
}
if err != nil {
_ = parent.Close()
return false, err
}
}
_ = parent.Close()
}
return found, nil
}
func replaceManagedView(parent *os.Root, sessionRoot, name, category, target string) error {
if _, err := existingManagedView(parent, sessionRoot, 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, sessionRoot, 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.root, v.name, category)
if err == nil && (current == nil || *current != attemptTarget(v.root, 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.root, v.name, category, *previous)
} else {
err = parent.Remove(v.name)
}
}
_ = parent.Close()
if err != nil {
return err
}
}
return nil
}

View File

@@ -0,0 +1,205 @@
package artifacts
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)
}
}
func TestManagedAttemptViewsInspectAndRemove(t *testing.T) {
root := t.TempDir()
names := []string{"polish", "extract", "restore"}
if found, err := InspectManagedAttemptViews(root, names); err != nil || found {
t.Fatalf("empty views = %v, %v", found, err)
}
for _, pair := range [][2]string{{"first", "polish"}, {"second", "extract"}, {"third", "restore"}} {
if _, err := BeginAttemptViews(root, pair[0], pair[1]); err != nil {
t.Fatal(err)
}
}
unrelated := filepath.Join(root, "logs", "operator")
if err := os.WriteFile(unrelated, []byte("keep"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.RemoveAll(filepath.Join(root, "runs", "second")); err != nil {
t.Fatal(err)
}
if found, err := InspectManagedAttemptViews(root, names); err != nil || !found {
t.Fatalf("managed views = %v, %v", found, err)
}
if _, err := os.Lstat(filepath.Join(root, "logs", "extract")); err != nil {
t.Fatalf("inspection changed dangling view: %v", err)
}
for range 2 {
if err := RemoveManagedAttemptViews(root, names); err != nil {
t.Fatal(err)
}
}
if found, err := InspectManagedAttemptViews(root, names); err != nil || found {
t.Fatalf("removed views = %v, %v", found, err)
}
if data, err := os.ReadFile(unrelated); err != nil || string(data) != "keep" {
t.Fatalf("operator content = %q, %v", data, err)
}
if _, err := os.Stat(filepath.Join(root, "runs", "first", "polish", "logs")); err != nil {
t.Fatalf("view target removed: %v", err)
}
}
func TestManagedAttemptViewsRejectConflicts(t *testing.T) {
for _, kind := range []string{"file", "foreign link", "category link"} {
t.Run(kind, func(t *testing.T) {
root := t.TempDir()
if kind == "category link" {
if err := os.Symlink(t.TempDir(), filepath.Join(root, "logs")); err != nil {
t.Fatal(err)
}
} else {
if err := os.Mkdir(filepath.Join(root, "logs"), 0o755); err != nil {
t.Fatal(err)
}
path := filepath.Join(root, "logs", "polish")
if kind == "file" {
if err := os.WriteFile(path, []byte("keep"), 0o600); err != nil {
t.Fatal(err)
}
} else if err := os.Symlink("../../outside", path); err != nil {
t.Fatal(err)
}
}
if _, err := InspectManagedAttemptViews(root, []string{"polish"}); err == nil {
t.Fatal("inspection accepted conflict")
}
if err := RemoveManagedAttemptViews(root, []string{"polish"}); err == nil {
t.Fatal("removal accepted conflict")
}
})
}
}

View File

@@ -1,24 +1,14 @@
package fileops package fileops
import ( import (
"crypto/rand"
"encoding/hex"
"errors" "errors"
"fmt" "fmt"
"gitea.maximumdirect.net/eric/narratio/internal/pathsafe"
"os" "os"
"path/filepath" "path/filepath"
"strings" "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 // EnsureWorkspaceDirectoryUnderRoot creates real directories beneath an
// existing root and rejects symlink components instead of following them. // existing root and rejects symlink components instead of following them.
func EnsureWorkspaceDirectoryUnderRoot(rootPath, relative string) error { func EnsureWorkspaceDirectoryUnderRoot(rootPath, relative string) error {
@@ -30,10 +20,10 @@ func EnsureWorkspaceDirectoryUnderRoot(rootPath, relative string) error {
return err return err
} }
defer root.Close() defer root.Close()
return ensureAttemptDirectory(root, relative) return ensureWorkspaceDirectory(root, relative)
} }
func ensureAttemptDirectory(root *os.Root, relative string) error { func ensureWorkspaceDirectory(root *os.Root, relative string) error {
current := "" current := ""
for _, component := range strings.Split(filepath.ToSlash(relative), "/") { for _, component := range strings.Split(filepath.ToSlash(relative), "/") {
if component == "" || component == "." || component == ".." { if component == "" || component == "." || component == ".." {
@@ -59,201 +49,3 @@ func ensureAttemptDirectory(root *os.Root, relative string) error {
} }
return nil 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
}
// InspectManagedAttemptViews reports whether any recognized managed view exists.
// Dangling links count as present; their targets are never followed.
func InspectManagedAttemptViews(sessionRoot string, names []string) (bool, error) {
return visitManagedAttemptViews(sessionRoot, names, false)
}
// RemoveManagedAttemptViews removes recognized managed links without following them.
func RemoveManagedAttemptViews(sessionRoot string, names []string) error {
_, err := visitManagedAttemptViews(sessionRoot, names, true)
return err
}
func visitManagedAttemptViews(sessionRoot string, names []string, remove bool) (bool, error) {
for _, name := range names {
if err := pathsafe.ValidateOpaqueSegment(name); err != nil {
return false, fmt.Errorf("invalid managed view %q: %w", name, err)
}
}
root, err := os.OpenRoot(sessionRoot)
if err != nil {
return false, err
}
defer root.Close()
found := false
for _, category := range []string{"logs", "debug"} {
info, err := root.Lstat(category)
if errors.Is(err, os.ErrNotExist) {
continue
}
if err != nil {
return false, err
}
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return false, fmt.Errorf("managed %s directory is unsafe", category)
}
parent, err := root.OpenRoot(category)
if err != nil {
return false, err
}
for _, name := range names {
target, err := existingManagedView(parent, name, category)
if err == nil && target != nil {
found = true
if remove {
err = parent.Remove(name)
if errors.Is(err, os.ErrNotExist) {
err = nil
}
}
}
if err != nil {
_ = parent.Close()
return false, err
}
}
_ = parent.Close()
}
return found, 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
}

View File

@@ -3,203 +3,15 @@ package fileops
import ( import (
"os" "os"
"path/filepath" "path/filepath"
"strings"
"testing" "testing"
) )
func TestAttemptViewsAdvanceAndRestoreManagedTargets(t *testing.T) { func TestEnsureWorkspaceDirectoryUnderRootRejectsSymlink(t *testing.T) {
root := t.TempDir() root := t.TempDir()
first, err := BeginAttemptViews(root, "run-one", "polish") if err := os.Symlink(t.TempDir(), filepath.Join(root, "link")); err != nil {
if err != nil {
t.Fatal(err) t.Fatal(err)
} }
_ = first if err := EnsureWorkspaceDirectoryUnderRoot(root, "link/nested"); err == nil {
for _, category := range []string{"logs", "debug"} { t.Fatal("accepted symlink directory")
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)
}
}
func TestManagedAttemptViewsInspectAndRemove(t *testing.T) {
root := t.TempDir()
names := []string{"polish", "extract", "restore"}
if found, err := InspectManagedAttemptViews(root, names); err != nil || found {
t.Fatalf("empty views = %v, %v", found, err)
}
for _, pair := range [][2]string{{"first", "polish"}, {"second", "extract"}, {"third", "restore"}} {
if _, err := BeginAttemptViews(root, pair[0], pair[1]); err != nil {
t.Fatal(err)
}
}
unrelated := filepath.Join(root, "logs", "operator")
if err := os.WriteFile(unrelated, []byte("keep"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.RemoveAll(filepath.Join(root, "runs", "second")); err != nil {
t.Fatal(err)
}
if found, err := InspectManagedAttemptViews(root, names); err != nil || !found {
t.Fatalf("managed views = %v, %v", found, err)
}
if _, err := os.Lstat(filepath.Join(root, "logs", "extract")); err != nil {
t.Fatalf("inspection changed dangling view: %v", err)
}
for range 2 {
if err := RemoveManagedAttemptViews(root, names); err != nil {
t.Fatal(err)
}
}
if found, err := InspectManagedAttemptViews(root, names); err != nil || found {
t.Fatalf("removed views = %v, %v", found, err)
}
if data, err := os.ReadFile(unrelated); err != nil || string(data) != "keep" {
t.Fatalf("operator content = %q, %v", data, err)
}
if _, err := os.Stat(filepath.Join(root, "runs", "first", "polish", "logs")); err != nil {
t.Fatalf("view target removed: %v", err)
}
}
func TestManagedAttemptViewsRejectConflicts(t *testing.T) {
for _, kind := range []string{"file", "foreign link", "category link"} {
t.Run(kind, func(t *testing.T) {
root := t.TempDir()
if kind == "category link" {
if err := os.Symlink(t.TempDir(), filepath.Join(root, "logs")); err != nil {
t.Fatal(err)
}
} else {
if err := os.Mkdir(filepath.Join(root, "logs"), 0o755); err != nil {
t.Fatal(err)
}
path := filepath.Join(root, "logs", "polish")
if kind == "file" {
if err := os.WriteFile(path, []byte("keep"), 0o600); err != nil {
t.Fatal(err)
}
} else if err := os.Symlink("../../outside", path); err != nil {
t.Fatal(err)
}
}
if _, err := InspectManagedAttemptViews(root, []string{"polish"}); err == nil {
t.Fatal("inspection accepted conflict")
}
if err := RemoveManagedAttemptViews(root, []string{"polish"}); err == nil {
t.Fatal("removal accepted conflict")
}
})
} }
} }

View File

@@ -8,6 +8,7 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
"gitea.maximumdirect.net/eric/narratio/internal/fileops" "gitea.maximumdirect.net/eric/narratio/internal/fileops"
"gitea.maximumdirect.net/eric/narratio/internal/manifest" "gitea.maximumdirect.net/eric/narratio/internal/manifest"
) )
@@ -47,7 +48,7 @@ func (cleanupStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (*S
} }
_, err := inspectCleanupTarget(target.root, target.target) _, err := inspectCleanupTarget(target.root, target.target)
if err == nil { if err == nil {
err = fileops.RemoveManagedAttemptViews(filepath.Dir(target.target), cleanupManagedNames()) err = artifacts.RemoveManagedAttemptViews(filepath.Dir(target.target), cleanupManagedNames())
if errors.Is(err, os.ErrNotExist) { if errors.Is(err, os.ErrNotExist) {
err = nil err = nil
} }
@@ -165,7 +166,7 @@ func inspectCleanupTarget(workspaceRoot, runsDir string) (bool, error) {
if runsExist && (!info.IsDir() || info.Mode()&os.ModeSymlink != 0) { if runsExist && (!info.IsDir() || info.Mode()&os.ModeSymlink != 0) {
return false, fmt.Errorf("unsafe run cleanup directory %q", runsDir) return false, fmt.Errorf("unsafe run cleanup directory %q", runsDir)
} }
viewsExist, err := fileops.InspectManagedAttemptViews(session, cleanupManagedNames()) viewsExist, err := artifacts.InspectManagedAttemptViews(session, cleanupManagedNames())
if err != nil { if err != nil {
return false, err return false, err
} }

View File

@@ -10,7 +10,6 @@ import (
"testing" "testing"
"gitea.maximumdirect.net/eric/narratio/internal/artifacts" "gitea.maximumdirect.net/eric/narratio/internal/artifacts"
"gitea.maximumdirect.net/eric/narratio/internal/fileops"
) )
func TestCleanupStageDisabledSelfSkips(t *testing.T) { func TestCleanupStageDisabledSelfSkips(t *testing.T) {
@@ -35,7 +34,7 @@ func TestCleanupRemovesSessionRunsAndManagedViews(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
for _, pair := range [][2]string{{published, "polish"}, {"older-failure", "extract"}, {"restore-run", "restore"}} { for _, pair := range [][2]string{{published, "polish"}, {"older-failure", "extract"}, {"restore-run", "restore"}} {
if _, err := fileops.BeginAttemptViews(session.Root, pair[0], pair[1]); err != nil { if _, err := artifacts.BeginAttemptViews(session.Root, pair[0], pair[1]); err != nil {
t.Fatal(err) t.Fatal(err)
} }
writeStageTestFile(t, filepath.Join(session.RunsDir, pair[0], pair[1], "logs", "diagnostic"), "data") writeStageTestFile(t, filepath.Join(session.RunsDir, pair[0], pair[1], "logs", "diagnostic"), "data")