merge: v0.2.8 QA report, QA tests and QA fixes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> # Conflicts: # plans/rework/04-dev-log.md
This commit is contained in:
commit
2dd42d0e03
16 changed files with 2391 additions and 37 deletions
29
CHANGELOG.md
29
CHANGELOG.md
|
|
@ -9,7 +9,8 @@ Data-loss and crash fixes for v0.2.7 while the larger rework is in progress.
|
|||
directory used to truncate the source; archiving a directory into a pane inside it made the archive include
|
||||
itself. Both are now refused. Archives are written to a temporary file and renamed into place only on success,
|
||||
so a failed or cancelled run leaves no partial file and keeps an existing archive intact; replacing an existing
|
||||
archive asks first.
|
||||
archive asks first. A replaced archive keeps its permissions (a private `0600` archive no longer becomes
|
||||
world-readable), and archive names close to the file-name length limit work again.
|
||||
- **Deleting a remote symlink to a directory no longer wipes the target directory.** The link itself is removed.
|
||||
- **SSH panes no longer act on local files.** Rename, Enter (edit / run / open / enter archive), archive and unpack
|
||||
in an SSH pane used to operate on the *local* file with the same path (e.g. running a local
|
||||
|
|
@ -18,7 +19,18 @@ Data-loss and crash fixes for v0.2.7 while the larger rework is in progress.
|
|||
archive used to put files into a temporary directory that is deleted when the archive is closed; with the
|
||||
`ssh://` host list as target, files went to `./ssh:/…` in the process directory. Both are now refused.
|
||||
- **Delete moves to the trash by default.** Permanent deletion is chosen explicitly with `D`/`d` in the dialog.
|
||||
`behavior.confirm_delete = false` now works and skips the question only for the trash.
|
||||
`behavior.confirm_delete = false` now works and skips the question only for the trash. If an item cannot be moved
|
||||
to the trash (e.g. it is on another filesystem than the home trash, or the trash is broken), vcom asks whether to
|
||||
delete the remaining items permanently instead; nothing is deleted without that confirmation.
|
||||
- **Mirror (`p`) is refused inside an archive.** It used to give the other pane the archive's temporary directory as
|
||||
a normal writable directory; changes there were lost when the archive was closed.
|
||||
|
||||
### SSH
|
||||
- **One unsupported line in `~/.ssh/known_hosts` no longer breaks every connection.** Lines with key types vcom
|
||||
cannot parse (e.g. OpenSSH 10 `ssh-mldsa44-ed25519`) are skipped with a warning in the log. A host recorded only
|
||||
with such a key is refused rather than silently trusted with a different key.
|
||||
- Host key types already recorded for a host are preferred in the handshake (like OpenSSH), so a server known only
|
||||
by its ed25519 key is no longer reported as "REMOTE HOST IDENTIFICATION HAS CHANGED".
|
||||
|
||||
### Crashes and races
|
||||
- Caret mode (`i` in the info pane) no longer panics without colors (`NO_COLOR`, dumb terminals).
|
||||
|
|
@ -34,7 +46,18 @@ Data-loss and crash fixes for v0.2.7 while the larger rework is in progress.
|
|||
- `q` closes the info pane, the filter or the selection first, and quits only from the plain browser; `q` no longer
|
||||
closes the SSH add-host form while typing.
|
||||
- `n` cancels yes/no dialogs, as their hints say.
|
||||
- Creating a directory that already exists reports an error instead of silent success.
|
||||
- Creating a directory that already exists reports an error instead of silent success, in local and SSH panes.
|
||||
- `j`, `k` and other letters can be typed in the filter (they used to move the cursor); arrows still navigate.
|
||||
- `?` can be typed in the SSH add-host form (e.g. in passwords); `F1` opens the form's help.
|
||||
|
||||
### Known issues
|
||||
- On a filesystem other than the one holding the home trash, delete still cannot use the trash
|
||||
(`$topdir/.Trash-$uid` is not supported yet): vcom offers permanent deletion instead.
|
||||
- `.trashinfo` files do not percent-encode `Path=` and `XDG_DATA_HOME` is ignored (the trash is always
|
||||
`~/.local/share/Trash`), so other tools may not restore some items; a broken symlink already in the trash can be
|
||||
replaced by a later item with the same name.
|
||||
|
||||
These are fixed by the new trash implementation of the rework.
|
||||
|
||||
### Development
|
||||
- In-process SSH/SFTP test server with a fault-injecting proxy (`internal/testutil/sshtest`), tree helpers
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import (
|
|||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
|
@ -341,7 +342,9 @@ func CreateArchive(ctx context.Context, sources []string, archivePath string, pr
|
|||
return fmt.Errorf("unsupported archive format: %s", filepath.Ext(archivePath))
|
||||
}
|
||||
|
||||
tmp, err := os.CreateTemp(filepath.Dir(archivePath), ".vcom-tmp-*-"+filepath.Base(archivePath))
|
||||
// Short temp name: a long but valid archive name plus a prefix would
|
||||
// exceed NAME_MAX (QA-7). CreateTemp makes it 0600 while it is written.
|
||||
tmp, err := os.CreateTemp(filepath.Dir(archivePath), ".vcom-tmp-*")
|
||||
if err != nil {
|
||||
return fmt.Errorf("create %s: %w", archivePath, err)
|
||||
}
|
||||
|
|
@ -351,7 +354,14 @@ func CreateArchive(ctx context.Context, sources []string, archivePath string, pr
|
|||
os.Remove(tmpPath)
|
||||
return err
|
||||
}
|
||||
if err := os.Chmod(tmpPath, 0o644); err != nil {
|
||||
// A replaced archive keeps its permissions (a private 0600 archive must
|
||||
// not become world-readable, QA-6); a new one gets 0666 minus umask,
|
||||
// as os.Create would.
|
||||
mode := 0o666 &^ processUmask()
|
||||
if st, err := os.Stat(archivePath); err == nil {
|
||||
mode = st.Mode().Perm()
|
||||
}
|
||||
if err := os.Chmod(tmpPath, mode); err != nil {
|
||||
os.Remove(tmpPath)
|
||||
return err
|
||||
}
|
||||
|
|
@ -726,3 +736,19 @@ func commonBaseDir(paths []string) string {
|
|||
}
|
||||
return base
|
||||
}
|
||||
|
||||
// processUmask reads the umask without changing it (syscall.Umask would
|
||||
// briefly change it for the whole process). Falls back to 022.
|
||||
func processUmask() os.FileMode {
|
||||
data, err := os.ReadFile("/proc/self/status")
|
||||
if err == nil {
|
||||
for _, line := range strings.Split(string(data), "\n") {
|
||||
if v, ok := strings.CutPrefix(line, "Umask:"); ok {
|
||||
if n, err := strconv.ParseUint(strings.TrimSpace(v), 8, 32); err == nil {
|
||||
return os.FileMode(n) & 0o777
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0o022
|
||||
}
|
||||
|
|
|
|||
395
internal/fs/qa_archive_trash_test.go
Normal file
395
internal/fs/qa_archive_trash_test.go
Normal file
|
|
@ -0,0 +1,395 @@
|
|||
package vfs
|
||||
|
||||
// QA (v0.2.8): independent checks of the stage-1 fixes in archive.go and
|
||||
// ops.go (U-P0-1 archive safety, U-P0-4 trash as default delete, MakeDir).
|
||||
// Tests that expose a still-open bug are skipped with "BUG QA-n" and are
|
||||
// described in plans/rework/05-qa-v0.2.8.md.
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"archive/zip"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"io"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func qaWrite(t *testing.T, p string, data string, mode os.FileMode) {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(p, []byte(data), mode); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Every format: archiving a file whose archive name equals its own name
|
||||
// into the same directory is refused and leaves the source intact.
|
||||
func TestQAArchiveIntoSourceDirAllFormats(t *testing.T) {
|
||||
cases := []struct{ name, format string }{
|
||||
{"data.zip", "zip"},
|
||||
{"data.tar", "tar"},
|
||||
{"data.tar", "tar.gz"}, // data.tar -> data.tar.gz: allowed, different file
|
||||
{"data.gz", "tar.gz"}, // data.gz -> data.tar.gz: allowed
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name+"->"+tc.format, func(t *testing.T) {
|
||||
d := t.TempDir()
|
||||
src := filepath.Join(d, tc.name)
|
||||
payload := strings.Repeat("z", 50000)
|
||||
qaWrite(t, src, payload, 0o644)
|
||||
arc := filepath.Join(d, ArchiveName([]string{src}, tc.format))
|
||||
err := CreateArchive(context.Background(), []string{src}, arc, nil)
|
||||
if arc == src {
|
||||
if err == nil {
|
||||
t.Fatal("archive equal to source must be refused")
|
||||
}
|
||||
} else if err != nil {
|
||||
t.Fatalf("archive %s of %s should work: %v", arc, src, err)
|
||||
}
|
||||
if b, _ := os.ReadFile(src); string(b) != payload {
|
||||
t.Fatalf("source changed (len %d)", len(b))
|
||||
}
|
||||
if left, _ := filepath.Glob(filepath.Join(d, ".vcom-tmp-*")); len(left) != 0 {
|
||||
t.Fatalf("temp files left: %v", left)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The produced archive must actually contain the source (zip, tar, tar.gz),
|
||||
// i.e. the temp+rename path did not break the formats.
|
||||
func TestQAArchiveContentsRoundTrip(t *testing.T) {
|
||||
for _, format := range []string{"zip", "tar", "tar.gz"} {
|
||||
t.Run(format, func(t *testing.T) {
|
||||
d, out := t.TempDir(), t.TempDir()
|
||||
qaWrite(t, filepath.Join(d, "proj", "a.txt"), "alpha", 0o644)
|
||||
qaWrite(t, filepath.Join(d, "proj", "sub", "б.txt"), "бета", 0o644)
|
||||
src := filepath.Join(d, "proj")
|
||||
arc := filepath.Join(out, ArchiveName([]string{src}, format))
|
||||
if err := CreateArchive(context.Background(), []string{src}, arc, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
names := qaListArchive(t, arc)
|
||||
joined := strings.Join(names, "\n")
|
||||
for _, want := range []string{"a.txt", "б.txt"} {
|
||||
if !strings.Contains(joined, want) {
|
||||
t.Fatalf("%s missing from %s: %v", want, arc, names)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func qaListArchive(t *testing.T, p string) []string {
|
||||
t.Helper()
|
||||
var names []string
|
||||
switch {
|
||||
case strings.HasSuffix(p, ".zip"):
|
||||
zr, err := zip.OpenReader(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer zr.Close()
|
||||
for _, f := range zr.File {
|
||||
names = append(names, f.Name)
|
||||
}
|
||||
default:
|
||||
f, err := os.Open(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
var r io.Reader = f
|
||||
if strings.HasSuffix(p, ".gz") {
|
||||
gz, err := gzip.NewReader(f)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r = gz
|
||||
}
|
||||
tr := tar.NewReader(r)
|
||||
for {
|
||||
h, err := tr.Next()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
names = append(names, h.Name)
|
||||
}
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
// Overwriting an existing archive after confirmation must not widen its
|
||||
// permissions: a private 0600 archive became world-readable 0644.
|
||||
func TestQAArchiveOverwriteKeepsPermissions(t *testing.T) {
|
||||
d, out := t.TempDir(), t.TempDir()
|
||||
qaWrite(t, filepath.Join(d, "secret.txt"), "pin 1234", 0o600)
|
||||
arc := filepath.Join(out, "secret.zip")
|
||||
qaWrite(t, arc, "old", 0o600)
|
||||
if err := CreateArchive(context.Background(), []string{filepath.Join(d, "secret.txt")}, arc, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st, err := os.Stat(arc)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if st.Mode().Perm() != 0o600 {
|
||||
t.Fatalf("existing 0600 archive replaced with mode %o", st.Mode().Perm())
|
||||
}
|
||||
}
|
||||
|
||||
// A long but valid file name (NAME_MAX is 255 bytes) can no longer be
|
||||
// archived: the temp name ".vcom-tmp-<rand>-<name>" exceeds NAME_MAX.
|
||||
func TestQAArchiveLongName(t *testing.T) {
|
||||
d, out := t.TempDir(), t.TempDir()
|
||||
base := strings.Repeat("n", 240)
|
||||
src := filepath.Join(d, base+".txt")
|
||||
qaWrite(t, src, "x", 0o644)
|
||||
arc := filepath.Join(out, ArchiveName([]string{src}, "zip")) // 244 bytes: valid
|
||||
if err := CreateArchive(context.Background(), []string{src}, arc, nil); err != nil {
|
||||
t.Fatalf("archive with a valid %d-byte name failed: %v", len(filepath.Base(arc)), err)
|
||||
}
|
||||
}
|
||||
|
||||
// A source that is a symlink to a directory, archived into that directory:
|
||||
// the link is resolved by nobody, so the check does not see the archive is
|
||||
// inside the (dereferenced) source. Make sure at least nothing is destroyed
|
||||
// and the archive does not contain itself.
|
||||
func TestQAArchiveSymlinkDirSourceIntoTarget(t *testing.T) {
|
||||
d := t.TempDir()
|
||||
proj := filepath.Join(d, "proj")
|
||||
qaWrite(t, filepath.Join(proj, "a.txt"), "alpha", 0o644)
|
||||
link := filepath.Join(d, "link")
|
||||
if err := os.Symlink(proj, link); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
arc := filepath.Join(proj, "link.tar")
|
||||
err := CreateArchive(context.Background(), []string{link}, arc, nil)
|
||||
if b, _ := os.ReadFile(filepath.Join(proj, "a.txt")); string(b) != "alpha" {
|
||||
t.Fatal("source content damaged")
|
||||
}
|
||||
if err == nil {
|
||||
for _, n := range qaListArchive(t, arc) {
|
||||
if strings.Contains(n, "link.tar") || strings.Contains(n, ".vcom-tmp") {
|
||||
t.Fatalf("archive contains itself: %v", n)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Cancelled archive into a directory with an existing archive: old archive
|
||||
// stays, no temp file (tar and tar.gz paths, the developer only tested zip).
|
||||
func TestQAArchiveCancelKeepsOldAllFormats(t *testing.T) {
|
||||
for _, format := range []string{"zip", "tar", "tar.gz"} {
|
||||
t.Run(format, func(t *testing.T) {
|
||||
d, out := t.TempDir(), t.TempDir()
|
||||
qaWrite(t, filepath.Join(d, "src", "f"), "x", 0o644)
|
||||
src := filepath.Join(d, "src")
|
||||
arc := filepath.Join(out, ArchiveName([]string{src}, format))
|
||||
qaWrite(t, arc, "OLD", 0o644)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
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("old archive replaced: %q", b)
|
||||
}
|
||||
if left, _ := filepath.Glob(filepath.Join(out, ".vcom-tmp-*")); len(left) != 0 {
|
||||
t.Fatalf("temp files left: %v", left)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// --- Trash (now the default delete) ---------------------------------------
|
||||
|
||||
func qaTrashHome(t *testing.T) string {
|
||||
t.Helper()
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
t.Setenv("XDG_DATA_HOME", filepath.Join(home, ".local", "share"))
|
||||
return filepath.Join(home, ".local", "share", "Trash")
|
||||
}
|
||||
|
||||
// Names with spaces and Cyrillic, and same-name collisions, all land in the
|
||||
// trash under distinct names with a matching .trashinfo.
|
||||
func TestQATrashNamesAndCollisions(t *testing.T) {
|
||||
trash := qaTrashHome(t)
|
||||
work := filepath.Join(os.Getenv("HOME"), "work") // same filesystem as HOME
|
||||
names := []string{"my file.txt", "отчёт 2026.txt"}
|
||||
for _, n := range names {
|
||||
qaWrite(t, filepath.Join(work, "a", n), "A "+n, 0o644)
|
||||
qaWrite(t, filepath.Join(work, "b", n), "B "+n, 0o644)
|
||||
}
|
||||
for _, sub := range []string{"a", "b"} {
|
||||
for _, n := range names {
|
||||
if err := MoveToTrash(filepath.Join(work, sub, n)); err != nil {
|
||||
t.Fatalf("MoveToTrash(%s/%s): %v", sub, n, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
files, _ := os.ReadDir(filepath.Join(trash, "files"))
|
||||
infos, _ := os.ReadDir(filepath.Join(trash, "info"))
|
||||
if len(files) != 4 || len(infos) != 4 {
|
||||
t.Fatalf("want 4 trashed files and 4 infos, got %d/%d", len(files), len(infos))
|
||||
}
|
||||
for _, f := range files {
|
||||
if _, err := os.Stat(filepath.Join(trash, "info", f.Name()+".trashinfo")); err != nil {
|
||||
t.Errorf("no trashinfo for %s", f.Name())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The XDG trash spec requires Path= in .trashinfo to be percent-encoded
|
||||
// (RFC 2396). Unencoded spaces/Cyrillic/newlines break restore in other
|
||||
// tools (gio, trash-cli) — a newline in a file name corrupts the info file.
|
||||
func TestQATrashInfoPathEncoded(t *testing.T) {
|
||||
t.Skip("BUG QA-5: .trashinfo Path= is written raw, not percent-encoded as the XDG trash spec requires (ops.go:323)")
|
||||
trash := qaTrashHome(t)
|
||||
work := filepath.Join(os.Getenv("HOME"), "work")
|
||||
p := filepath.Join(work, "my file\nx.txt")
|
||||
qaWrite(t, p, "x", 0o644)
|
||||
if err := MoveToTrash(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err := os.ReadFile(filepath.Join(trash, "info", "my file\nx.txt.trashinfo"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var pathLine string
|
||||
for _, l := range strings.Split(string(b), "\n") {
|
||||
if strings.HasPrefix(l, "Path=") {
|
||||
pathLine = strings.TrimPrefix(l, "Path=")
|
||||
}
|
||||
}
|
||||
got, err := url.PathUnescape(pathLine)
|
||||
if err != nil || got != p {
|
||||
t.Fatalf("Path=%q does not decode to %q (err %v)", pathLine, p, err)
|
||||
}
|
||||
}
|
||||
|
||||
// XDG_DATA_HOME must be honoured ($XDG_DATA_HOME/Trash), otherwise vcom and
|
||||
// the desktop use different trash cans.
|
||||
func TestQATrashHonoursXDGDataHome(t *testing.T) {
|
||||
t.Skip("BUG QA-5: MoveToTrash ignores XDG_DATA_HOME and always uses ~/.local/share/Trash (ops.go:286)")
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
xdg := filepath.Join(home, "xdgdata")
|
||||
t.Setenv("XDG_DATA_HOME", xdg)
|
||||
p := filepath.Join(home, "f.txt")
|
||||
qaWrite(t, p, "x", 0o644)
|
||||
if err := MoveToTrash(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(xdg, "Trash", "files", "f.txt")); err != nil {
|
||||
t.Fatalf("file not in $XDG_DATA_HOME/Trash: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// otherDevice returns a writable directory on a different filesystem than
|
||||
// home, or "" if none is available.
|
||||
func otherDevice(t *testing.T, home string) string {
|
||||
t.Helper()
|
||||
var hs syscall.Stat_t
|
||||
if err := syscall.Stat(home, &hs); err != nil {
|
||||
return ""
|
||||
}
|
||||
wd, _ := os.Getwd()
|
||||
for _, cand := range []string{"/dev/shm", os.Getenv("XDG_RUNTIME_DIR"), "/var/tmp", wd} {
|
||||
if cand == "" {
|
||||
continue
|
||||
}
|
||||
var cs syscall.Stat_t
|
||||
if err := syscall.Stat(cand, &cs); err != nil || cs.Dev == hs.Dev {
|
||||
continue
|
||||
}
|
||||
dir, err := os.MkdirTemp(cand, ".vcom-qa-*")
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
t.Cleanup(func() { os.RemoveAll(dir) })
|
||||
return dir
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// With trash as the default, deleting a file on another filesystem than
|
||||
// $HOME (/tmp on tmpfs, /mnt, USB, a second disk) must still work: the spec
|
||||
// uses $topdir/.Trash-$uid or a copy. Here MoveToTrash only does os.Rename
|
||||
// and fails with EXDEV.
|
||||
func TestQATrashCrossDevice(t *testing.T) {
|
||||
t.Skip("BUG QA-1: MoveToTrash fails with EXDEV for files on another filesystem than $HOME; with trash now the default, F8+Enter cannot delete files in /tmp, /mnt, USB disks (ops.go:312)")
|
||||
home := qaTrashHome(t)
|
||||
_ = home
|
||||
dir := otherDevice(t, os.Getenv("HOME"))
|
||||
if dir == "" {
|
||||
t.Skip("no second filesystem available")
|
||||
}
|
||||
p := filepath.Join(dir, "on-other-fs.txt")
|
||||
qaWrite(t, p, "x", 0o644)
|
||||
if err := MoveToTrash(p); err != nil {
|
||||
t.Fatalf("MoveToTrash across filesystems: %v", err)
|
||||
}
|
||||
if _, err := os.Lstat(p); !os.IsNotExist(err) {
|
||||
t.Fatal("file still in place")
|
||||
}
|
||||
}
|
||||
|
||||
// A trashed broken symlink with the same name must not be silently replaced
|
||||
// by the next trashed item (collision check uses Stat, which follows links).
|
||||
func TestQATrashCollisionWithBrokenSymlink(t *testing.T) {
|
||||
t.Skip("BUG QA-8: trash collision check uses os.Stat; a broken symlink already in Trash/files is overwritten by the next item with that name (ops.go:303)")
|
||||
trash := qaTrashHome(t)
|
||||
work := filepath.Join(os.Getenv("HOME"), "work")
|
||||
if err := os.MkdirAll(work, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
link := filepath.Join(work, "x")
|
||||
if err := os.Symlink("/nonexistent/target", link); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := MoveToTrash(link); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
qaWrite(t, link, "file now", 0o644)
|
||||
if err := MoveToTrash(link); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
files, _ := os.ReadDir(filepath.Join(trash, "files"))
|
||||
if len(files) != 2 {
|
||||
t.Fatalf("want 2 items in trash, got %d (first one overwritten)", len(files))
|
||||
}
|
||||
}
|
||||
|
||||
// --- MakeDir ---------------------------------------------------------------
|
||||
|
||||
func TestQAMakeDirEdgeCases(t *testing.T) {
|
||||
d := t.TempDir()
|
||||
if _, err := MakeDir(d, "a/b"); err != nil {
|
||||
t.Fatalf("nested name: %v", err)
|
||||
}
|
||||
if _, err := MakeDir(d, "a/b"); err == nil {
|
||||
t.Fatal("existing nested dir must error")
|
||||
}
|
||||
if _, err := MakeDir(d, "a"); err == nil {
|
||||
t.Fatal("existing parent must error")
|
||||
}
|
||||
qaWrite(t, filepath.Join(d, "file"), "x", 0o644)
|
||||
if _, err := MakeDir(d, "file"); err == nil {
|
||||
t.Fatal("name of an existing file must error")
|
||||
}
|
||||
if _, err := MakeDir(d, "папка с пробелом"); err != nil {
|
||||
t.Fatalf("cyrillic name: %v", err)
|
||||
}
|
||||
}
|
||||
26
internal/fs/qa_fixes_test.go
Normal file
26
internal/fs/qa_fixes_test.go
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
package vfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// QA-6: a new archive gets 0666 minus umask (as os.Create would), not the
|
||||
// 0600 of the temp file and not a fixed 0644.
|
||||
func TestNewArchiveModeFollowsUmask(t *testing.T) {
|
||||
d, out := t.TempDir(), t.TempDir()
|
||||
qaWrite(t, filepath.Join(d, "a.txt"), "x", 0o644)
|
||||
arc := filepath.Join(out, "a.tar")
|
||||
if err := CreateArchive(context.Background(), []string{filepath.Join(d, "a.txt")}, arc, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st, err := os.Stat(arc)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if want := 0o666 &^ processUmask(); st.Mode().Perm() != want {
|
||||
t.Fatalf("new archive mode %o, want %o", st.Mode().Perm(), want)
|
||||
}
|
||||
}
|
||||
|
|
@ -87,7 +87,7 @@ func Connect(host SSHHost) (*SSHClient, error) {
|
|||
return nil, fmt.Errorf("ssh auth: %w", err)
|
||||
}
|
||||
|
||||
hostKeyCB, err := tofuHostKeyCallback()
|
||||
hostKeyCB, hostKeyAlgos, err := tofuHostKeyCallback(host.Addr())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("host key verification: %w", err)
|
||||
}
|
||||
|
|
@ -98,10 +98,11 @@ func Connect(host SSHHost) (*SSHClient, error) {
|
|||
}
|
||||
|
||||
config := &ssh.ClientConfig{
|
||||
User: user,
|
||||
Auth: authMethods,
|
||||
HostKeyCallback: hostKeyCB,
|
||||
Timeout: 15 * time.Second,
|
||||
User: user,
|
||||
Auth: authMethods,
|
||||
HostKeyCallback: hostKeyCB,
|
||||
HostKeyAlgorithms: hostKeyAlgos,
|
||||
Timeout: 15 * time.Second,
|
||||
}
|
||||
|
||||
addr := host.Addr()
|
||||
|
|
@ -154,30 +155,33 @@ func Connect(host SSHHost) (*SSHClient, error) {
|
|||
// previously recorded entry is rejected outright, since that's the signature
|
||||
// of a man-in-the-middle attack or a legitimately reissued key that the user
|
||||
// must verify and update manually (e.g. via `ssh-keygen -R <host>`).
|
||||
func tofuHostKeyCallback() (ssh.HostKeyCallback, error) {
|
||||
//
|
||||
// Lines of known_hosts that cannot be parsed (unknown key types) are skipped,
|
||||
// see knownHostsDB. It also returns the host key algorithms to offer for addr.
|
||||
func tofuHostKeyCallback(addr string) (ssh.HostKeyCallback, []string, error) {
|
||||
khPath := KnownHostsPath()
|
||||
if khPath == "" {
|
||||
return nil, fmt.Errorf("cannot determine known_hosts path")
|
||||
return nil, nil, fmt.Errorf("cannot determine known_hosts path")
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(filepath.Dir(khPath), 0o700); err != nil {
|
||||
return nil, fmt.Errorf("create ssh dir: %w", err)
|
||||
return nil, nil, fmt.Errorf("create ssh dir: %w", err)
|
||||
}
|
||||
if _, err := os.Stat(khPath); os.IsNotExist(err) {
|
||||
f, err := os.OpenFile(khPath, os.O_CREATE|os.O_WRONLY, 0o600)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create known_hosts: %w", err)
|
||||
return nil, nil, fmt.Errorf("create known_hosts: %w", err)
|
||||
}
|
||||
f.Close()
|
||||
}
|
||||
|
||||
verify, err := knownhosts.New(khPath)
|
||||
db, err := loadKnownHosts(khPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse known_hosts: %w", err)
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
return func(hostname string, remote net.Addr, key ssh.PublicKey) error {
|
||||
err := verify(hostname, remote, key)
|
||||
err := db.verify(hostname, remote, key)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
|
@ -187,6 +191,10 @@ func tofuHostKeyCallback() (ssh.HostKeyCallback, error) {
|
|||
return fmt.Errorf("REMOTE HOST IDENTIFICATION HAS CHANGED for %s! This may indicate a man-in-the-middle attack, or the server's key was legitimately reissued. Refusing to connect; run `ssh-keygen -R %s` to remove the stale entry once you've verified the new key: %w", hostname, hostname, err)
|
||||
}
|
||||
|
||||
if db.unsupportedOnly(hostname) {
|
||||
return fmt.Errorf("the host key of %s is recorded in %s only with a key type vcom does not support yet; refusing to trust a different key automatically. Add a supported key for it (e.g. from `ssh-keyscan -t ed25519`) after verifying it: %w", hostname, khPath, err)
|
||||
}
|
||||
|
||||
// Unknown host: trust on first use and remember the key.
|
||||
line := knownhosts.Line([]string{knownhosts.Normalize(hostname)}, key)
|
||||
f, ferr := os.OpenFile(khPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
|
||||
|
|
@ -198,7 +206,7 @@ func tofuHostKeyCallback() (ssh.HostKeyCallback, error) {
|
|||
return fmt.Errorf("cannot save host key for %s: %w", hostname, werr)
|
||||
}
|
||||
return nil
|
||||
}, nil
|
||||
}, db.hostKeyAlgorithms(addr), nil
|
||||
}
|
||||
|
||||
// sshAgentAuth connects to the running ssh-agent (via SSH_AUTH_SOCK) and
|
||||
|
|
@ -391,6 +399,26 @@ func (c *SSHClient) Mkdir(dirPath string) error {
|
|||
return c.sftpCli.Mkdir(dirPath)
|
||||
}
|
||||
|
||||
// MkdirNew creates dirPath (and missing parents) and fails if dirPath
|
||||
// already exists, like the local MakeDir: F7 with a taken name must report
|
||||
// an error (QA-10).
|
||||
func (c *SSHClient) MkdirNew(dirPath string) error {
|
||||
if c.unusable() {
|
||||
return errNotConnected
|
||||
}
|
||||
if _, err := c.sftpCli.Lstat(dirPath); err == nil {
|
||||
return &os.PathError{Op: "mkdir", Path: dirPath, Err: os.ErrExist}
|
||||
} else if !os.IsNotExist(err) {
|
||||
return err
|
||||
}
|
||||
if parent := path.Dir(dirPath); parent != dirPath && parent != "." {
|
||||
if err := c.MkdirAll(parent); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return c.sftpCli.Mkdir(dirPath)
|
||||
}
|
||||
|
||||
// Remove deletes a remote file.
|
||||
func (c *SSHClient) Remove(filePath string) error {
|
||||
if c.unusable() {
|
||||
|
|
@ -518,10 +546,13 @@ func (c *SSHClient) SameHostAs(other *SSHClient) bool {
|
|||
|
||||
// RemoveRecursive recursively deletes a remote file or directory.
|
||||
// For directories, it walks and removes all children first.
|
||||
func (c *SSHClient) RemoveRecursive(path string) error {
|
||||
func (c *SSHClient) RemoveRecursive(target string) error {
|
||||
if c.unusable() {
|
||||
return errNotConnected
|
||||
}
|
||||
// Clean first: lstat("link/") resolves the link on POSIX servers, and
|
||||
// the target's contents would be deleted (QA-9).
|
||||
path := path.Clean(target)
|
||||
|
||||
// Lstat, not Stat: a symlink to a directory must be removed as a link.
|
||||
// Following it would delete the contents of the link's target (N-P0-3).
|
||||
|
|
|
|||
202
internal/fs/remote/knownhosts.go
Normal file
202
internal/fs/remote/knownhosts.go
Normal file
|
|
@ -0,0 +1,202 @@
|
|||
package remote
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/ed25519"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
"golang.org/x/crypto/ssh/knownhosts"
|
||||
)
|
||||
|
||||
// knownHostsDB is a tolerant view of ~/.ssh/known_hosts (QA-11).
|
||||
//
|
||||
// knownhosts.New rejects the whole file when a single line cannot be parsed,
|
||||
// e.g. a key type x/crypto/ssh does not implement such as OpenSSH 10's
|
||||
// "ssh-mldsa44-ed25519". OpenSSH skips such lines, and so do we: they are
|
||||
// left out (with a warning in the log) and the rest of the file is used.
|
||||
//
|
||||
// A host whose skipped lines are its only record is not silently re-trusted
|
||||
// on first use: unsupported records which apply to it make the unknown-host
|
||||
// path refuse instead, since we cannot check the key the user already
|
||||
// accepted.
|
||||
type knownHostsDB struct {
|
||||
verify ssh.HostKeyCallback
|
||||
// unsupported matches the host patterns of skipped lines (with a
|
||||
// placeholder key); nil when nothing was skipped.
|
||||
unsupported ssh.HostKeyCallback
|
||||
// hasCA: the file has @cert-authority lines, so known keys of a host
|
||||
// cannot be told apart from CA keys; host key algorithms are then left
|
||||
// at the x/crypto defaults.
|
||||
hasCA bool
|
||||
}
|
||||
|
||||
// placeholderKey never matches a real host key; it is used to probe which
|
||||
// keys are recorded for a host and as the key of placeholder lines.
|
||||
var placeholderKey = func() ssh.PublicKey {
|
||||
priv := ed25519.NewKeyFromSeed(make([]byte, ed25519.SeedSize))
|
||||
pub, err := ssh.NewPublicKey(priv.Public())
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return pub
|
||||
}()
|
||||
|
||||
var probeRemote = &net.TCPAddr{IP: net.IPv4zero, Port: 0}
|
||||
|
||||
// loadKnownHosts reads khPath, dropping lines knownhosts cannot parse.
|
||||
func loadKnownHosts(khPath string) (*knownHostsDB, error) {
|
||||
data, err := os.ReadFile(khPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read known_hosts: %w", err)
|
||||
}
|
||||
lines := strings.Split(string(data), "\n")
|
||||
|
||||
verify, skipped, err := parseTolerant(lines, khPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
db := &knownHostsDB{verify: verify}
|
||||
for _, l := range lines {
|
||||
if strings.HasPrefix(strings.TrimSpace(l), "@cert-authority") {
|
||||
db.hasCA = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
var placeholders []string
|
||||
marshalled := strings.TrimSpace(string(ssh.MarshalAuthorizedKey(placeholderKey)))
|
||||
for _, n := range skipped {
|
||||
fields := strings.Fields(lines[n])
|
||||
if len(fields) == 0 || strings.HasPrefix(fields[0], "@") {
|
||||
// @revoked / @cert-authority with an unsupported key: such a
|
||||
// key can never be negotiated, nothing to protect.
|
||||
continue
|
||||
}
|
||||
placeholders = append(placeholders, fields[0]+" "+marshalled)
|
||||
}
|
||||
if len(placeholders) > 0 {
|
||||
unsupported, _, err := parseTolerant(placeholders, "")
|
||||
if err == nil {
|
||||
db.unsupported = unsupported
|
||||
}
|
||||
}
|
||||
return db, nil
|
||||
}
|
||||
|
||||
// parseTolerant feeds lines to knownhosts.New, commenting out every line it
|
||||
// rejects, and returns the callback and the indexes of the rejected lines.
|
||||
// origin names the file in log warnings ("" = no warnings).
|
||||
func parseTolerant(lines []string, origin string) (ssh.HostKeyCallback, []int, error) {
|
||||
work := make([]string, len(lines))
|
||||
copy(work, lines)
|
||||
var skipped []int
|
||||
skip := func(i int, why string) {
|
||||
if origin != "" {
|
||||
log.Printf("[SSH] %s:%d: skipping known_hosts line: %s", origin, i+1, why)
|
||||
}
|
||||
work[i] = "#"
|
||||
skipped = append(skipped, i)
|
||||
}
|
||||
for i, l := range work {
|
||||
// bufio.Scanner in knownhosts fails the whole file on an over-long line.
|
||||
if len(l) >= bufio.MaxScanTokenSize-1 {
|
||||
skip(i, "line too long")
|
||||
}
|
||||
}
|
||||
|
||||
tmp, err := os.CreateTemp("", "vcom-known_hosts-*")
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("parse known_hosts: %w", err)
|
||||
}
|
||||
tmpPath := tmp.Name()
|
||||
tmp.Close()
|
||||
defer os.Remove(tmpPath)
|
||||
|
||||
prefix := "knownhosts: " + tmpPath + ":"
|
||||
for attempt := 0; attempt <= len(work); attempt++ {
|
||||
if err := os.WriteFile(tmpPath, []byte(strings.Join(work, "\n")+"\n"), 0o600); err != nil {
|
||||
return nil, nil, fmt.Errorf("parse known_hosts: %w", err)
|
||||
}
|
||||
cb, err := knownhosts.New(tmpPath)
|
||||
if err == nil {
|
||||
return cb, skipped, nil
|
||||
}
|
||||
msg := err.Error()
|
||||
rest, ok := strings.CutPrefix(msg, prefix)
|
||||
if !ok {
|
||||
return nil, nil, fmt.Errorf("parse known_hosts: %w", err)
|
||||
}
|
||||
numStr, why, _ := strings.Cut(rest, ":")
|
||||
n, perr := strconv.Atoi(numStr)
|
||||
if perr != nil || n < 1 || n > len(work) || work[n-1] == "#" {
|
||||
return nil, nil, fmt.Errorf("parse known_hosts: %w", err)
|
||||
}
|
||||
skip(n-1, strings.TrimSpace(why))
|
||||
}
|
||||
return nil, nil, errors.New("parse known_hosts: too many invalid lines")
|
||||
}
|
||||
|
||||
// unsupportedOnly reports whether hostname has records only in lines that
|
||||
// were skipped (so a new key must not be trusted on first use).
|
||||
func (db *knownHostsDB) unsupportedOnly(hostname string) bool {
|
||||
if db.unsupported == nil {
|
||||
return false
|
||||
}
|
||||
var keyErr *knownhosts.KeyError
|
||||
err := db.unsupported(hostname, probeRemote, placeholderKey)
|
||||
if err == nil {
|
||||
return true
|
||||
}
|
||||
return errors.As(err, &keyErr) && len(keyErr.Want) > 0
|
||||
}
|
||||
|
||||
// plainHostKeyAlgos is what the client can verify without certificates.
|
||||
var plainHostKeyAlgos = []string{
|
||||
ssh.KeyAlgoED25519,
|
||||
ssh.KeyAlgoECDSA256, ssh.KeyAlgoECDSA384, ssh.KeyAlgoECDSA521,
|
||||
ssh.KeyAlgoRSASHA512, ssh.KeyAlgoRSASHA256, ssh.KeyAlgoRSA,
|
||||
}
|
||||
|
||||
// hostKeyAlgorithms returns the host key algorithms to offer for addr:
|
||||
// those of keys already recorded for it first (like OpenSSH), then the rest
|
||||
// of the plain algorithms. Without that, x/crypto prefers ECDSA, and a
|
||||
// server known only by its ed25519 key looks like a changed host key.
|
||||
// Only algorithms x/crypto implements are returned, never the type of a
|
||||
// skipped line. nil means "use the defaults".
|
||||
func (db *knownHostsDB) hostKeyAlgorithms(addr string) []string {
|
||||
if db.hasCA {
|
||||
return nil
|
||||
}
|
||||
var keyErr *knownhosts.KeyError
|
||||
if err := db.verify(addr, probeRemote, placeholderKey); !errors.As(err, &keyErr) || len(keyErr.Want) == 0 {
|
||||
return nil
|
||||
}
|
||||
known := map[string]bool{}
|
||||
for _, k := range keyErr.Want {
|
||||
t := k.Key.Type()
|
||||
if t == ssh.KeyAlgoRSA {
|
||||
known[ssh.KeyAlgoRSASHA512] = true
|
||||
known[ssh.KeyAlgoRSASHA256] = true
|
||||
}
|
||||
known[t] = true
|
||||
}
|
||||
var first, rest []string
|
||||
for _, a := range plainHostKeyAlgos {
|
||||
if known[a] {
|
||||
first = append(first, a)
|
||||
} else {
|
||||
rest = append(rest, a)
|
||||
}
|
||||
}
|
||||
if len(first) == 0 {
|
||||
return nil
|
||||
}
|
||||
return append(first, rest...)
|
||||
}
|
||||
146
internal/fs/remote/knownhosts_test.go
Normal file
146
internal/fs/remote/knownhosts_test.go
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
package remote
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
"golang.org/x/crypto/ssh/knownhosts"
|
||||
|
||||
"vcom/internal/testutil/sshtest"
|
||||
)
|
||||
|
||||
// Unsupported OpenSSH 10 post-quantum key (QA-11). The blob only has to look
|
||||
// like base64; x/crypto rejects it by its algorithm name.
|
||||
const mldsaKey = "ssh-mldsa44-ed25519 AAAAFHNzaC1tbGRzYTQ0LWVkMjU1MTkAAAAA"
|
||||
|
||||
func writeKnownHosts(t *testing.T, lines ...string) string {
|
||||
t.Helper()
|
||||
p := filepath.Join(os.Getenv("HOME"), ".ssh", "known_hosts")
|
||||
if err := os.WriteFile(p, []byte(strings.Join(lines, "\n")+"\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func connectTo(srv *sshtest.Server) (*SSHClient, error) {
|
||||
return Connect(SSHHost{Name: "h", HostName: "127.0.0.1", Port: srv.Port(), User: "u", Password: srv.Password})
|
||||
}
|
||||
|
||||
func hostPattern(srv *sshtest.Server) string {
|
||||
return knownhosts.Normalize(fmt.Sprintf("127.0.0.1:%s", srv.Port()))
|
||||
}
|
||||
|
||||
// Unparseable lines for other hosts (unknown key type, garbage, bad hash)
|
||||
// are skipped; the connection proceeds and the new key is recorded.
|
||||
func TestKnownHostsSkipsUnparseableLines(t *testing.T) {
|
||||
sshtest.IsolatedHome(t)
|
||||
srv := sshtest.Start(t, sshtest.Options{})
|
||||
kh := writeKnownHosts(t,
|
||||
"# comment",
|
||||
"otherhost "+mldsaKey,
|
||||
"garbage-without-key",
|
||||
"|2|bad|hash ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl",
|
||||
"@revoked * "+mldsaKey,
|
||||
)
|
||||
c, err := connectTo(srv)
|
||||
if err != nil {
|
||||
t.Fatalf("connect: %v", err)
|
||||
}
|
||||
c.Close()
|
||||
data, _ := os.ReadFile(kh)
|
||||
if !strings.Contains(string(data), "otherhost "+mldsaKey) {
|
||||
t.Fatal("skipped lines must stay in known_hosts untouched")
|
||||
}
|
||||
if !strings.Contains(string(data), hostPattern(srv)+" ") {
|
||||
t.Fatalf("new host key was not recorded:\n%s", data)
|
||||
}
|
||||
// Second connection verifies against the recorded key.
|
||||
c, err = connectTo(srv)
|
||||
if err != nil {
|
||||
t.Fatalf("reconnect: %v", err)
|
||||
}
|
||||
c.Close()
|
||||
}
|
||||
|
||||
// The maintainer's case: the host is recorded with an unsupported PQ key and
|
||||
// with its ed25519 key only. The server also has an ECDSA key, which
|
||||
// x/crypto would prefer by default and then report as a changed key; the
|
||||
// recorded algorithm must be negotiated instead.
|
||||
func TestKnownHostsPrefersRecordedAlgorithm(t *testing.T) {
|
||||
sshtest.IsolatedHome(t)
|
||||
ed, ec := sshtest.GenKeys(t)
|
||||
srv := sshtest.Start(t, sshtest.Options{HostKeys: []ssh.Signer{ed, ec}})
|
||||
writeKnownHosts(t,
|
||||
hostPattern(srv)+" "+mldsaKey,
|
||||
knownhosts.Line([]string{hostPattern(srv)}, ed.PublicKey()),
|
||||
)
|
||||
c, err := connectTo(srv)
|
||||
if err != nil {
|
||||
t.Fatalf("connect: %v", err)
|
||||
}
|
||||
c.Close()
|
||||
}
|
||||
|
||||
// A recorded key of a type we cannot check must not be replaced silently
|
||||
// by trust-on-first-use of another key.
|
||||
func TestKnownHostsUnsupportedOnlyRefuses(t *testing.T) {
|
||||
sshtest.IsolatedHome(t)
|
||||
srv := sshtest.Start(t, sshtest.Options{})
|
||||
kh := writeKnownHosts(t, hostPattern(srv)+" "+mldsaKey)
|
||||
if c, err := connectTo(srv); err == nil {
|
||||
c.Close()
|
||||
t.Fatal("connected although the only recorded key is of an unsupported type")
|
||||
} else if !strings.Contains(err.Error(), "does not support") {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
data, _ := os.ReadFile(kh)
|
||||
if strings.Count(string(data), "\n") != 1 {
|
||||
t.Fatalf("known_hosts modified:\n%s", data)
|
||||
}
|
||||
}
|
||||
|
||||
// A changed key is still refused when the file also has unsupported lines.
|
||||
func TestKnownHostsMismatchStillRefused(t *testing.T) {
|
||||
sshtest.IsolatedHome(t)
|
||||
srv := sshtest.Start(t, sshtest.Options{})
|
||||
other, _ := sshtest.GenKeys(t)
|
||||
writeKnownHosts(t,
|
||||
"otherhost "+mldsaKey,
|
||||
knownhosts.Line([]string{hostPattern(srv)}, other.PublicKey()),
|
||||
)
|
||||
if c, err := connectTo(srv); err == nil {
|
||||
c.Close()
|
||||
t.Fatal("connected with a mismatching recorded key")
|
||||
} else if !strings.Contains(err.Error(), "HAS CHANGED") {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHostKeyAlgorithmsNeverUnsupported(t *testing.T) {
|
||||
sshtest.IsolatedHome(t)
|
||||
ed, _ := sshtest.GenKeys(t)
|
||||
kh := writeKnownHosts(t,
|
||||
"h.example "+mldsaKey,
|
||||
knownhosts.Line([]string{"h.example"}, ed.PublicKey()),
|
||||
)
|
||||
db, err := loadKnownHosts(kh)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
algos := db.hostKeyAlgorithms("h.example:22")
|
||||
if len(algos) == 0 || algos[0] != ssh.KeyAlgoED25519 {
|
||||
t.Fatalf("recorded algorithm not first: %v", algos)
|
||||
}
|
||||
for _, a := range algos {
|
||||
if strings.Contains(a, "mldsa") {
|
||||
t.Fatalf("unsupported algorithm offered: %v", algos)
|
||||
}
|
||||
}
|
||||
if got := db.hostKeyAlgorithms("unknown.example:22"); got != nil {
|
||||
t.Fatalf("unknown host: want defaults, got %v", got)
|
||||
}
|
||||
}
|
||||
50
internal/fs/remote/qa_fixes_test.go
Normal file
50
internal/fs/remote/qa_fixes_test.go
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
package remote
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// QA-10: MkdirNew creates missing parents but refuses an existing name
|
||||
// (directory, file or symlink).
|
||||
func TestMkdirNew(t *testing.T) {
|
||||
_, c, dir := setup(t)
|
||||
nested := filepath.Join(dir, "a", "b")
|
||||
if err := c.MkdirNew(nested); err != nil {
|
||||
t.Fatalf("nested mkdir: %v", err)
|
||||
}
|
||||
if fi, err := os.Stat(nested); err != nil || !fi.IsDir() {
|
||||
t.Fatalf("not created: %v", err)
|
||||
}
|
||||
writeFile(t, filepath.Join(dir, "file"), 1, 0o644)
|
||||
if err := os.Symlink("/nonexistent", filepath.Join(dir, "broken")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, n := range []string{"a", "a/b", "file", "broken"} {
|
||||
if err := c.MkdirNew(filepath.Join(dir, n)); !errors.Is(err, os.ErrExist) {
|
||||
t.Errorf("MkdirNew(%s) = %v, want ErrExist", n, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// QA-9: a path with "/." or "//" variants of the link name is cleaned too.
|
||||
func TestRemoveRecursiveCleansPath(t *testing.T) {
|
||||
_, c, dir := setup(t)
|
||||
target := filepath.Join(dir, "target")
|
||||
writeFile(t, filepath.Join(target, "keep"), 10, 0o644)
|
||||
link := filepath.Join(dir, "link")
|
||||
if err := os.Symlink(target, link); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := c.RemoveRecursive(link + "/."); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Lstat(link); !os.IsNotExist(err) {
|
||||
t.Fatal("link not removed")
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(target, "keep")); err != nil {
|
||||
t.Fatal("target contents deleted")
|
||||
}
|
||||
}
|
||||
176
internal/fs/remote/qa_remote_test.go
Normal file
176
internal/fs/remote/qa_remote_test.go
Normal file
|
|
@ -0,0 +1,176 @@
|
|||
package remote
|
||||
|
||||
// QA (v0.2.8): independent checks of N-P0-3 (RemoveRecursive never follows
|
||||
// symlinks) and N-P0-8 (Close is safe under concurrent use, refcount).
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestQARemoveRecursiveSymlinkVariants(t *testing.T) {
|
||||
_, c, dir := setup(t)
|
||||
target := filepath.Join(dir, "target")
|
||||
writeFile(t, filepath.Join(target, "keep.txt"), 10, 0o644)
|
||||
file := filepath.Join(dir, "file.txt")
|
||||
writeFile(t, file, 10, 0o644)
|
||||
|
||||
mk := func(name, to string) string {
|
||||
p := filepath.Join(dir, name)
|
||||
if err := os.Symlink(to, p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return p
|
||||
}
|
||||
cases := map[string]string{
|
||||
"broken": mk("broken", filepath.Join(dir, "nowhere")),
|
||||
"to-file": mk("to-file", file),
|
||||
"relative": mk("relative", "target"),
|
||||
"to-parent": mk("to-parent", ".."),
|
||||
}
|
||||
for name, p := range cases {
|
||||
if err := c.RemoveRecursive(p); err != nil {
|
||||
t.Errorf("%s: RemoveRecursive: %v", name, err)
|
||||
}
|
||||
if _, err := os.Lstat(p); !os.IsNotExist(err) {
|
||||
t.Errorf("%s: link not removed", name)
|
||||
}
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(target, "keep.txt")); err != nil {
|
||||
t.Fatalf("target content removed: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(file); err != nil {
|
||||
t.Fatalf("link target file removed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A directory containing symlinks to a sibling directory and to a file
|
||||
// outside: only the links go, targets survive.
|
||||
func TestQARemoveRecursiveDirWithOutsideLinks(t *testing.T) {
|
||||
_, c, dir := setup(t)
|
||||
outside := filepath.Join(dir, "outside")
|
||||
writeFile(t, filepath.Join(outside, "a.txt"), 10, 0o644)
|
||||
writeFile(t, filepath.Join(outside, "b.txt"), 10, 0o644)
|
||||
victim := filepath.Join(dir, "victim")
|
||||
writeFile(t, filepath.Join(victim, "own.txt"), 10, 0o644)
|
||||
if err := os.MkdirAll(filepath.Join(victim, "deep", "deeper"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(outside, filepath.Join(victim, "deep", "deeper", "dirlink")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(filepath.Join(outside, "b.txt"), filepath.Join(victim, "filelink")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := c.RemoveRecursive(victim); err != nil {
|
||||
t.Fatalf("RemoveRecursive: %v", err)
|
||||
}
|
||||
if _, err := os.Lstat(victim); !os.IsNotExist(err) {
|
||||
t.Fatal("victim dir still exists")
|
||||
}
|
||||
for _, f := range []string{"a.txt", "b.txt"} {
|
||||
if _, err := os.Stat(filepath.Join(outside, f)); err != nil {
|
||||
t.Fatalf("outside/%s removed through a link: %v", f, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// "link/" (trailing slash) makes lstat resolve the link on POSIX servers.
|
||||
// The UI never builds such paths today, but RemoveRecursive is a public
|
||||
// helper: with a trailing slash it still empties the target.
|
||||
func TestQARemoveRecursiveSymlinkTrailingSlash(t *testing.T) {
|
||||
_, c, dir := setup(t)
|
||||
target := filepath.Join(dir, "target")
|
||||
writeFile(t, filepath.Join(target, "keep.txt"), 10, 0o644)
|
||||
link := filepath.Join(dir, "link")
|
||||
if err := os.Symlink(target, link); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = c.RemoveRecursive(link + "/")
|
||||
if _, err := os.Stat(filepath.Join(target, "keep.txt")); err != nil {
|
||||
t.Fatalf("target content removed via link/: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Close while uploads and downloads are streaming: errors, no panic, no race.
|
||||
func TestQACloseDuringTransfers(t *testing.T) {
|
||||
_, c, dir := setup(t)
|
||||
src := filepath.Join(dir, "big.bin")
|
||||
writeFile(t, src, 4<<20, 0o644)
|
||||
var wg sync.WaitGroup
|
||||
panics := make(chan any, 16)
|
||||
for i := 0; i < 3; i++ {
|
||||
wg.Add(2)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
panics <- r
|
||||
}
|
||||
}()
|
||||
_ = c.CopyFileToRemote(src, filepath.Join(dir, "up", "u"+string(rune('0'+i))))
|
||||
}(i)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
panics <- r
|
||||
}
|
||||
}()
|
||||
_ = c.CopyFileFromRemote(src, filepath.Join(dir, "down", "d"+string(rune('0'+i))))
|
||||
_ = c.RemoveRecursive(filepath.Join(dir, "up"))
|
||||
_ = c.ExecWithProgress("true", func(string) {})
|
||||
_ = c.MkdirAll(filepath.Join(dir, "m", "n"))
|
||||
}(i)
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
var cw sync.WaitGroup
|
||||
for i := 0; i < 3; i++ {
|
||||
cw.Add(1)
|
||||
go func() { defer cw.Done(); c.Close() }()
|
||||
}
|
||||
cw.Wait()
|
||||
wg.Wait()
|
||||
close(panics)
|
||||
for p := range panics {
|
||||
t.Fatalf("panic during Close: %v", p)
|
||||
}
|
||||
if c.IsConnected() {
|
||||
t.Fatal("still connected after Close")
|
||||
}
|
||||
}
|
||||
|
||||
// Concurrent Acquire/Release from panels and jobs: the client is closed
|
||||
// exactly when the last user leaves, never earlier.
|
||||
func TestQAAcquireReleaseConcurrent(t *testing.T) {
|
||||
_, c, dir := setup(t)
|
||||
const n = 50
|
||||
for i := 0; i < n; i++ {
|
||||
c.Acquire()
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < n; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
_, _ = c.ReadDir(dir)
|
||||
c.Release()
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
if !c.IsConnected() {
|
||||
t.Fatal("client closed while the original user still holds it")
|
||||
}
|
||||
if c.Users() != 1 {
|
||||
t.Fatalf("users=%d, want 1", c.Users())
|
||||
}
|
||||
c.Release()
|
||||
if c.IsConnected() {
|
||||
t.Fatal("last Release must close")
|
||||
}
|
||||
// Extra Release (double release by a buggy caller) must not panic.
|
||||
c.Release()
|
||||
}
|
||||
|
|
@ -21,6 +21,7 @@ func IsolatedHome(t testing.TB) string {
|
|||
t.Setenv("HOME", home)
|
||||
t.Setenv("SSH_AUTH_SOCK", "")
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
|
||||
t.Setenv("XDG_DATA_HOME", filepath.Join(home, ".local", "share"))
|
||||
if err := os.MkdirAll(filepath.Join(home, ".ssh"), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -133,6 +133,10 @@ type archiveDoneMsg struct {
|
|||
sourcePaths []string
|
||||
targetPath string
|
||||
err error
|
||||
// trashFailed lists the items a trash job could not move to the trash
|
||||
// (the failing one and the rest); the user is offered to delete them
|
||||
// permanently (QA-1).
|
||||
trashFailed []string
|
||||
}
|
||||
|
||||
type copyDoneMsg struct {
|
||||
|
|
@ -662,6 +666,9 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||
if m.modal.kind == modalArchiveProgress {
|
||||
m.modal = modalState{}
|
||||
}
|
||||
if len(msg.trashFailed) > 0 && msg.err != context.Canceled {
|
||||
m.offerPermanentDelete(msg.trashFailed, msg.err)
|
||||
}
|
||||
return m, m.loadPreviewCmd()
|
||||
}
|
||||
|
||||
|
|
@ -1031,6 +1038,9 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||
|
||||
// Filter mode: route keys to the filter input
|
||||
if m.filterMode {
|
||||
// Printable keys are text for the query, even if they are
|
||||
// also navigation keys in the browser (j/k): QA-3.
|
||||
printable := msg.Type == tea.KeyRunes || msg.Type == tea.KeySpace
|
||||
switch {
|
||||
case msg.String() == "esc":
|
||||
log.Printf("[KEY] Filter: Esc — clear filter")
|
||||
|
|
@ -1046,16 +1056,16 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||
m.filterInput.Blur()
|
||||
m.status = fmt.Sprintf("Filter: %s", m.filterQuery)
|
||||
return m, nil
|
||||
case key.Matches(msg, m.keys.Up):
|
||||
case !printable && key.Matches(msg, m.keys.Up):
|
||||
m.moveFilteredCursor(-1)
|
||||
return m, m.loadPreviewCmd()
|
||||
case key.Matches(msg, m.keys.Down):
|
||||
case !printable && key.Matches(msg, m.keys.Down):
|
||||
m.moveFilteredCursor(1)
|
||||
return m, m.loadPreviewCmd()
|
||||
case key.Matches(msg, m.keys.PageUp):
|
||||
case !printable && key.Matches(msg, m.keys.PageUp):
|
||||
m.moveFilteredCursor(-max(m.bodyHeight()-6, 5))
|
||||
return m, m.loadPreviewCmd()
|
||||
case key.Matches(msg, m.keys.PageDown):
|
||||
case !printable && key.Matches(msg, m.keys.PageDown):
|
||||
m.moveFilteredCursor(max(m.bodyHeight()-6, 5))
|
||||
return m, m.loadPreviewCmd()
|
||||
default:
|
||||
|
|
@ -1590,10 +1600,9 @@ func (m Model) handleModalKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
|
|||
case msg.String() == "shift+tab":
|
||||
m.ssh.cycleInput(-1)
|
||||
return m, nil
|
||||
case key.Matches(msg, m.keys.Help):
|
||||
m.ssh.showHelp = !m.ssh.showHelp
|
||||
return m, nil
|
||||
case msg.String() == "?":
|
||||
case msg.String() == "f1", m.ssh.showHelp && key.Matches(msg, m.keys.Help):
|
||||
// '?' is text in the fields (passwords, user names): only F1
|
||||
// opens the help; '?' still closes it while it is shown (QA-4).
|
||||
m.ssh.showHelp = !m.ssh.showHelp
|
||||
return m, nil
|
||||
default:
|
||||
|
|
@ -2649,12 +2658,12 @@ func (m *Model) handleMirrorPane() (tea.Model, tea.Cmd) {
|
|||
return m, nil
|
||||
}
|
||||
} else if active.InArchive() {
|
||||
// Archive mounts: set path directly, archive data stays on active pane
|
||||
passive.Path = targetPath
|
||||
if err := m.reloadPane(passive.ID, ""); err != nil {
|
||||
m.status = fmt.Sprintf("Mirror failed: %v", err)
|
||||
return m, nil
|
||||
}
|
||||
// The archive mount (and its temp extraction dir) belongs to the
|
||||
// active pane; the passive pane would get the temp dir as a plain
|
||||
// writable directory whose changes vanish when the archive is
|
||||
// closed (QA-2). Refused until archive mounts can be shared.
|
||||
m.status = "Mirror is not supported inside an archive"
|
||||
return m, nil
|
||||
} else {
|
||||
// Local directory — simple path copy
|
||||
releaseMounts(passive.ClearRemotes())
|
||||
|
|
@ -3248,6 +3257,25 @@ func (m *Model) openRenameModal() {
|
|||
}
|
||||
}
|
||||
|
||||
// offerPermanentDelete asks, after the trash refused some items (another
|
||||
// filesystem without a usable trash, broken trash), whether to delete them
|
||||
// permanently instead. Nothing is deleted without this explicit
|
||||
// confirmation (QA-1).
|
||||
func (m *Model) offerPermanentDelete(paths []string, cause error) {
|
||||
m.deleteKind = "permanent"
|
||||
n := len(paths)
|
||||
m.openConfirmModal(
|
||||
"Cannot move to trash. Delete permanently?",
|
||||
fmt.Sprintf("%s\nNot in trash: %d entr%s (first: %s)\nPermanently deleted files cannot be restored.",
|
||||
strings.Join(strings.Fields(cause.Error()), " "), n, pluralSuffix(n, "y", "ies"), filepath.Base(paths[0])),
|
||||
"Enter / y to delete permanently, Esc / n to keep the files",
|
||||
pendingOperation{
|
||||
kind: opPermanentDelete,
|
||||
sourcePaths: append([]string(nil), paths...),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
func (m *Model) openConfirmModal(title, body, note string, pending pendingOperation) {
|
||||
m.modal = modalState{
|
||||
kind: modalConfirm,
|
||||
|
|
@ -5277,11 +5305,15 @@ func (m *Model) startDeleteJob(kind fileOpKind, sources []string) tea.Cmd {
|
|||
err = vfs.MoveToTrash(sourcePath)
|
||||
}
|
||||
if err != nil {
|
||||
m.archiveProgress <- archiveDoneMsg{
|
||||
done := archiveDoneMsg{
|
||||
jobID: jobID,
|
||||
sourcePaths: append([]string(nil), sources...),
|
||||
err: fmt.Errorf("%s %s: %w", verb, sourcePath, err),
|
||||
}
|
||||
if kind != opPermanentDelete {
|
||||
done.trashFailed = append([]string(nil), sources[i:]...)
|
||||
}
|
||||
m.archiveProgress <- done
|
||||
return
|
||||
}
|
||||
|
||||
|
|
@ -5340,7 +5372,7 @@ func (m *Model) mkdirCmd(parent, name string) tea.Cmd {
|
|||
if mount, ok := m.activePane().CurrentRemote(); ok {
|
||||
return func() tea.Msg {
|
||||
targetPath := path.Join(parent, name)
|
||||
err := mount.Client.MkdirAll(targetPath)
|
||||
err := mount.Client.MkdirNew(targetPath)
|
||||
return opMsg{kind: opMkdir, targetPath: targetPath, err: err}
|
||||
}
|
||||
}
|
||||
|
|
@ -6849,10 +6881,10 @@ func renderSSHConnectModal(m Model, palette theme.Palette, width int) string {
|
|||
}
|
||||
lines = append(lines, spacer)
|
||||
// Use hint token renderer to highlight Enter, Esc, F1
|
||||
if hl, ok := renderModalHintTokens("Enter to confirm · Esc to cancel · F1/? for help", contentWidth, palette, palette.Muted); ok {
|
||||
if hl, ok := renderModalHintTokens("Enter to confirm · Esc to cancel · F1 for help", contentWidth, palette, palette.Muted); ok {
|
||||
lines = append(lines, hl)
|
||||
} else {
|
||||
lines = append(lines, noteStyle.Render("Enter to confirm · Esc to cancel · F1/? for help"))
|
||||
lines = append(lines, noteStyle.Render("Enter to confirm · Esc to cancel · F1 for help"))
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
87
internal/ui/qa_fixes_test.go
Normal file
87
internal/ui/qa_fixes_test.go
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
package ui
|
||||
|
||||
// Developer C (v0.2.8 QA fixes): tests for fixes that need more than the QA
|
||||
// tests in qa_*_test.go.
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"vcom/internal/testutil/teadriver"
|
||||
)
|
||||
|
||||
// QA-1: when the trash refuses an item (another filesystem without a
|
||||
// usable trash, a broken trash), the same flow offers permanent deletion;
|
||||
// nothing is deleted without the explicit confirmation.
|
||||
func TestQA1TrashFailureOffersPermanentDelete(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
answer string
|
||||
deleted bool
|
||||
}{
|
||||
{"confirm", "enter", true},
|
||||
{"y", "y", true},
|
||||
{"cancel", "esc", false},
|
||||
{"n", "n", false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, filepath.Join(dir, "a.txt"), "x")
|
||||
writeFile(t, filepath.Join(dir, "b.txt"), "y")
|
||||
d := newDriver(t, dir, t.TempDir())
|
||||
// A file where the trash directory should be: MoveToTrash fails.
|
||||
writeFile(t, filepath.Join(os.Getenv("HOME"), ".local", "share", "Trash"), "not a dir")
|
||||
m := cur(t, d)
|
||||
for _, e := range m.activePane().Entries {
|
||||
if !e.IsParent {
|
||||
m.activePane().EnsureMarked(e.Path)
|
||||
}
|
||||
}
|
||||
d = teadriver.New(t, m, 160, 40, teadriver.WithoutInit(), teadriver.WithLongCmd(300*time.Millisecond))
|
||||
d.Press("f8", "enter")
|
||||
d.Settle(settle)
|
||||
if !exists(filepath.Join(dir, "a.txt")) || !exists(filepath.Join(dir, "b.txt")) {
|
||||
t.Fatal("files deleted before confirmation")
|
||||
}
|
||||
if !d.ScreenContains("Delete permanently?") || !d.ScreenContains("Not in trash: 2") {
|
||||
t.Fatalf("permanent delete not offered:\n%s", d.Screen())
|
||||
}
|
||||
d.Press(tc.answer)
|
||||
d.Settle(settle)
|
||||
for _, n := range []string{"a.txt", "b.txt"} {
|
||||
if got := exists(filepath.Join(dir, n)); got == tc.deleted {
|
||||
t.Fatalf("%s exists=%v after %q (status %q)", n, got, tc.answer, cur(t, d).status)
|
||||
}
|
||||
}
|
||||
if cur(t, d).modal.kind != modalNone {
|
||||
t.Fatalf("dialog still open:\n%s", d.Screen())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// QA-3: in the filter j/k are text, while the arrow keys still move the
|
||||
// cursor through the filtered list.
|
||||
func TestQA3FilterArrowsStillNavigate(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
for _, n := range []string{"jk1.txt", "jk2.txt", "other.txt"} {
|
||||
writeFile(t, filepath.Join(dir, n), "x")
|
||||
}
|
||||
d := newDriver(t, dir, t.TempDir())
|
||||
d.Press("/")
|
||||
d.Type("jk")
|
||||
if q := cur(t, d).filterQuery; q != "jk" {
|
||||
t.Fatalf("query %q", q)
|
||||
}
|
||||
cursor := func() int { m := cur(t, d); return m.activePane().Cursor }
|
||||
before := cursor()
|
||||
d.Press("down")
|
||||
if cursor() == before {
|
||||
t.Fatal("down arrow does not move the cursor in filter mode")
|
||||
}
|
||||
if q := cur(t, d).filterQuery; q != "jk" {
|
||||
t.Fatalf("arrow changed the query: %q", q)
|
||||
}
|
||||
}
|
||||
460
internal/ui/qa_hotfix_test.go
Normal file
460
internal/ui/qa_hotfix_test.go
Normal file
|
|
@ -0,0 +1,460 @@
|
|||
package ui
|
||||
|
||||
// QA (v0.2.8): independent checks of the stage-1 UI hotfixes, aimed at the
|
||||
// paths next to the ones the developer fixed. Tests that expose an open bug
|
||||
// are skipped with "BUG QA-n"; see plans/rework/05-qa-v0.2.8.md.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/muesli/termenv"
|
||||
|
||||
vfs "vcom/internal/fs"
|
||||
"vcom/internal/testutil/teadriver"
|
||||
)
|
||||
|
||||
// --- U-P1-5: Cyrillic / arbitrary text in every input ---------------------
|
||||
|
||||
// Mkdir and rename fields must accept the letters that are also dialog
|
||||
// keys elsewhere: q (close), n (no), y (confirm), j/k (move), ? (help).
|
||||
func TestQATextModalsAcceptCommandLetters(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, filepath.Join(dir, "old.txt"), "x")
|
||||
d := newDriver(t, dir, t.TempDir())
|
||||
d.Press("f7")
|
||||
d.Type("qnyjk?п")
|
||||
if got := cur(t, d).modal.input.Value(); got != "qnyjk?п" {
|
||||
t.Fatalf("mkdir input %q, want %q", got, "qnyjk?п")
|
||||
}
|
||||
d.Press("enter")
|
||||
d.Settle(settle)
|
||||
if !exists(filepath.Join(dir, "qnyjk?п")) {
|
||||
t.Fatalf("dir not created, status %q", cur(t, d).status)
|
||||
}
|
||||
|
||||
selectName(t, d, "old.txt")
|
||||
d.Press("f2", "ctrl+u")
|
||||
d.Type("qй ё?.txt")
|
||||
d.Press("enter")
|
||||
d.Settle(settle)
|
||||
if !exists(filepath.Join(dir, "qй ё?.txt")) {
|
||||
t.Fatalf("rename failed, status %q", cur(t, d).status)
|
||||
}
|
||||
}
|
||||
|
||||
// The filter is a text field: typing "jpg" or "kotlin" must filter by that
|
||||
// text. j/k are bound to Up/Down inside the filter handler and never reach
|
||||
// the input.
|
||||
func TestQAFilterAcceptsJK(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, filepath.Join(dir, "photo.jpg"), "x")
|
||||
writeFile(t, filepath.Join(dir, "notes.txt"), "x")
|
||||
d := newDriver(t, dir, t.TempDir())
|
||||
d.Press("/")
|
||||
d.Type("jpg")
|
||||
if q := cur(t, d).filterQuery; q != "jpg" {
|
||||
t.Fatalf("filter query %q, want jpg", q)
|
||||
}
|
||||
}
|
||||
|
||||
// Cyrillic filter: the list really narrows (the developer only checked the
|
||||
// query string).
|
||||
func TestQAFilterCyrillicNarrows(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, filepath.Join(dir, "отчёт.txt"), "x")
|
||||
writeFile(t, filepath.Join(dir, "summary.txt"), "x")
|
||||
d := newDriver(t, dir, t.TempDir())
|
||||
d.Press("/")
|
||||
d.Type("отч")
|
||||
d.Press("enter")
|
||||
s := d.Screen()
|
||||
if !strings.Contains(s, "отчёт.txt") || strings.Contains(s, "summary.txt") {
|
||||
t.Fatalf("Cyrillic filter did not narrow the list:\n%s", s)
|
||||
}
|
||||
}
|
||||
|
||||
func openSSHAddForm(t *testing.T, d *teadriver.Driver) {
|
||||
t.Helper()
|
||||
d.Press("s") // SSH host list
|
||||
d.Settle(settle)
|
||||
if p := activeOf(t, d).Path; p != sshHostListPath {
|
||||
t.Fatalf("SSH host list not opened, path %q", p)
|
||||
}
|
||||
selectName(t, d, "+ Add host")
|
||||
d.Press("enter")
|
||||
d.Settle(settle)
|
||||
if cur(t, d).modal.kind != modalSSHConnect {
|
||||
t.Fatalf("add-host form not opened (modal %d)", cur(t, d).modal.kind)
|
||||
}
|
||||
}
|
||||
|
||||
// SSH form: Cyrillic name, and q/n/y/j/k in fields.
|
||||
func TestQASSHFormCyrillicAndLetters(t *testing.T) {
|
||||
d := newDriver(t, t.TempDir(), t.TempDir())
|
||||
openSSHAddForm(t, d)
|
||||
d.Type("сервер-qnyjk")
|
||||
d.Press("tab")
|
||||
d.Type("host.example")
|
||||
m := cur(t, d)
|
||||
if got := m.ssh.inputs[0].Value(); got != "сервер-qnyjk" {
|
||||
t.Fatalf("name field %q", got)
|
||||
}
|
||||
if got := m.ssh.inputs[1].Value(); got != "host.example" {
|
||||
t.Fatalf("host field %q", got)
|
||||
}
|
||||
if m.modal.kind != modalSSHConnect {
|
||||
t.Fatal("form closed while typing")
|
||||
}
|
||||
}
|
||||
|
||||
// '?' is a valid password character, but in the SSH form it toggles help.
|
||||
func TestQASSHFormPasswordQuestionMark(t *testing.T) {
|
||||
d := newDriver(t, t.TempDir(), t.TempDir())
|
||||
openSSHAddForm(t, d)
|
||||
for i := 0; i < 4; i++ {
|
||||
d.Press("tab")
|
||||
}
|
||||
d.Type("pa?ss")
|
||||
if got := cur(t, d).ssh.inputs[4].Value(); got != "pa?ss" {
|
||||
t.Fatalf("password field %q, want pa?ss", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Russian layout in yes/no dialogs: "т" (n) cancels, "н" (y) confirms.
|
||||
func TestQARussianLayoutInConfirm(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, filepath.Join(dir, "a.txt"), "x")
|
||||
d := newDriver(t, dir, t.TempDir())
|
||||
selectName(t, d, "a.txt")
|
||||
d.Press("f8", "т")
|
||||
d.Settle(settle)
|
||||
if cur(t, d).modal.kind != modalNone || !exists(filepath.Join(dir, "a.txt")) {
|
||||
t.Fatal("т (n on the Russian layout) should cancel")
|
||||
}
|
||||
d.Press("f8", "н")
|
||||
d.Settle(settle)
|
||||
if exists(filepath.Join(dir, "a.txt")) {
|
||||
t.Fatal("н (y on the Russian layout) should confirm")
|
||||
}
|
||||
}
|
||||
|
||||
// --- U-P1-16: q / Esc in every layer --------------------------------------
|
||||
|
||||
func TestQAQAndEscCloseEveryLayer(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, filepath.Join(dir, "a.txt"), "hello\nworld\n")
|
||||
writeFile(t, filepath.Join(dir, "b.txt"), "x")
|
||||
type layer struct {
|
||||
name string
|
||||
open []string
|
||||
check func(m Model) bool // true while the layer is open
|
||||
}
|
||||
layers := []layer{
|
||||
{"help", []string{"f1"}, func(m Model) bool { return m.modal.kind == modalHelp }},
|
||||
{"theme", []string{"t"}, func(m Model) bool { return m.modal.kind == modalThemeSelect }},
|
||||
{"view", []string{"f3"}, func(m Model) bool { return m.viewMode }},
|
||||
{"info", []string{"f9"}, func(m Model) bool { return m.infoMode }},
|
||||
{"caret", []string{"f9", "i"}, func(m Model) bool { return m.cursorMode || m.infoMode }},
|
||||
{"confirm-delete", []string{"f8"}, func(m Model) bool { return m.modal.kind == modalConfirm }},
|
||||
{"archive-type", []string{"f4"}, func(m Model) bool { return m.modal.kind == modalArchiveType }},
|
||||
{"copy-confirm", []string{"f5"}, func(m Model) bool { return m.modal.kind == modalConfirm }},
|
||||
{"selection", []string{"J"}, func(m Model) bool { return len(m.activePane().MarkedEntries()) > 0 }},
|
||||
}
|
||||
for _, closeKey := range []string{"q", "esc"} {
|
||||
for _, l := range layers {
|
||||
t.Run(closeKey+"/"+l.name, func(t *testing.T) {
|
||||
d := newDriver(t, dir, t.TempDir())
|
||||
selectName(t, d, "a.txt")
|
||||
d.Press(l.open...)
|
||||
d.Settle(settle)
|
||||
if !l.check(cur(t, d)) {
|
||||
t.Fatalf("layer did not open")
|
||||
}
|
||||
for i := 0; i < 3 && l.check(cur(t, d)); i++ {
|
||||
d.Press(closeKey)
|
||||
d.Settle(settle)
|
||||
if d.Quit() {
|
||||
t.Fatalf("%s quit the program with %s open", closeKey, l.name)
|
||||
}
|
||||
}
|
||||
if l.check(cur(t, d)) {
|
||||
t.Fatalf("%s did not close %s", closeKey, l.name)
|
||||
}
|
||||
if !exists(filepath.Join(dir, "a.txt")) {
|
||||
t.Fatal("closing a layer deleted a.txt")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- U-P0-1: archive through the UI, all formats ---------------------------
|
||||
|
||||
func TestQAArchiveSameDirZipThroughUI(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
src := filepath.Join(dir, "report.zip")
|
||||
writeFile(t, src, strings.Repeat("r", 40000))
|
||||
d := newDriver(t, dir, dir)
|
||||
selectName(t, d, "report.zip")
|
||||
d.Press("f4")
|
||||
d.Settle(settle)
|
||||
if f := cur(t, d).archiveFormat; f != "zip" {
|
||||
t.Fatalf("default format %q", f)
|
||||
}
|
||||
d.Press("enter")
|
||||
d.Settle(settle)
|
||||
if fileSize(t, src) != 40000 {
|
||||
t.Fatal("report.zip truncated")
|
||||
}
|
||||
if !d.ScreenContains("Cannot archive") {
|
||||
t.Fatalf("no refusal on screen:\n%s", d.Screen())
|
||||
}
|
||||
}
|
||||
|
||||
// Archive a directory into the same pane for every format, then archive it
|
||||
// again over the existing file with confirmation.
|
||||
func TestQAArchiveFormatsAndOverwriteThroughUI(t *testing.T) {
|
||||
formats := []struct {
|
||||
presses int // presses of "f" from the default zip
|
||||
ext string
|
||||
}{{0, ".zip"}, {1, ".tar"}, {2, ".tar.gz"}}
|
||||
for _, f := range formats {
|
||||
t.Run(f.ext, func(t *testing.T) {
|
||||
dir, out := t.TempDir(), t.TempDir()
|
||||
writeFile(t, filepath.Join(dir, "proj", "a.txt"), "alpha")
|
||||
d := newDriver(t, dir, out)
|
||||
selectName(t, d, "proj")
|
||||
for round := 0; round < 2; round++ {
|
||||
d.Press("f4")
|
||||
d.Settle(settle)
|
||||
for i := 0; i < f.presses; i++ {
|
||||
d.Press("f")
|
||||
}
|
||||
d.Press("enter")
|
||||
d.Settle(settle)
|
||||
if round == 1 {
|
||||
if !d.ScreenContains("Overwrite existing archive") {
|
||||
t.Fatalf("second archive did not ask to overwrite:\n%s", d.Screen())
|
||||
}
|
||||
d.Press("y")
|
||||
d.Settle(settle)
|
||||
}
|
||||
}
|
||||
arc := filepath.Join(out, "proj"+f.ext)
|
||||
if st, err := os.Stat(arc); err != nil || st.Size() == 0 {
|
||||
t.Fatalf("archive %s not written: %v (status %q)", arc, err, cur(t, d).status)
|
||||
}
|
||||
left, _ := filepath.Glob(filepath.Join(out, ".vcom-tmp-*"))
|
||||
if len(left) != 0 {
|
||||
t.Fatalf("temp files left: %v", left)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// --- U-P0-2: archive pane as target, adjacent paths -------------------------
|
||||
|
||||
// Mirror (p) from a pane inside an archive gives the passive pane the
|
||||
// archive's temp extraction directory as a plain local path: it is not
|
||||
// marked as an archive, so canWriteTo lets copy/move write there, and the
|
||||
// directory is deleted when the archive is closed.
|
||||
func TestQAMirrorFromArchiveKeepsReadOnly(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, filepath.Join(dir, "inner.txt"), "in archive")
|
||||
if err := vfs.CreateArchive(context.Background(), []string{filepath.Join(dir, "inner.txt")}, filepath.Join(dir, "box.zip"), nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
work := t.TempDir()
|
||||
writeFile(t, filepath.Join(work, "precious.txt"), "user data")
|
||||
|
||||
d := newDriver(t, dir, work)
|
||||
selectName(t, d, "box.zip")
|
||||
d.Press("enter")
|
||||
d.Settle(settle)
|
||||
if !activeOf(t, d).InArchive() {
|
||||
t.Fatal("did not enter archive")
|
||||
}
|
||||
d.Press("p") // mirror: right pane now shows the archive's temp dir
|
||||
d.Settle(settle)
|
||||
m := cur(t, d)
|
||||
// Developer C: refusing the mirror (passive pane stays on its own
|
||||
// directory) is the chosen fix; a read-only mirror would pass too.
|
||||
if m.passivePane().Path == work && !strings.Contains(m.status, "not supported") {
|
||||
t.Fatalf("mirror neither applied nor refused visibly (status %q)", m.status)
|
||||
}
|
||||
if err := canWriteTo(m.passivePane()); err == nil && m.passivePane().Path != work {
|
||||
// Show the actual loss: move a real file there, close the archive.
|
||||
m.passivePane()
|
||||
t.Fatalf("passive pane %q (mirror of an archive) is writable", m.passivePane().Path)
|
||||
}
|
||||
}
|
||||
|
||||
// Delete/mkdir in a pane that shows an archive's temp dir via mirror.
|
||||
// (Documented together with QA-2.)
|
||||
|
||||
// --- U-P0-3: caret on every profile, with the status line and the filter ---
|
||||
|
||||
func TestQACaretAllProfilesNarrowTerminal(t *testing.T) {
|
||||
for name, profile := range map[string]termenv.Profile{"Ascii": termenv.Ascii, "ANSI": termenv.ANSI, "ANSI256": termenv.ANSI256, "TrueColor": termenv.TrueColor} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, filepath.Join(dir, "t.txt"), "строка один\n\tтаб\n"+strings.Repeat("длинная ", 40)+"\n")
|
||||
m := newTestModel(t, dir, t.TempDir())
|
||||
d := teadriver.New(t, m, 72, 18, teadriver.WithProfile(profile), teadriver.WithLongCmd(300*time.Millisecond))
|
||||
d.Settle(settle)
|
||||
selectName(t, d, "t.txt")
|
||||
d.Press("f9")
|
||||
d.Settle(settle)
|
||||
d.Press("i")
|
||||
d.Settle(settle)
|
||||
d.Press("j", "j", "l", "l", "w", "v", "l", "l", "e", "b", "k")
|
||||
_ = d.Screen()
|
||||
d.Press("f3") // view mode on top
|
||||
d.Settle(settle)
|
||||
_ = d.Screen()
|
||||
if n := len(strings.Split(d.Screen(), "\n")); n != 18 {
|
||||
t.Fatalf("view height %d, want 18", n)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// --- U-P1-1: the status line ------------------------------------------------
|
||||
|
||||
// Multi-line and very long errors stay on one line and keep the height.
|
||||
func TestQAStatusLineMultilineAndLong(t *testing.T) {
|
||||
d := newDriver(t, t.TempDir(), t.TempDir())
|
||||
m := cur(t, d)
|
||||
m.status = "Copy failed: first line\nsecond line\r\n" + strings.Repeat("ошибка ", 100)
|
||||
d2 := teadriver.New(t, m, 80, 20, teadriver.WithoutInit())
|
||||
s := d2.Screen()
|
||||
lines := strings.Split(s, "\n")
|
||||
if len(lines) != 20 {
|
||||
t.Fatalf("height %d, want 20", len(lines))
|
||||
}
|
||||
found := false
|
||||
for _, l := range lines {
|
||||
if strings.Contains(l, "first line second line") {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("status not joined on one line:\n%s", s)
|
||||
}
|
||||
}
|
||||
|
||||
// Status line under every profile does not change the line count.
|
||||
func TestQAStatusLineProfiles(t *testing.T) {
|
||||
for _, profile := range []termenv.Profile{termenv.Ascii, termenv.ANSI, termenv.TrueColor} {
|
||||
dir := t.TempDir()
|
||||
if err := os.Mkdir(filepath.Join(dir, "x"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m := newTestModel(t, dir, t.TempDir())
|
||||
d := teadriver.New(t, m, 100, 25, teadriver.WithProfile(profile), teadriver.WithLongCmd(300*time.Millisecond))
|
||||
d.Settle(settle)
|
||||
d.Press("f7")
|
||||
d.Type("x")
|
||||
d.Press("enter")
|
||||
d.Settle(settle)
|
||||
if !d.ScreenContains("file exists") {
|
||||
t.Fatalf("profile %v: error not shown:\n%s", profile, d.Screen())
|
||||
}
|
||||
if n := len(strings.Split(d.Screen(), "\n")); n != 25 {
|
||||
t.Fatalf("profile %v: %d lines", profile, n)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- U-P0-4: delete defaults to trash ----------------------------------------
|
||||
|
||||
// Multi-selection with names containing spaces and Cyrillic, plus a
|
||||
// directory, all go to the trash.
|
||||
func TestQADeleteToTrashMultiSelection(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
for _, n := range []string{"a b.txt", "отчёт.txt"} {
|
||||
writeFile(t, filepath.Join(dir, n), n)
|
||||
}
|
||||
writeFile(t, filepath.Join(dir, "папка", "inner"), "x")
|
||||
d := newDriver(t, dir, t.TempDir())
|
||||
selectName(t, d, "a b.txt")
|
||||
m := cur(t, d)
|
||||
p := m.activePane()
|
||||
for _, e := range p.Entries {
|
||||
if !e.IsParent {
|
||||
p.EnsureMarked(e.Path)
|
||||
}
|
||||
}
|
||||
d = teadriver.New(t, m, 160, 40, teadriver.WithoutInit(), teadriver.WithLongCmd(300*time.Millisecond))
|
||||
d.Press("f8")
|
||||
d.Settle(settle)
|
||||
if !d.ScreenContains("to trash") {
|
||||
t.Fatalf("dialog does not say trash:\n%s", d.Screen())
|
||||
}
|
||||
d.Press("enter")
|
||||
d.Settle(settle)
|
||||
left, _ := os.ReadDir(dir)
|
||||
if len(left) != 0 {
|
||||
t.Fatalf("left in dir: %v (status %q)", left, cur(t, d).status)
|
||||
}
|
||||
trashed, _ := os.ReadDir(trashFiles(t))
|
||||
if len(trashed) != 3 {
|
||||
t.Fatalf("trash has %d items, want 3", len(trashed))
|
||||
}
|
||||
}
|
||||
|
||||
// D toggles to permanent and back: the second D must return to trash.
|
||||
func TestQADeleteModeToggleBack(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, filepath.Join(dir, "a.txt"), "x")
|
||||
d := newDriver(t, dir, t.TempDir())
|
||||
selectName(t, d, "a.txt")
|
||||
d.Press("f8", "D", "D")
|
||||
d.Press("enter")
|
||||
d.Settle(settle)
|
||||
if !exists(filepath.Join(trashFiles(t), "a.txt")) {
|
||||
t.Fatalf("after D,D the file should go to the trash (status %q)", cur(t, d).status)
|
||||
}
|
||||
}
|
||||
|
||||
// The delete kind must not leak into the next dialog: after a permanent
|
||||
// delete, the next F8 starts in trash mode again.
|
||||
func TestQADeleteModeResetsBetweenDialogs(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, filepath.Join(dir, "a.txt"), "x")
|
||||
writeFile(t, filepath.Join(dir, "b.txt"), "y")
|
||||
d := newDriver(t, dir, t.TempDir())
|
||||
selectName(t, d, "a.txt")
|
||||
d.Press("f8", "D", "esc")
|
||||
selectName(t, d, "b.txt")
|
||||
d.Press("f8", "enter")
|
||||
d.Settle(settle)
|
||||
if !exists(filepath.Join(trashFiles(t), "b.txt")) {
|
||||
t.Fatal("cancelled permanent mode leaked into the next delete")
|
||||
}
|
||||
}
|
||||
|
||||
// With trash as default, the user sees the failure when the trash is not
|
||||
// usable (here: a file where the trash directory should be) and the file
|
||||
// stays.
|
||||
func TestQADeleteTrashFailureVisible(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, filepath.Join(dir, "a.txt"), "x")
|
||||
d := newDriver(t, dir, t.TempDir())
|
||||
trash := filepath.Join(os.Getenv("HOME"), ".local", "share", "Trash")
|
||||
writeFile(t, trash, "not a dir")
|
||||
selectName(t, d, "a.txt")
|
||||
d.Press("f8", "enter")
|
||||
d.Settle(settle)
|
||||
if !exists(filepath.Join(dir, "a.txt")) {
|
||||
t.Fatal("file lost although the trash is broken")
|
||||
}
|
||||
if st := cur(t, d).status; classifyStatus(st) != statusError || !d.ScreenContains("trash") {
|
||||
t.Fatalf("trash failure not reported: %q\n%s", st, d.Screen())
|
||||
}
|
||||
}
|
||||
477
internal/ui/qa_regression_test.go
Normal file
477
internal/ui/qa_regression_test.go
Normal file
|
|
@ -0,0 +1,477 @@
|
|||
package ui
|
||||
|
||||
// QA (v0.2.8): regression pass over the main user scenarios through the
|
||||
// teadriver (local panes) and through sshtest (remote pane).
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"vcom/internal/config"
|
||||
"vcom/internal/fs/remote"
|
||||
"vcom/internal/testutil/sshtest"
|
||||
"vcom/internal/testutil/teadriver"
|
||||
)
|
||||
|
||||
func readFile(t *testing.T, p string) string {
|
||||
t.Helper()
|
||||
b, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
t.Fatalf("read %s: %v", p, err)
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// F5 local->local: overwrite confirmed replaces, cancelled keeps.
|
||||
func TestQACopyOverwriteConfirmAndCancel(t *testing.T) {
|
||||
src, dst := t.TempDir(), t.TempDir()
|
||||
writeFile(t, filepath.Join(src, "a.txt"), "NEW")
|
||||
writeFile(t, filepath.Join(dst, "a.txt"), "OLD")
|
||||
d := newDriver(t, src, dst)
|
||||
selectName(t, d, "a.txt")
|
||||
|
||||
d.Press("f5")
|
||||
d.Settle(settle)
|
||||
if !d.ScreenContains("verwrite") {
|
||||
t.Fatalf("no overwrite warning:\n%s", d.Screen())
|
||||
}
|
||||
d.Press("n")
|
||||
d.Settle(settle)
|
||||
if got := readFile(t, filepath.Join(dst, "a.txt")); got != "OLD" {
|
||||
t.Fatalf("cancel overwrote: %q", got)
|
||||
}
|
||||
d.Press("f5")
|
||||
d.Settle(settle)
|
||||
d.Press("enter")
|
||||
d.Settle(settle)
|
||||
if got := readFile(t, filepath.Join(dst, "a.txt")); got != "NEW" {
|
||||
t.Fatalf("confirmed overwrite: %q (status %q)", got, cur(t, d).status)
|
||||
}
|
||||
}
|
||||
|
||||
// F6 local->local: file and directory, without and with an existing target.
|
||||
func TestQAMoveFileAndDir(t *testing.T) {
|
||||
src, dst := t.TempDir(), t.TempDir()
|
||||
writeFile(t, filepath.Join(src, "f.txt"), "file")
|
||||
writeFile(t, filepath.Join(src, "dir", "inner.txt"), "inner")
|
||||
writeFile(t, filepath.Join(src, "dup.txt"), "NEW")
|
||||
writeFile(t, filepath.Join(dst, "dup.txt"), "OLD")
|
||||
d := newDriver(t, src, dst)
|
||||
for _, n := range []string{"f.txt", "dir"} {
|
||||
selectName(t, d, n)
|
||||
d.Press("f6")
|
||||
d.Settle(settle)
|
||||
d.Press("enter")
|
||||
d.Settle(settle)
|
||||
if exists(filepath.Join(src, n)) || !exists(filepath.Join(dst, n)) {
|
||||
t.Fatalf("move %s failed (status %q)", n, cur(t, d).status)
|
||||
}
|
||||
}
|
||||
if readFile(t, filepath.Join(dst, "dir", "inner.txt")) != "inner" {
|
||||
t.Fatal("moved dir content wrong")
|
||||
}
|
||||
selectName(t, d, "dup.txt")
|
||||
d.Press("f6")
|
||||
d.Settle(settle)
|
||||
d.Press("esc")
|
||||
d.Settle(settle)
|
||||
if !exists(filepath.Join(src, "dup.txt")) || readFile(t, filepath.Join(dst, "dup.txt")) != "OLD" {
|
||||
t.Fatal("cancelled move changed files")
|
||||
}
|
||||
d.Press("f6")
|
||||
d.Settle(settle)
|
||||
d.Press("y")
|
||||
d.Settle(settle)
|
||||
if exists(filepath.Join(src, "dup.txt")) || readFile(t, filepath.Join(dst, "dup.txt")) != "NEW" {
|
||||
t.Fatalf("confirmed move-overwrite failed (status %q)", cur(t, d).status)
|
||||
}
|
||||
}
|
||||
|
||||
// Sorting, hidden files toggle, history back/forward, mirror, info, view,
|
||||
// theme selector, PgUp/PgDn.
|
||||
func TestQABrowseScenarios(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
for i := 0; i < 60; i++ {
|
||||
writeFile(t, filepath.Join(dir, fmt.Sprintf("f%02d.txt", i)), strings.Repeat("x", i))
|
||||
}
|
||||
writeFile(t, filepath.Join(dir, ".hidden"), "h")
|
||||
writeFile(t, filepath.Join(dir, "sub", "deep", "z.txt"), "z")
|
||||
other := t.TempDir()
|
||||
d := newDriver(t, dir, other)
|
||||
|
||||
// hidden toggle
|
||||
before := d.ScreenContains(".hidden")
|
||||
d.Press(".")
|
||||
d.Settle(settle)
|
||||
if d.ScreenContains(".hidden") == before {
|
||||
t.Fatal(". did not toggle hidden files")
|
||||
}
|
||||
|
||||
// sort cycles and changes order
|
||||
first := func() string {
|
||||
p := activeOf(t, d)
|
||||
for _, e := range p.Entries {
|
||||
if !e.IsParent && !e.IsDir {
|
||||
return e.Name
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
order0 := first()
|
||||
changed := false
|
||||
for i := 0; i < 4; i++ {
|
||||
d.Press("g")
|
||||
d.Settle(settle)
|
||||
if first() != order0 {
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
t.Fatal("g never changed the order")
|
||||
}
|
||||
|
||||
// PgDn / PgUp
|
||||
d.Press("pgdown")
|
||||
mid := activeOf(t, d).Cursor
|
||||
d.Press("pgup")
|
||||
if mid == 0 || activeOf(t, d).Cursor >= mid {
|
||||
t.Fatalf("PgDn/PgUp: %d then %d", mid, activeOf(t, d).Cursor)
|
||||
}
|
||||
|
||||
// history
|
||||
selectName(t, d, "sub")
|
||||
d.Press("enter")
|
||||
d.Settle(settle)
|
||||
selectName(t, d, "deep")
|
||||
d.Press("enter")
|
||||
d.Settle(settle)
|
||||
d.Press("alt+left")
|
||||
d.Settle(settle)
|
||||
if p := activeOf(t, d).Path; p != filepath.Join(dir, "sub") {
|
||||
t.Fatalf("history back -> %s", p)
|
||||
}
|
||||
d.Press("alt+right")
|
||||
d.Settle(settle)
|
||||
if p := activeOf(t, d).Path; p != filepath.Join(dir, "sub", "deep") {
|
||||
t.Fatalf("history forward -> %s", p)
|
||||
}
|
||||
|
||||
// mirror
|
||||
d.Press("p")
|
||||
d.Settle(settle)
|
||||
m := cur(t, d)
|
||||
if m.passivePane().Path != filepath.Join(dir, "sub", "deep") {
|
||||
t.Fatalf("mirror: passive at %s", m.passivePane().Path)
|
||||
}
|
||||
|
||||
// info + view
|
||||
selectName(t, d, "z.txt")
|
||||
d.Press("f9")
|
||||
d.Settle(settle)
|
||||
if !cur(t, d).infoMode {
|
||||
t.Fatal("info did not open")
|
||||
}
|
||||
d.Press("f3")
|
||||
d.Settle(settle)
|
||||
if !cur(t, d).viewMode {
|
||||
t.Fatal("view did not open")
|
||||
}
|
||||
d.Press("esc")
|
||||
d.Settle(settle)
|
||||
if cur(t, d).viewMode {
|
||||
t.Fatal("esc did not close view")
|
||||
}
|
||||
d.Press("f9")
|
||||
d.Settle(settle)
|
||||
|
||||
// theme selector: move and confirm
|
||||
d.Press("t")
|
||||
d.Settle(settle)
|
||||
if cur(t, d).modal.kind != modalThemeSelect {
|
||||
t.Fatal("theme selector did not open")
|
||||
}
|
||||
d.Press("j", "enter")
|
||||
d.Settle(settle)
|
||||
if cur(t, d).modal.kind != modalNone {
|
||||
t.Fatal("theme selector did not close on enter")
|
||||
}
|
||||
if n := len(strings.Split(d.Screen(), "\n")); n != 40 {
|
||||
t.Fatalf("height %d after theme change", n)
|
||||
}
|
||||
}
|
||||
|
||||
// F7 with a nested name and the error for an existing one is visible.
|
||||
func TestQAMkdirNestedAndExisting(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
d := newDriver(t, dir, t.TempDir())
|
||||
d.Press("f7")
|
||||
d.Type("a/b")
|
||||
d.Press("enter")
|
||||
d.Settle(settle)
|
||||
if !exists(filepath.Join(dir, "a", "b")) {
|
||||
t.Fatalf("nested mkdir failed: %q", cur(t, d).status)
|
||||
}
|
||||
d.Press("f7")
|
||||
d.Type("a")
|
||||
d.Press("enter")
|
||||
d.Settle(settle)
|
||||
if classifyStatus(cur(t, d).status) != statusError || !d.ScreenContains("exists") {
|
||||
t.Fatalf("existing dir not reported: %q", cur(t, d).status)
|
||||
}
|
||||
}
|
||||
|
||||
// --- remote pane (sshtest) -------------------------------------------------
|
||||
|
||||
func TestQARemoteListingCopyBothWays(t *testing.T) {
|
||||
rdir, local := t.TempDir(), t.TempDir()
|
||||
writeFile(t, filepath.Join(rdir, "remote.txt"), "from server")
|
||||
writeFile(t, filepath.Join(rdir, "rdir", "nested.txt"), "nested")
|
||||
writeFile(t, filepath.Join(local, "local.txt"), "from laptop")
|
||||
writeFile(t, filepath.Join(local, "ldir", "n.txt"), "ln")
|
||||
d := newRemoteDriver(t, rdir, local)
|
||||
if !d.ScreenContains("remote.txt") || !d.ScreenContains("rdir") {
|
||||
t.Fatalf("remote listing missing:\n%s", d.Screen())
|
||||
}
|
||||
// remote -> local, file and dir
|
||||
for _, n := range []string{"remote.txt", "rdir"} {
|
||||
selectName(t, d, n)
|
||||
d.Press("f5")
|
||||
d.Settle(settle)
|
||||
d.Press("enter")
|
||||
d.Settle(settle)
|
||||
}
|
||||
if readFile(t, filepath.Join(local, "remote.txt")) != "from server" || readFile(t, filepath.Join(local, "rdir", "nested.txt")) != "nested" {
|
||||
t.Fatal("remote->local copy wrong")
|
||||
}
|
||||
// local -> remote
|
||||
d.Press("tab")
|
||||
for _, n := range []string{"local.txt", "ldir"} {
|
||||
selectName(t, d, n)
|
||||
d.Press("f5")
|
||||
d.Settle(settle)
|
||||
d.Press("enter")
|
||||
d.Settle(settle)
|
||||
}
|
||||
if readFile(t, filepath.Join(rdir, "local.txt")) != "from laptop" || readFile(t, filepath.Join(rdir, "ldir", "n.txt")) != "ln" {
|
||||
t.Fatalf("local->remote copy wrong (status %q)", cur(t, d).status)
|
||||
}
|
||||
// the remote pane shows the uploaded files after refresh
|
||||
d.Press("tab", "ctrl+r")
|
||||
d.Settle(settle)
|
||||
if !d.ScreenContains("local.txt") {
|
||||
t.Fatalf("remote pane not refreshed:\n%s", d.Screen())
|
||||
}
|
||||
}
|
||||
|
||||
func TestQARemoteDeleteFileDirAndSymlink(t *testing.T) {
|
||||
rdir := t.TempDir()
|
||||
writeFile(t, filepath.Join(rdir, "f.txt"), "x")
|
||||
writeFile(t, filepath.Join(rdir, "d", "inner.txt"), "x")
|
||||
precious := t.TempDir()
|
||||
writeFile(t, filepath.Join(precious, "keep.txt"), "keep")
|
||||
if err := os.Symlink(precious, filepath.Join(rdir, "link")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// confirm_delete=false must not skip the question for a permanent remote delete
|
||||
m := newTestModel(t, t.TempDir(), t.TempDir(), func(c *config.Config) { c.Behavior.ConfirmDelete = false })
|
||||
c := connectTestHost(t)
|
||||
mountRemote(t, &m, PaneLeft, c, rdir)
|
||||
d := teadriver.New(t, m, 160, 40, teadriver.WithLongCmd(300*time.Millisecond))
|
||||
d.Settle(settle)
|
||||
for _, n := range []string{"f.txt", "d", "link"} {
|
||||
selectName(t, d, n)
|
||||
d.Press("f8")
|
||||
d.Settle(settle)
|
||||
if cur(t, d).modal.kind != modalConfirm {
|
||||
t.Fatalf("remote delete of %s did not ask (permanent)", n)
|
||||
}
|
||||
d.Press("enter")
|
||||
d.Settle(settle)
|
||||
if exists(filepath.Join(rdir, n)) {
|
||||
t.Fatalf("%s not deleted (status %q)", n, cur(t, d).status)
|
||||
}
|
||||
}
|
||||
if readFile(t, filepath.Join(precious, "keep.txt")) != "keep" {
|
||||
t.Fatal("deleting the remote symlink removed the target content")
|
||||
}
|
||||
if d.ScreenContains("f.txt") {
|
||||
t.Fatalf("remote pane not refreshed after delete:\n%s", d.Screen())
|
||||
}
|
||||
}
|
||||
|
||||
// Remote mkdir with an existing name: the local path now reports an error
|
||||
// (CHANGELOG: "Creating a directory that already exists reports an
|
||||
// error"), the SSH pane still reports success.
|
||||
func TestQARemoteMkdirExisting(t *testing.T) {
|
||||
rdir := t.TempDir()
|
||||
if err := os.Mkdir(filepath.Join(rdir, "taken"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d := newRemoteDriver(t, rdir, t.TempDir())
|
||||
d.Press("f7")
|
||||
d.Type("taken")
|
||||
d.Press("enter")
|
||||
d.Settle(settle)
|
||||
if classifyStatus(cur(t, d).status) != statusError {
|
||||
t.Fatalf("existing remote dir not reported: %q", cur(t, d).status)
|
||||
}
|
||||
}
|
||||
|
||||
// Every local-file action is refused in an SSH pane; none touches the local
|
||||
// file with the same path (adjacent to N-P0-1/N-P0-2: edit, open, view,
|
||||
// archive, unpack, rename, move-within).
|
||||
func TestQARemoteLocalActionsRefused(t *testing.T) {
|
||||
rdir := t.TempDir()
|
||||
conf := filepath.Join(rdir, "app.conf")
|
||||
writeFile(t, conf, "x=1\n")
|
||||
writeFile(t, filepath.Join(rdir, "a.zip"), "PK")
|
||||
t.Setenv("VISUAL", "true")
|
||||
started := recordProcesses(t)
|
||||
d := newRemoteDriver(t, rdir, t.TempDir())
|
||||
selectName(t, d, "app.conf")
|
||||
for _, k := range []string{"f4", "a", "f2", "r", "enter"} {
|
||||
d.Press(k)
|
||||
d.Settle(settle)
|
||||
if mk := cur(t, d).modal.kind; mk != modalNone {
|
||||
t.Fatalf("%s opened modal %d in an SSH pane", k, mk)
|
||||
}
|
||||
}
|
||||
selectName(t, d, "a.zip")
|
||||
for _, k := range []string{"f11", "e", "enter"} {
|
||||
d.Press(k)
|
||||
d.Settle(settle)
|
||||
if mk := cur(t, d).modal.kind; mk != modalNone {
|
||||
t.Fatalf("%s opened modal %d on a remote archive", k, mk)
|
||||
}
|
||||
if activeOf(t, d).InArchive() {
|
||||
t.Fatal("entered a remote archive through the local path")
|
||||
}
|
||||
}
|
||||
if len(*started) != 0 || len(d.Execs()) != 0 {
|
||||
t.Fatalf("local processes started: %v execs=%d", *started, len(d.Execs()))
|
||||
}
|
||||
if readFile(t, conf) != "x=1\n" {
|
||||
t.Fatal("file changed")
|
||||
}
|
||||
}
|
||||
|
||||
// N-P0-8 / N-P1-12 in the UI: a remote copy sent to the background keeps
|
||||
// working after the pane leaves the host; the connection is closed only
|
||||
// when the job is done.
|
||||
func TestQARemoteBackgroundCopyThenLeaveHost(t *testing.T) {
|
||||
rdir, local := t.TempDir(), t.TempDir()
|
||||
data := sshtest.WriteRandom(t, filepath.Join(rdir, "big.bin"), 2<<20, 0o644)
|
||||
|
||||
m := newTestModel(t, local, local) // isolates HOME before connecting
|
||||
srv := sshtest.Start(t, sshtest.Options{})
|
||||
proxy := sshtest.NewProxy(t, srv.Addr)
|
||||
c, err := remote.Connect(remote.SSHHost{Name: "testhost", HostName: "127.0.0.1", Port: proxy.Port(), User: "u", Password: srv.Password})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { c.Close() })
|
||||
|
||||
mountRemote(t, &m, PaneLeft, c, "/")
|
||||
p := m.paneByID(PaneLeft)
|
||||
p.Path = rdir
|
||||
if err := m.reloadRemotePane(PaneLeft, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d := teadriver.New(t, m, 160, 40, teadriver.WithLongCmd(300*time.Millisecond))
|
||||
d.Settle(settle)
|
||||
selectName(t, d, "big.bin")
|
||||
proxy.SetDelay(2 * time.Millisecond)
|
||||
d.Press("f5")
|
||||
d.Settle(settle)
|
||||
d.Press("enter") // job starts: holds its own client reference
|
||||
if cur(t, d).modal.kind != modalCopyProgress {
|
||||
t.Fatalf("no progress dialog (modal %d)", cur(t, d).modal.kind)
|
||||
}
|
||||
d.Press("b") // background
|
||||
// leave the host: walk up to "/" and once more
|
||||
for i := 0; i < 20 && activeOf(t, d).InRemote(); i++ {
|
||||
d.Press("backspace")
|
||||
}
|
||||
if activeOf(t, d).InRemote() {
|
||||
t.Fatal("could not leave the host")
|
||||
}
|
||||
if !c.IsConnected() {
|
||||
t.Fatal("leaving the host closed the client under the background job")
|
||||
}
|
||||
d.Settle(30 * time.Second)
|
||||
got, err := os.ReadFile(filepath.Join(local, "big.bin"))
|
||||
if err != nil || len(got) != len(data) || string(got) != string(data) {
|
||||
t.Fatalf("background copy incomplete: %d/%d bytes, err %v, status %q", len(got), len(data), err, cur(t, d).status)
|
||||
}
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for c.IsConnected() && time.Now().Before(deadline) {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if c.IsConnected() {
|
||||
t.Fatal("client not closed after the last user (job) finished")
|
||||
}
|
||||
}
|
||||
|
||||
// Mirror an SSH pane, start a remote delete job, leave the host in both
|
||||
// panes while it runs: no panic or race, the job finishes.
|
||||
func TestQARemoteMirrorDeleteJobAndLeave(t *testing.T) {
|
||||
rdir := t.TempDir()
|
||||
for i := 0; i < 30; i++ {
|
||||
writeFile(t, filepath.Join(rdir, "victim", fmt.Sprintf("f%02d", i)), "x")
|
||||
}
|
||||
writeFile(t, filepath.Join(rdir, "keep.txt"), "k")
|
||||
m := newTestModel(t, t.TempDir(), t.TempDir())
|
||||
c := connectTestHost(t)
|
||||
mountRemote(t, &m, PaneLeft, c, "/")
|
||||
p := m.paneByID(PaneLeft)
|
||||
p.Path = rdir
|
||||
if err := m.reloadRemotePane(PaneLeft, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d := teadriver.New(t, m, 160, 40, teadriver.WithLongCmd(300*time.Millisecond))
|
||||
d.Settle(settle)
|
||||
d.Press("p") // mirror
|
||||
d.Settle(settle)
|
||||
selectName(t, d, "victim")
|
||||
d.Press("f8", "enter", "b") // job holds a reference; send it to the background
|
||||
for i := 0; i < 20 && activeOf(t, d).InRemote(); i++ {
|
||||
d.Press("backspace")
|
||||
}
|
||||
d.Press("tab")
|
||||
for i := 0; i < 20 && activeOf(t, d).InRemote(); i++ {
|
||||
d.Press("backspace")
|
||||
}
|
||||
d.Settle(20 * time.Second)
|
||||
if exists(filepath.Join(rdir, "victim")) {
|
||||
t.Fatalf("delete job did not finish (status %q)", cur(t, d).status)
|
||||
}
|
||||
if !exists(filepath.Join(rdir, "keep.txt")) {
|
||||
t.Fatal("keep.txt removed")
|
||||
}
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for c.IsConnected() && time.Now().Before(deadline) {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if c.IsConnected() {
|
||||
t.Fatalf("client still open after both panes left and the job ended (users=%d)", c.Users())
|
||||
}
|
||||
}
|
||||
|
||||
// A single known_hosts line with a key type x/crypto/ssh does not know
|
||||
// (OpenSSH 10 post-quantum "ssh-mldsa44-ed25519", present on the
|
||||
// maintainer's machine) makes every connection fail with "parse known_hosts".
|
||||
func TestQAKnownHostsUnknownAlgorithm(t *testing.T) {
|
||||
isolateEnv(t)
|
||||
kh := filepath.Join(os.Getenv("HOME"), ".ssh", "known_hosts")
|
||||
writeFile(t, kh, "otherhost ssh-mldsa44-ed25519 AAAAFHNzaC1tbGRzYTQ0LWVkMjU1MTkAAAAA\n")
|
||||
srv := sshtest.Start(t, sshtest.Options{})
|
||||
c, err := remote.Connect(remote.SSHHost{Name: "h", HostName: "127.0.0.1", Port: srv.Port(), User: "u", Password: srv.Password})
|
||||
if err != nil {
|
||||
t.Fatalf("connect fails because of an unrelated known_hosts line: %v", err)
|
||||
}
|
||||
c.Close()
|
||||
}
|
||||
|
|
@ -108,3 +108,53 @@
|
|||
до этапа 6/7. Старые `log.Printf` идут через адаптер (`logx.RedirectStdLog`) на уровне debug; на уровне по
|
||||
умолчанию (warn) не пишутся вовсе. Redaction — по имени атрибута (`password`, `passphrase`, `answers`, `answer`,
|
||||
`secret`, `token`, без учёта регистра); свободный текст старых `log.Printf` не фильтруется (они только на debug).
|
||||
|
||||
## Разработчик C, QA-фиксы v0.2.8
|
||||
|
||||
Точечные фиксы по `05-qa-v0.2.8.md` в старом коде (`internal/ui`, `internal/fs`, `internal/fs/remote`). С каждого
|
||||
исправленного бага снят `t.Skip("BUG QA-n")`; дополнительные тесты — `internal/ui/qa_fixes_test.go`,
|
||||
`internal/fs/qa_fixes_test.go`, `internal/fs/remote/qa_fixes_test.go`, `internal/fs/remote/knownhosts_test.go`.
|
||||
|
||||
- **QA-11 (known_hosts).** `knownhosts.New` принимает только файлы и падает целиком на первой плохой строке.
|
||||
Решение (`internal/fs/remote/knownhosts.go`): содержимое пишется во временный файл, при ошибке разбора номер строки
|
||||
берётся из сообщения `knownhosts: <file>:<n>: …`, строка заменяется на `#`, повтор (не больше числа строк). Так
|
||||
отбрасывается ровно то, что не принимает сам парсер x/crypto (неизвестный алгоритм, битый хэш, пустой шаблон),
|
||||
а не наша приблизительная проверка. Каждая пропущенная строка — `log.Printf("[SSH] …:N: skipping known_hosts line")`
|
||||
(лог vcom в `/tmp/vcom-logs`). Исходный `known_hosts` не меняется, TOFU дописывает в него как раньше.
|
||||
Безопасность: если хост записан *только* строками, которые мы пропустили (например, только `ssh-mldsa44-ed25519`),
|
||||
TOFU не принимает другой ключ молча — отказ с объяснением (шаблоны хостов пропущенных строк проверяются через
|
||||
второй db с ключом-заглушкой). `@revoked`/`@cert-authority` с неизвестным ключом просто пропускаются.
|
||||
**HostKeyAlgorithms:** в старом клиенте не задавался, и x/crypto по умолчанию предпочитает ECDSA: хост, записанный
|
||||
только ed25519-ключом (типично), выглядел бы «REMOTE HOST IDENTIFICATION HAS CHANGED» сразу после этого фикса
|
||||
(тест `TestKnownHostsPrefersRecordedAlgorithm` без этой части падает именно так). Теперь, как в OpenSSH, первыми
|
||||
предлагаются алгоритмы ключей, уже записанных для хоста, затем остальные из фиксированного списка поддерживаемых
|
||||
x/crypto (ed25519, ecdsa-256/384/521, rsa-sha2-512/256, ssh-rsa). Тип пропущенной строки туда попасть не может:
|
||||
список берётся из ключей, которые x/crypto распарсил. При наличии `@cert-authority` в файле список не задаётся
|
||||
(CA-ключи нельзя отличить от ключей хоста в `KeyError.Want`) — поведение как раньше.
|
||||
- **QA-1 (корзина на другом разделе).** Сначала сделал `$topdir/.Trash-$uid` в `MoveToTrash`, но по указанию
|
||||
координатора откатил до коммита: корзину целиком переписал разработчик A (`internal/vfs/localfs.Trash`, на неё
|
||||
делегирует `internal/fs.MoveToTrash`), правка внутренностей мешала бы мержу. **`internal/fs/ops.go` не изменён.**
|
||||
Оставлена UI-часть: если задача удаления в корзину получила ошибку на каком-то элементе, в том же потоке
|
||||
открывается подтверждение «Cannot move to trash. Delete permanently?» с причиной и числом оставшихся элементов
|
||||
(не попавший в корзину и все следующие; уже перемещённые не трогаются). Enter/y — безвозвратно, Esc/n — файлы
|
||||
остаются. Срабатывает на любую ошибку корзины, не только EXDEV: при сломанной корзине тоже лучше предложить
|
||||
явный выбор, чем молча отказать; удаление без явного подтверждения невозможно. Почему не copy в домашнюю корзину:
|
||||
долго и рискованно для больших каталогов (частичная копия при ошибке/отмене), а `$topdir`-корзина — задача новой
|
||||
реализации. `TestQATrashCrossDevice` остаётся со Skip до мержа `localfs.Trash`.
|
||||
- **QA-5, QA-8** не трогал — закрываются новой корзиной разработчика A; в CHANGELOG записаны в Known issues
|
||||
для старого кода (уберутся при мерже). Skip в их тестах оставлены.
|
||||
- **QA-3.** В режиме фильтра печатные клавиши (`KeyRunes`, пробел) всегда идут в строку; навигация — только
|
||||
стрелками/PgUp/PgDn.
|
||||
- **QA-4.** В SSH-форме `?` вводится в поле; справку открывает F1; `?` закрывает уже открытую справку (поля в этот
|
||||
момент скрыты). Подсказка формы — «F1 for help».
|
||||
- **QA-10.** Новый `SSHClient.MkdirNew`: `Lstat` цели → `ErrExist`, иначе `MkdirAll(parent)` + `Mkdir`.
|
||||
`MkdirAll` не менял (им пользуются копирование и др.).
|
||||
- **QA-9.** `path.Clean` в начале `RemoveRecursive`.
|
||||
- **QA-6, QA-7.** Временный архив — `.vcom-tmp-<rand>` (короткое имя фиксированной длины; префикс оставлен, на
|
||||
него завязаны проверки «не осталось temp-файлов»). Права: при замене — права старого архива, для нового —
|
||||
`0666 &^ umask` (umask читается из `/proc/self/status`, не через `syscall.Umask`, который на мгновение меняет его
|
||||
всему процессу; fallback 022). Пока архив пишется, temp остаётся 0600.
|
||||
- **QA-2.** Выбран запрет: `p` в архив-панели — «Mirror is not supported inside an archive», пассивная панель не
|
||||
меняется. Read-only-зеркало потребовало бы делить archive mount между панелями (кто чистит temp при выходе) — не
|
||||
для хотфикса. Проверка QA-теста дополнена: принимается и отказ, и read-only.
|
||||
- `sshtest.IsolatedHome` теперь задаёт и `XDG_DATA_HOME`, чтобы ни один тест не мог дойти до настоящей корзины.
|
||||
|
|
|
|||
172
plans/rework/05-qa-v0.2.8.md
Normal file
172
plans/rework/05-qa-v0.2.8.md
Normal file
|
|
@ -0,0 +1,172 @@
|
|||
# 05. QA: проверка v0.2.8 перед релизом
|
||||
|
||||
Ветка: `rework/stabilize` @ `945ae80` (этапы 0 и 1). Проверял независимо от тестов разработчика: читал диф
|
||||
`main..HEAD` по `internal/fs`, `internal/fs/remote`, `internal/ui`, пытался сломать каждый фикс через граничные случаи
|
||||
и соседние пути, прогнал основные сценарии через `teadriver` и `sshtest`. Код продукта не менял.
|
||||
|
||||
Новые тесты (только тесты):
|
||||
- `internal/fs/qa_archive_trash_test.go` — архивация (все форматы, отмена, права, длинные имена, симлинк-источник),
|
||||
корзина (имена, коллизии, `.trashinfo`, XDG, другой раздел), `MakeDir`.
|
||||
- `internal/fs/remote/qa_remote_test.go` — `RemoveRecursive` на всех видах симлинков, `Close` во время передач,
|
||||
конкурентные `Acquire/Release`.
|
||||
- `internal/ui/qa_hotfix_test.go` — ввод текста во всех полях (кириллица, q/n/y/j/k/?), q/Esc во всех слоях, архив
|
||||
через UI во всех форматах + перезапись, mirror из архива, caret на всех профилях, строка статуса, корзина из UI.
|
||||
- `internal/ui/qa_regression_test.go` — регрессии: F5/F6 с перезаписью и без, F7, сортировка, скрытые, PgUp/PgDn,
|
||||
history, mirror, info, view, тема; remote: листинг, copy local↔remote (файл и каталог), delete remote
|
||||
(файл/каталог/симлинк на каталог), запрет локальных действий в SSH-панели, фоновая передача + выход с хоста,
|
||||
mirror + фоновое удаление + выход из обеих панелей.
|
||||
|
||||
Всего добавлено 45 тестов (с подтестами — больше 70 случаев); 12 из них — `t.Skip("BUG QA-n: …")` на реальные баги.
|
||||
|
||||
## Итог прогонов
|
||||
|
||||
| Команда | Результат |
|
||||
|---|---|
|
||||
| `make ci` (gofmt, vet, vendor-check, build, `go test -race -count=1`) | зелёный |
|
||||
| `go test -race -count=3 ./...` | зелёный (до и после добавления QA-тестов) |
|
||||
| `go test -race -count=3 -cpu=1,2 ./...` | зелёный |
|
||||
| `go test -race -count=10` на чувствительных ко времени тестах (`QARemote*`, `NP112`, `NP0*`, `sshtest`, `fs/remote`) | зелёный |
|
||||
|
||||
**Флейков не обнаружено.** DATA RACE и паник нет, в том числе в `TestQACloseDuringTransfers` (3 параллельных `Close`
|
||||
во время upload/download/exec/remove) и в UI-сценариях с mirror и фоновой джобой.
|
||||
|
||||
## Заявленные фиксы: результат проверки
|
||||
|
||||
| Баг | Что проверено сверх тестов разработчика | Вердикт |
|
||||
|---|---|---|
|
||||
| N-P0-1 rename в SSH | F2 и `r` в SSH-панели; панель списка хостов | закрыт |
|
||||
| N-P0-2 Enter/edit/open в SSH | Enter на `.conf`, `.zip`, исполняемом файле; F11/`e`, F4/`a` на remote; ни одного `ExecProcess`/xdg-open, локальный файл не изменён | закрыт |
|
||||
| N-P0-3 удаление remote-симлинка | симлинки битый, на файл, относительный, на `..`; каталог с вложенными симлинками на внешний каталог и файл; через UI (F8 на `link`) | закрыт; для пути со слешем на конце см. QA-9 (P2, из UI недостижимо) |
|
||||
| N-P1-15 archive/unpack с SSH | обе стороны: активная remote и пассивная remote | закрыт |
|
||||
| N-P2-10 запись в `ssh://` | F5/F6/F4 в список хостов; F7 в списке хостов | закрыт |
|
||||
| N-P0-8 гонка Close (часть) | `Close` ×3 параллельно с upload/download/`RemoveRecursive`/`ExecWithProgress`/`MkdirAll` под `-race` | закрыт |
|
||||
| N-P1-12 mirror (часть) | 50 параллельных `Acquire/Release`; двойной `Release` не паникует; фоновая копия remote→local с задержкой в прокси, затем выход с хоста: клиент жив до конца джобы, файл скопирован полностью, после джобы клиент закрыт; mirror + фоновое удаление + выход из обеих панелей: удаление завершено, клиент закрыт | закрыт |
|
||||
| U-P0-1 архив уничтожает источник | `report.zip`→zip и `data.tar`→tar в тот же каталог; `data.tar`→tar.gz и `data.gz`→tar.gz (разрешено, источник цел); содержимое zip/tar/tar.gz корректно (кириллица в именах); отмена для всех трёх форматов сохраняет старый архив без temp-файлов; повторная архивация с подтверждением для всех форматов; источник-симлинк на каталог, архив внутри цели — архив себя не содержит | закрыт; побочные эффекты temp+rename — QA-6, QA-7 (P2) |
|
||||
| U-P0-2 запись в архив-панель | F5/F6/F4/F11 в пассивную архив-панель | закрыт для прямого пути; обход через mirror — QA-2 (P2) |
|
||||
| U-P0-3 caret без цветов | Ascii/ANSI/ANSI256/TrueColor на минимальном размере 72×18, движение `j l w v e b k`, затем F3 поверх; высота экрана не меняется | закрыт |
|
||||
| U-P0-4 удаление в корзину | мультивыделение с пробелами, кириллицей и каталогом; `D,D` возвращает в корзину; режим не «протекает» между диалогами; сломанная корзина → ошибка видна, файл цел; `confirm_delete=false` не пропускает подтверждение для remote (там удаление безвозвратное); `т`/`н` (n/y в русской раскладке) | закрыт, но корзина по умолчанию не работает на другом разделе — QA-1 (P1) |
|
||||
| U-P1-1 строка статуса | многострочная ошибка склеивается в одну строку, длинная обрезается, высота сохраняется на Ascii/ANSI/TrueColor | закрыт |
|
||||
| U-P1-5 кириллица в полях | mkdir, rename, фильтр (список реально сужается), SSH-форма (имя, хост) | закрыт; но в фильтре нельзя набрать `j`/`k` (QA-3), в SSH-форме `?` (QA-4) |
|
||||
| U-P1-6 PgDn | PgDn/PgUp в браузере | закрыт |
|
||||
| U-P1-16 q (часть) | q и Esc в 9 слоях: help, тема, view, info, caret, confirm delete, выбор формата архива, confirm copy, выделение — ни разу не выходит из программы и всё закрывает; q в mkdir/rename/SSH-форме набирается как текст | закрыт |
|
||||
|
||||
## Найденные баги
|
||||
|
||||
Нумерация QA-n; приоритеты по шкале анализа (P0 — потеря данных/крах, P1 — неверное поведение, P2 — мелочи).
|
||||
|
||||
### QA-1 (P1). Удаление по умолчанию не работает для файлов на другом разделе
|
||||
- **Где:** `internal/fs/ops.go:312` (`MoveToTrash`: только `os.Rename`, при `EXDEV` — ошибка); стало заметно из-за
|
||||
`internal/ui/model.go:2538` (корзина теперь по умолчанию, U-P0-4).
|
||||
- **Шаги:** `$HOME` на `/home`, файл на другой ФС (`/tmp` на tmpfs, `/mnt/…`, USB, второй диск). F8 → Enter.
|
||||
- **Ожидаемое:** файл в корзине (`$topdir/.Trash-$uid` по спецификации или copy+delete) или, как минимум, предложение
|
||||
удалить безвозвратно.
|
||||
- **Фактическое:** `cannot move to trash: rename …: invalid cross-device link`, файл на месте. Пользователь должен
|
||||
догадаться нажать `D`. В v0.2.7 то же действие удаляло файл. Данные не теряются, ошибка видна в строке статуса.
|
||||
- **Контекст:** у аналитиков это записано (01-analysis-ui-core.md:176, network:384) и запланировано на 2A, но после смены
|
||||
умолчания в 1.4 это регрессия для пользователя v0.2.8. На машине мейнтейнера `/tmp` — tmpfs, `/home` — nvme.
|
||||
- **Тест:** `internal/fs/qa_archive_trash_test.go` `TestQATrashCrossDevice`.
|
||||
|
||||
### QA-11 (P1, есть с v0.2.7). Одна строка с неизвестным алгоритмом в `known_hosts` ломает все SSH-подключения
|
||||
- **Где:** `internal/fs/remote/client.go:174-176`: ошибка `knownhosts.New` фатальна.
|
||||
- **Шаги:** в `~/.ssh/known_hosts` есть строка с типом ключа, который `x/crypto/ssh` не знает (например,
|
||||
`ssh-mldsa44-ed25519` из OpenSSH 10). Подключиться к любому хосту.
|
||||
- **Ожидаемое:** незнакомые строки пропускаются (как в OpenSSH), подключение идёт.
|
||||
- **Фактическое:** `host key verification: parse known_hosts: … unknown key algorithm: ssh-mldsa44-ed25519`. SSH не
|
||||
работает вообще. **В `~/.ssh/known_hosts` мейнтейнера такая строка есть (строка 4)**: тест, который случайно прочитал
|
||||
настоящий файл, упал именно с этой ошибкой (ничего не записал: ошибка на разборе). Это не регрессия v0.2.8, но в
|
||||
хотфикс-релизе SSH у мейнтейнера не заработает.
|
||||
- **Тест:** `internal/ui/qa_regression_test.go` `TestQAKnownHostsUnknownAlgorithm`.
|
||||
|
||||
### QA-2 (P2). Mirror из архив-панели даёт обычную записываемую панель во временном каталоге
|
||||
- **Где:** `internal/ui/model.go:2620-2626` (`handleMirrorPane`, ветка `InArchive`: копируется только `Path`, без
|
||||
mount архива).
|
||||
- **Шаги:** войти в `box.zip` в левой панели, нажать `p`. Правая панель показывает `/tmp/vcom-archive-XXXX` как обычный
|
||||
локальный каталог.
|
||||
- **Ожидаемое:** правая панель тоже read-only (или mirror из архива запрещён).
|
||||
- **Фактическое:** `canWriteTo(правая)` = nil. В ней работают F7, F2, F8, редактирование, копирование из архива;
|
||||
всё это пропадает при выходе из архива (`RemoveAll` temp), а панель остаётся на удалённом каталоге. Пробовал довести
|
||||
до потери пользовательского файла: после выхода из архива F6 реального файла в «мёртвую» панель падает с
|
||||
`no such file or directory`, файл цел. То есть теряются только правки внутри распакованной копии — поэтому P2, а не P0.
|
||||
- **Тест:** `internal/ui/qa_hotfix_test.go` `TestQAMirrorFromArchiveKeepsReadOnly`.
|
||||
|
||||
### QA-3 (P1, есть с v0.2.7). В фильтр нельзя ввести `j` и `k`
|
||||
- **Где:** `internal/ui/model.go:1015-1020`: в обработчике фильтра `keys.Up`/`keys.Down` (`k`/`j`) проверяются до
|
||||
передачи в textinput.
|
||||
- **Шаги:** `/`, набрать `jpg`.
|
||||
- **Ожидаемое:** запрос `jpg`. **Фактическое:** запрос `pg`, курсор сдвинулся. Фильтр по `jpg`, `kotlin`, `json`
|
||||
невозможен. Фикс U-P1-5 («кириллица в фильтре») это не задел, но сценарий «фильтр работает с любым текстом» сломан.
|
||||
- **Тест:** `TestQAFilterAcceptsJK`.
|
||||
|
||||
### QA-4 (P2). `?` и F1 в форме SSH переключают справку и не попадают в поле
|
||||
- **Где:** `internal/ui/model.go:1562-1568` (`modalSSHConnect`: `keys.Help` и `"?"` раньше `default`).
|
||||
- **Шаги:** `s` → «+ Add host» → в поле Password набрать `pa?ss`.
|
||||
- **Ожидаемое:** `pa?ss`. **Фактическое:** `pass`, справка мигает. Пароль с `?` ввести нельзя (q в форме исправлен
|
||||
в 1.6, `?` — тот же класс).
|
||||
- **Тест:** `TestQASSHFormPasswordQuestionMark`.
|
||||
|
||||
### QA-5 (P2, известно). `.trashinfo` не по спецификации XDG
|
||||
- **Где:** `internal/fs/ops.go:323` (`Path=` без percent-encoding), `ops.go:286` (`XDG_DATA_HOME` игнорируется).
|
||||
- **Фактическое:** имя с переводом строки ломает `.trashinfo` (`Path=` обрезается); пробелы/кириллица не кодируются —
|
||||
восстановление из корзины другими инструментами может не сработать; при заданном `XDG_DATA_HOME` vcom и рабочий стол
|
||||
пишут в разные корзины. С корзиной по умолчанию это стало важнее.
|
||||
- **Тесты:** `TestQATrashInfoPathEncoded`, `TestQATrashHonoursXDGDataHome`.
|
||||
|
||||
### QA-6 (P2). Перезапись архива меняет права на 0644
|
||||
- **Где:** `internal/fs/archive.go:354` (`os.Chmod(tmpPath, 0o644)`).
|
||||
- **Шаги:** существует `secret.zip` с правами 0600, архивировать поверх с подтверждением.
|
||||
- **Ожидаемое:** права сохранены (или по umask). **Фактическое:** 0644, архив стал читаемым для всех.
|
||||
- **Тест:** `TestQAArchiveOverwriteKeepsPermissions`.
|
||||
|
||||
### QA-7 (P2). Архив с длинным именем не создаётся
|
||||
- **Где:** `internal/fs/archive.go:344` (temp-имя `.vcom-tmp-<rand>-<имя>` длиннее имени на ~20 байт).
|
||||
- **Шаги:** файл с именем 240 байт + `.txt`, архивировать в zip (имя архива 244 байта — допустимо).
|
||||
- **Фактическое:** `file name too long`. В v0.2.7 работало.
|
||||
- **Тест:** `TestQAArchiveLongName`.
|
||||
|
||||
### QA-8 (P2). Коллизия в корзине с битым симлинком затирает его
|
||||
- **Где:** `internal/fs/ops.go:303` (проверка занятости имени через `os.Stat`, который идёт по ссылке).
|
||||
- **Шаги:** удалить в корзину битый симлинк `x`, затем файл с тем же именем `x`.
|
||||
- **Ожидаемое:** в корзине два элемента. **Фактическое:** один, симлинк затёрт `rename`.
|
||||
- **Тест:** `TestQATrashCollisionWithBrokenSymlink`.
|
||||
|
||||
### QA-9 (P2). `RemoveRecursive("link/")` идёт по ссылке
|
||||
- **Где:** `internal/fs/remote/client.go:528`: `Lstat` пути со слешем на конце на POSIX-сервере разрешает ссылку.
|
||||
- **Шаги:** `RemoveRecursive(link + "/")`, где `link` → каталог. **Фактическое:** содержимое цели удалено.
|
||||
- **Достижимость:** из UI сейчас нет (пути собираются через `path.Join`, слеш на конце не остаётся). Стоит
|
||||
`path.Clean` в начале функции.
|
||||
- **Тест:** `TestQARemoveRecursiveSymlinkTrailingSlash`.
|
||||
|
||||
### QA-10 (P2). F7 с существующим именем в SSH-панели «успешен»
|
||||
- **Где:** `internal/ui/model.go:5312` (`mkdirCmd` → `Client.MkdirAll`).
|
||||
- **Ожидаемое:** ошибка, как локально после 1.1 (CHANGELOG: «Creating a directory that already exists reports an
|
||||
error»). **Фактическое:** `Created …/taken`. CHANGELOG обещает больше, чем сделано.
|
||||
- **Тест:** `TestQARemoteMkdirExisting`.
|
||||
|
||||
## Наблюдения без отдельного id
|
||||
|
||||
- `goParent` после `Release` оставляет хост помеченным «connected», если клиентом пользуется другая панель или джоба.
|
||||
Это корректно. Но `exitSSHMode` ставит `connectedHosts=false` безусловно — значок в списке хостов может врать,
|
||||
пока работает mirror. Мелочь.
|
||||
- `Close` ждёт keepalive-горутину под `closeMu`. При «замёрзшей» сети `SendRequest` может висеть, и последний `Release`
|
||||
из `Update` (выход с хоста) заблокирует UI. Так было и до фикса (N-P1-8/9 — этап 2B).
|
||||
- `ssh.activeClients` нигде не заполняется: код закрытия в `exitSSHMode`/`executeSSHHostDelete` мёртвый. Это не баг.
|
||||
- Переход Enter по remote-симлинку на каталог теперь выдаёт «Opening remote files is not supported». Раньше это тоже
|
||||
не работало (remote-записи для симлинков — не каталоги), регрессии нет.
|
||||
|
||||
## Вердикт
|
||||
|
||||
Все заявленные фиксы этапа 1 (N-P0-1/2/3, N-P1-15, N-P2-10, части N-P0-8/N-P1-12, U-P0-1..4, U-P1-1/5/6, часть
|
||||
U-P1-16) **подтверждены** и выдержали попытки обойти их через соседние пути. Регрессий в основных сценариях
|
||||
(local и remote) нет, CI зелёный, флейков нет. **P0 не найдено.**
|
||||
|
||||
**v0.2.8 можно выпускать.** До тега рекомендую закрыть два P1, оба небольшие:
|
||||
1. **QA-1**: при `EXDEV` в `MoveToTrash` делать fallback (copy+delete в `~/.local/share/Trash` или
|
||||
`$topdir/.Trash-$uid`), либо при ошибке корзины предлагать в том же диалоге безвозвратное удаление. Иначе
|
||||
новое умолчание «в корзину» ломает F8 за пределами раздела `$HOME`. Если не исправлять, это нужно записать в CHANGELOG
|
||||
как известное ограничение.
|
||||
2. **QA-11**: если `knownhosts.New` не разобрал файл, не отказывать в подключении — пропускать незнакомые строки.
|
||||
Это не регрессия, но SSH у мейнтейнера сейчас не работает вовсе (OpenSSH 10 пишет PQ-ключи в known_hosts).
|
||||
|
||||
Остальное (QA-2..QA-10) не блокирует релиз; QA-3 (j/k в фильтре) и QA-10 (несоответствие CHANGELOG) стоит взять в
|
||||
следующий хотфикс или в этап 6. CHANGELOG стоит поправить: для F7 указать, что ошибка на существующем имени пока
|
||||
только для локальных панелей.
|
||||
Loading…
Add table
Add a link
Reference in a new issue