fix(archive): never archive over or into a source; confirm overwrite (U-P0-1)
- CreateArchive refuses an archive path that is a source or lies inside one (symlinked parents resolved) and writes to a temp file renamed over the target only on success, so failures/cancels leave no partial file and keep an existing archive intact - the UI checks the target before starting and asks before replacing an existing archive Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
2ba00b0ad0
commit
fbaffb4354
4 changed files with 252 additions and 3 deletions
|
|
@ -315,22 +315,94 @@ func ArchiveName(sources []string, format string) string {
|
||||||
// CreateArchive creates an archive from source paths using the given format.
|
// CreateArchive creates an archive from source paths using the given format.
|
||||||
// Supported formats: "zip", "tar", "tar.gz" (or "targz", "tgz").
|
// Supported formats: "zip", "tar", "tar.gz" (or "targz", "tgz").
|
||||||
// Progress is reported via the callback function.
|
// Progress is reported via the callback function.
|
||||||
|
//
|
||||||
|
// The archive is written to a temporary file next to archivePath and renamed
|
||||||
|
// over it only on success, so a failed or cancelled run leaves neither a
|
||||||
|
// partial archive nor a damaged previous one. An archivePath that is one of
|
||||||
|
// the sources or lies inside one is refused (U-P0-1).
|
||||||
func CreateArchive(ctx context.Context, sources []string, archivePath string, progress func(CopyProgress)) error {
|
func CreateArchive(ctx context.Context, sources []string, archivePath string, progress func(CopyProgress)) error {
|
||||||
if ctx == nil {
|
if ctx == nil {
|
||||||
ctx = context.Background()
|
ctx = context.Background()
|
||||||
}
|
}
|
||||||
|
if err := CheckArchiveTarget(sources, archivePath); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
var create func(context.Context, []string, string, func(CopyProgress)) error
|
||||||
lower := strings.ToLower(archivePath)
|
lower := strings.ToLower(archivePath)
|
||||||
switch {
|
switch {
|
||||||
case strings.HasSuffix(lower, ".zip"):
|
case strings.HasSuffix(lower, ".zip"):
|
||||||
return createZipArchive(ctx, sources, archivePath, progress)
|
create = createZipArchive
|
||||||
case strings.HasSuffix(lower, ".tar.gz"), strings.HasSuffix(lower, ".tgz"):
|
case strings.HasSuffix(lower, ".tar.gz"), strings.HasSuffix(lower, ".tgz"):
|
||||||
return createTarGzArchive(ctx, sources, archivePath, progress)
|
create = createTarGzArchive
|
||||||
case strings.HasSuffix(lower, ".tar"):
|
case strings.HasSuffix(lower, ".tar"):
|
||||||
return createTarArchive(ctx, sources, archivePath, progress)
|
create = createTarArchive
|
||||||
default:
|
default:
|
||||||
return fmt.Errorf("unsupported archive format: %s", filepath.Ext(archivePath))
|
return fmt.Errorf("unsupported archive format: %s", filepath.Ext(archivePath))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
tmp, err := os.CreateTemp(filepath.Dir(archivePath), ".vcom-tmp-*-"+filepath.Base(archivePath))
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("create %s: %w", archivePath, err)
|
||||||
|
}
|
||||||
|
tmpPath := tmp.Name()
|
||||||
|
tmp.Close()
|
||||||
|
if err := create(ctx, sources, tmpPath, progress); err != nil {
|
||||||
|
os.Remove(tmpPath)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := os.Chmod(tmpPath, 0o644); err != nil {
|
||||||
|
os.Remove(tmpPath)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := os.Rename(tmpPath, archivePath); err != nil {
|
||||||
|
os.Remove(tmpPath)
|
||||||
|
return fmt.Errorf("rename %s: %w", archivePath, err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CheckArchiveTarget returns an error if writing archivePath would overwrite
|
||||||
|
// one of sources or place the archive inside a source directory (where it
|
||||||
|
// would be truncated before being read, or include itself). Symlinked
|
||||||
|
// parent directories are resolved.
|
||||||
|
func CheckArchiveTarget(sources []string, archivePath string) error {
|
||||||
|
target := []string{archivePath}
|
||||||
|
if r, ok := resolveParent(archivePath); ok {
|
||||||
|
target = append(target, r)
|
||||||
|
}
|
||||||
|
for _, src := range sources {
|
||||||
|
candidates := []string{src}
|
||||||
|
if r, ok := resolveParent(src); ok {
|
||||||
|
candidates = append(candidates, r)
|
||||||
|
}
|
||||||
|
for _, t := range target {
|
||||||
|
for _, c := range candidates {
|
||||||
|
within, err := pathWithin(t, c)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if within {
|
||||||
|
return fmt.Errorf("archive %s would overwrite or be inside its source %s", filepath.Base(archivePath), src)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// resolveParent resolves symlinks in p's parent directory (p itself may not
|
||||||
|
// exist yet and is not followed).
|
||||||
|
func resolveParent(p string) (string, bool) {
|
||||||
|
abs, err := filepath.Abs(p)
|
||||||
|
if err != nil {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
dir, err := filepath.EvalSymlinks(filepath.Dir(abs))
|
||||||
|
if err != nil {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return filepath.Join(dir, filepath.Base(abs)), true
|
||||||
}
|
}
|
||||||
|
|
||||||
func createZipArchive(ctx context.Context, sources []string, archivePath string, progress func(CopyProgress)) error {
|
func createZipArchive(ctx context.Context, sources []string, archivePath string, progress func(CopyProgress)) error {
|
||||||
|
|
|
||||||
|
|
@ -183,3 +183,58 @@ func TestRenamePathRejectsExistingTarget(t *testing.T) {
|
||||||
t.Fatalf("expected overwrite error %q, got %q", want, got)
|
t.Fatalf("expected overwrite error %q, got %q", want, got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestCreateArchiveRefusesSourceAndSelfInclusion(t *testing.T) {
|
||||||
|
d := t.TempDir()
|
||||||
|
src := filepath.Join(d, "data.tar")
|
||||||
|
if err := os.WriteFile(src, make([]byte, 100000), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := CreateArchive(context.Background(), []string{src}, filepath.Join(d, ArchiveName([]string{src}, "tar")), nil); err == nil {
|
||||||
|
t.Fatal("archive over its own source must be refused")
|
||||||
|
}
|
||||||
|
if st, _ := os.Stat(src); st.Size() != 100000 {
|
||||||
|
t.Fatalf("source damaged: %d", st.Size())
|
||||||
|
}
|
||||||
|
|
||||||
|
proj := filepath.Join(d, "proj")
|
||||||
|
if err := os.MkdirAll(proj, 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := CreateArchive(context.Background(), []string{proj}, filepath.Join(proj, "proj.zip"), nil); err == nil {
|
||||||
|
t.Fatal("archive inside its source must be refused")
|
||||||
|
}
|
||||||
|
// Same through a symlinked parent.
|
||||||
|
if err := os.Symlink(proj, filepath.Join(d, "alias")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := CreateArchive(context.Background(), []string{proj}, filepath.Join(d, "alias", "proj.zip"), nil); err == nil {
|
||||||
|
t.Fatal("archive inside its source via a symlinked dir must be refused")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreateArchiveFailureKeepsOldArchive(t *testing.T) {
|
||||||
|
d := t.TempDir()
|
||||||
|
arc := filepath.Join(d, "out.zip")
|
||||||
|
if err := os.WriteFile(arc, []byte("OLD"), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
cancel()
|
||||||
|
src := filepath.Join(d, "src")
|
||||||
|
if err := os.MkdirAll(src, 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(filepath.Join(src, "f"), []byte("x"), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := CreateArchive(ctx, []string{src}, arc, nil); err == nil {
|
||||||
|
t.Fatal("cancelled archive should fail")
|
||||||
|
}
|
||||||
|
if b, _ := os.ReadFile(arc); string(b) != "OLD" {
|
||||||
|
t.Fatalf("failed run replaced the old archive: %q", b)
|
||||||
|
}
|
||||||
|
if left, _ := filepath.Glob(filepath.Join(d, ".vcom-tmp-*")); len(left) != 0 {
|
||||||
|
t.Fatalf("temp files left: %v", left)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -423,3 +423,97 @@ func TestUP15_CyrillicTextAndCommands(t *testing.T) {
|
||||||
t.Fatal("rename with a Cyrillic name failed")
|
t.Fatal("rename with a Cyrillic name failed")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func fileSize(t *testing.T, p string) int64 {
|
||||||
|
t.Helper()
|
||||||
|
st, err := os.Stat(p)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return st.Size()
|
||||||
|
}
|
||||||
|
|
||||||
|
// U-P0-1: archiving data.tar as tar into the same directory truncated the
|
||||||
|
// source (archive name == source name).
|
||||||
|
func TestUP01_ArchiveDoesNotDestroySource(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
src := filepath.Join(dir, "data.tar")
|
||||||
|
writeFile(t, src, strings.Repeat("x", 100000))
|
||||||
|
d := newDriver(t, dir, dir)
|
||||||
|
selectName(t, d, "data.tar")
|
||||||
|
d.Press("f4")
|
||||||
|
d.Settle(settle)
|
||||||
|
if cur(t, d).modal.kind != modalArchiveType {
|
||||||
|
t.Fatalf("archive dialog did not open, status %q", cur(t, d).status)
|
||||||
|
}
|
||||||
|
d.Press("f") // zip -> tar
|
||||||
|
if cur(t, d).archiveFormat != "tar" {
|
||||||
|
t.Fatalf("format %q", cur(t, d).archiveFormat)
|
||||||
|
}
|
||||||
|
d.Press("enter")
|
||||||
|
d.Settle(settle)
|
||||||
|
if got := fileSize(t, src); got != 100000 {
|
||||||
|
t.Fatalf("source truncated to %d bytes", got)
|
||||||
|
}
|
||||||
|
if !d.ScreenContains("Cannot archive") {
|
||||||
|
t.Fatalf("refusal not shown:\n%s", d.Screen())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// U-P0-1: passive pane inside the archived directory made the archive
|
||||||
|
// include itself.
|
||||||
|
func TestUP01_ArchiveNotInsideSource(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
proj := filepath.Join(dir, "proj")
|
||||||
|
writeFile(t, filepath.Join(proj, "a.bin"), strings.Repeat("y", 1<<16))
|
||||||
|
d := newDriver(t, dir, proj)
|
||||||
|
selectName(t, d, "proj")
|
||||||
|
d.Press("f4")
|
||||||
|
d.Settle(settle)
|
||||||
|
d.Press("enter")
|
||||||
|
d.Settle(settle)
|
||||||
|
entries, _ := os.ReadDir(proj)
|
||||||
|
if len(entries) != 1 {
|
||||||
|
t.Fatalf("archive was written inside its own source: %v", entries)
|
||||||
|
}
|
||||||
|
if !d.ScreenContains("Cannot archive") {
|
||||||
|
t.Fatalf("refusal not shown:\n%s", d.Screen())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// U-P0-1 (adjacent): an existing archive was overwritten without asking.
|
||||||
|
func TestUP01_ExistingArchiveNeedsConfirm(t *testing.T) {
|
||||||
|
dir, out := t.TempDir(), t.TempDir()
|
||||||
|
writeFile(t, filepath.Join(dir, "a.txt"), "new content")
|
||||||
|
old := filepath.Join(out, "a.zip")
|
||||||
|
writeFile(t, old, "OLD ARCHIVE")
|
||||||
|
d := newDriver(t, dir, out)
|
||||||
|
selectName(t, d, "a.txt")
|
||||||
|
|
||||||
|
d.Press("f4")
|
||||||
|
d.Settle(settle)
|
||||||
|
d.Press("enter")
|
||||||
|
d.Settle(settle)
|
||||||
|
if !d.ScreenContains("Overwrite existing archive") {
|
||||||
|
t.Fatalf("no overwrite confirmation:\n%s", d.Screen())
|
||||||
|
}
|
||||||
|
d.Press("n")
|
||||||
|
d.Settle(settle)
|
||||||
|
if b, _ := os.ReadFile(old); string(b) != "OLD ARCHIVE" {
|
||||||
|
t.Fatal("cancelled overwrite changed the archive")
|
||||||
|
}
|
||||||
|
|
||||||
|
d.Press("f4")
|
||||||
|
d.Settle(settle)
|
||||||
|
d.Press("enter")
|
||||||
|
d.Settle(settle)
|
||||||
|
d.Press("enter") // confirm overwrite
|
||||||
|
d.Settle(settle)
|
||||||
|
if b, _ := os.ReadFile(old); string(b) == "OLD ARCHIVE" || len(b) == 0 {
|
||||||
|
t.Fatalf("confirmed overwrite did not write the archive (status %q)", cur(t, d).status)
|
||||||
|
}
|
||||||
|
leftovers, _ := filepath.Glob(filepath.Join(out, ".vcom-tmp-*"))
|
||||||
|
if len(leftovers) != 0 {
|
||||||
|
t.Fatalf("temp files left: %v", leftovers)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -70,6 +70,7 @@ type pendingOperation struct {
|
||||||
overwrite bool
|
overwrite bool
|
||||||
existingTargets int
|
existingTargets int
|
||||||
stats vfs.TransferStats
|
stats vfs.TransferStats
|
||||||
|
format string // archive format for opArchive
|
||||||
|
|
||||||
// Remote operation fields — non-nil when source/target is remote
|
// Remote operation fields — non-nil when source/target is remote
|
||||||
srcClient *remote.SSHClient
|
srcClient *remote.SSHClient
|
||||||
|
|
@ -1428,6 +1429,16 @@ func (m Model) handleModalKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
|
||||||
return m, m.startDeleteJob(pending.kind, pending.sourcePaths)
|
return m, m.startDeleteJob(pending.kind, pending.sourcePaths)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Archive over an existing file, confirmed
|
||||||
|
if pending.kind == opArchive {
|
||||||
|
if m.archiveJob != nil {
|
||||||
|
m.status = "Archive is already running"
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
m.busy = true
|
||||||
|
return m, m.startArchiveJob(pending.sourcePaths, pending.targetDir, pending.format, pending.stats)
|
||||||
|
}
|
||||||
|
|
||||||
// Extract archive
|
// Extract archive
|
||||||
if pending.kind == opExtractArchive {
|
if pending.kind == opExtractArchive {
|
||||||
if m.archiveJob != nil {
|
if m.archiveJob != nil {
|
||||||
|
|
@ -1485,6 +1496,23 @@ func (m Model) handleModalKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
|
||||||
m.status = "Archive is already running"
|
m.status = "Archive is already running"
|
||||||
return m, nil
|
return m, nil
|
||||||
}
|
}
|
||||||
|
archivePath := filepath.Join(pending.targetDir, vfs.ArchiveName(pending.sourcePaths, m.archiveFormat))
|
||||||
|
if err := vfs.CheckArchiveTarget(pending.sourcePaths, archivePath); err != nil {
|
||||||
|
m.busy = false
|
||||||
|
m.status = fmt.Sprintf("Cannot archive: %v", err)
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
if _, err := os.Lstat(archivePath); err == nil {
|
||||||
|
pending.format = m.archiveFormat
|
||||||
|
pending.overwrite = true
|
||||||
|
m.openConfirmModal(
|
||||||
|
"Overwrite existing archive?",
|
||||||
|
fmt.Sprintf("Archive: %s\nexists and will be replaced.", archivePath),
|
||||||
|
"Enter / y to overwrite, Esc / n to cancel",
|
||||||
|
pending,
|
||||||
|
)
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
m.busy = true
|
m.busy = true
|
||||||
log.Printf("[MODAL] Archive confirmed — sources=%d targetDir=%s format=%s", len(pending.sourcePaths), pending.targetDir, m.archiveFormat)
|
log.Printf("[MODAL] Archive confirmed — sources=%d targetDir=%s format=%s", len(pending.sourcePaths), pending.targetDir, m.archiveFormat)
|
||||||
return m, m.startArchiveJob(pending.sourcePaths, pending.targetDir, m.archiveFormat, pending.stats)
|
return m, m.startArchiveJob(pending.sourcePaths, pending.targetDir, m.archiveFormat, pending.stats)
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue