diff --git a/README.md b/README.md index fa300c4..efea8a6 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,45 @@ Install the following tools, either via the indicated command or what is suggest sqlc is used for the audit functionality as well as the SQLite output format. If you never change this functionality it may not be required, however _never_ edit the `./processor/database/` files directly. Edit `./assets/db/` and run `sqlc generate` instead. +### Testing + +An audit that passes when a file was changed is the worst thing hashit can do, so audit mode is tested far more heavily than the rest of the tool. Every fix in the audit code came from a report that was reproduced, explained and discussed before anything changed, and each was then added as a test. + +You don't have to take hashit's word for any of this. Its audit files are standard formats that other tools can check, so you can verify your files with hashit, with another tool, or with both: + +- A `hashdeep` file written by hashit can be audited with `hashdeep -l -r -a -k audit.txt .`, and hashit can audit files written by `hashdeep`. See [Verifying with `hashdeep`](#verifying-with-hashdeep). +- A `sum` file written by hashit can be checked with `md5sum -c`, `sha256sum -c` and the other `*sum` tools, and hashit can audit their output. See [Auditing with `sum` Files](#auditing-with-sum-files). +- A SQLite database is an ordinary SQLite file which you can query yourself. See [Verifying with your own tools](#verifying-with-your-own-tools-python-example). + +An audit only reads. It never changes, overwrites or deletes your files, the audit file or the database. + +Run everything with `./test-all.sh < /dev/null`, which needs `hashdeep`, GNU coreutils and `sqlite3` installed. It runs: + +- `go test ./...`: unit tests, plus the parser fuzz tests on their seed inputs and the end-to-end audit tests below. +- Over 300 command line checks of hashing, output formats, exit codes, symbolic links, unreadable files, and every audit edge case found in review, many of them checked against `hashdeep` and `md5sum`. +- `./test-audit.sh`: audit scenarios checked against `hashdeep -a` and `md5sum -c`, and `sum` files of every hash `sha1sum`, `sha224sum`, `sha256sum`, `sha384sum`, `sha512sum` and `b2sum` check, verified by those tools and failed by them once a file is modified. Audits known to be wrong are reported as known bugs without failing the run, and fail once they are fixed, so they can be moved to the scenarios which must pass. + +`./test-hashdeep.sh` separately checks that `hashdeep` and hashit agree on each other's output. + +The end-to-end audit tests in `main_audit_test.go` build a tree, write a manifest with hashit, then copy or move the tree, change it and audit it. The result is compared with what was actually changed, not with what hashit says: an audit must never pass when a known file was modified or is missing, and must pass when nothing changed. They cover every format (`hashdeep`, `sum` and SQLite), manifests kept beside the tree, at its root or in a subdirectory, written from the tree or its parent, trees left in place, copied or moved, audits run from the root, the parent or a subdirectory, edited or missing `## Invoked from:` lines, and every combination of `--allow-new` and `--allow-moved`. + +- `TestAuditMatrix` runs 3,680 of these over every combination. +- `TestAuditRegressions` holds every wrong audit found so far. +- `FuzzAudit` and `TestAuditSweep` generate random trees, biased towards the layouts that have hidden bugs, such as the same name in several directories, or a file named like the manifest. `go test -fuzz FuzzAudit .` works, but Go's fuzzer mutates around a few seeds, so a sweep over many seeds finds more: + +```shell +go test -c -o audit.test . +HASHIT_AUDIT_SWEEP=1000 HASHIT_AUDIT_SEED=0 ./audit.test -test.run TestAuditSweep +``` + +Run several with different `HASHIT_AUDIT_SEED` values in parallel. + +The parsers have their own fuzz tests in `processor/audit_fuzz_test.go`: sum lines round trip and parse to a hash of the right length, `hashdeep` lines split back into the line they came from, any audit file is parsed or refused without panicking, and path resolution is absolute and stable. Run one with `go test -fuzz FuzzParseSumLine ./processor`. + +Audit mode has also been through repeated rounds of independent review, each with four reviewers covering paths, `hashdeep` files, `sum` files and SQLite databases. Each reviewer compared hashit with `hashdeep`, `md5sum` and earlier versions of hashit, wrote its own differential fuzzers, and measured CPU time against the previous version. + +The sweep is run across 16 processes at a time. Before the latest fixes, 304,000 scenarios found 106 wrong audits, 104 of them passes which should have failed, all from two causes. Both are fixed and the cases are in `TestAuditRegressions`. A one hour sweep afterwards ran 1,568,000 scenarios and found one wrong audit, a pass when as many files matched through two directories, as in a copied tree with its manifest kept in a subdirectory. That is also fixed and in `TestAuditRegressions`, and a 15 minute sweep after the fix ran 416,000 scenarios and found none. + ### Pitch Why use `hashit`? @@ -334,9 +373,9 @@ Some other points worth knowing: - A file which cannot be read, including files in a directory which cannot be read, is reported as could not be read in `-v` output, counted as missing when it is in the audit file and not counted otherwise, and `hashit` exits with `2` rather than `1`. - The same file supplied more than once by the same absolute path, such as through `.` and `./sub`, is only counted once. The same file reached through a symbolic link is a different path, so is counted again. - Modification times are recorded with `--mtime` but are not compared by an audit. -- A `sum` file which lists the same file more than once, such as once with `md5sum` and again with `sha1sum`, or as both `./file` and `file`, has every line checked as `md5sum -c` does, including when its paths only name the same file through the directory containing the `sum` file or a symbolic link, where a line is only not reported on its own when another line was checked against that same file and it names that file through the directory the audit is matched through, and a file listed with different values of the same hash is reported as modified with a warning. In a `hashdeep` file only the first entry for a path is used, with a warning. In a SQLite database a row for a path already listed with the same values is not counted, with a warning, while one with other values is reported as missing. Entries are only the same path when they name the same file through the directory the audit is matched through, so after a tree is copied elsewhere an absolute entry into the original is audited on its own. When every file matched an absolute entry no directory is chosen, and entries are the same path when they name the same file through the invoked from directory, or for a `sum` file, which has none, through any of them. A SQLite database whose `file_hashes` table does not have a text `filepath` on every row as its primary key compared exactly, as one not created by hashit may not, is refused rather than audited. +- A `sum` file which lists the same file more than once, such as once with `md5sum` and again with `sha1sum`, or as both `./file` and `file`, has every line checked as `md5sum -c` does. Lines are the same file when they name it through the directory the audit is matched through, including through a symbolic link, and a line is only not reported on its own when another line was checked against that file. A file listed with different values of the same hash is reported as modified with a warning. Lines which only name the same file through another directory name different files, so a `sum` file at the root of a tree listing `./README` and `./sub/README` passes when audited from `sub`. When as many files match through another directory as through the one chosen, lines naming the same file through either must agree, as which the `sum` file is relative to is not known. In a `hashdeep` file only the first entry for a path is used, with a warning. In a SQLite database a row for a path already listed with the same values is not counted, with a warning, while one with other values is reported as missing. Entries are only the same path when they name the same file through the directory the audit is matched through, so after a tree is copied elsewhere an absolute entry into the original is audited on its own. When every file matched an absolute entry no directory is chosen, and entries are the same path when they name the same file through the invoked from directory, or for a `sum` file, which has none, through any of them. A SQLite database whose `file_hashes` table does not have a text `filepath` on every row as its primary key compared exactly, as one not created by hashit may not, is refused rather than audited. - The audit file of an empty directory passes when audited against an empty directory, as does an audit file which is empty or only contains comments, which `md5sum -c` treats as an error. `hashdeep` reports an error for an audit file with no files in it. -- An audit file written by a shell redirect into the directory being hashed, such as `hashit --format hashdeep . > manifest.txt`, lists itself as an empty file. That entry is ignored when auditing, but `--output manifest.txt` avoids it entirely and is recommended, especially for the `sum` format which writes as it goes and so may record part of itself, which then fails when audited from another directory. +- An audit file written by a shell redirect into the directory being hashed, such as `hashit --format hashdeep . > manifest.txt`, lists itself as an empty file. That entry is ignored when auditing. Without an invoked from directory, as for a `sum` file, an entry is only taken to be the audit file when it names it through the directory the audit is matched through, so another file of the same name, such as `data/data/hashes.md5` listed in `data/hashes.md5` and audited from the parent of `data`, is still audited. `--output manifest.txt` avoids the entry entirely and is recommended, especially for the `sum` format which writes as it goes and so may record part of itself, which then fails when audited from another directory. - Concatenated `hashdeep` files are read, but only the first `## Invoked from:` line is used, so files concatenated from different directories may report moved files. `hashdeep` also fails to audit these. #### Modification Times @@ -355,7 +394,7 @@ hashdeep: Audit passed #### Paths in Audit Files -Relative paths in a `hashdeep` file are resolved against the directory recorded in its `## Invoked from:` line, so an audit file created with `hashit --format hashdeep .` can be audited from anywhere using either a relative or absolute path. When the invoked from directory does not contain the files, such as after they have been copied elsewhere, paths are also resolved against the directory containing the audit file, being where the file really is and then where the path supplied for it is when that is a symbolic link, and then the current directory. An audit is matched through only one of these, the one through which the most files match their records, or the first of those in this order, so a file found only through another, such as a file moved to where the directory containing the audit file places its record, is reported as moved or new. Relative paths in `sum` files have no invoked from directory, so are resolved against the current directory first. Matching is case sensitive on every platform. Paths are always compared as absolute paths, so the path to audit may be supplied as relative or absolute, and `./file` and `file` are the same file. So a manifest stored at the root of a set of files, created from that directory, can be audited from anywhere after the files are copied or shipped elsewhere. Symbolic links in the path to audit are not resolved, so a manifest created through `real/` and audited through a link to it reports every file as moved, as `hashdeep` does. When the current directory was reached through a symbolic link, paths through where it, or a directory containing it, really is are compared through the link, so a manifest of absolute paths through `real/` audited with `.` from the link passes. A path containing `..`, such as `../dir` or `link/../dir`, names the directory the operating system reads, being the parent of the directory a symbolic link points to rather than the directory containing the link, in the paths supplied, the paths recorded in audit files and with `--absolute`. Where removing the `..` names the same directory, such as from a current directory reached through a symbolic link, the path is kept as written, A recorded path through a directory which no longer exists, such as the directory an audit file was created in, has its `..` removed as text, as a missing directory cannot be a symbolic link, while a recorded path with `..` after a link which no longer exists, a file, or a directory which cannot be searched never matches another file. When two files on disk match the same record, such as when the path to audit overlaps a copy of the files, the one matching through the invoked from directory is used and the other is reported as new. +Relative paths in a `hashdeep` file are resolved against the directory recorded in its `## Invoked from:` line, so an audit file created with `hashit --format hashdeep .` can be audited from anywhere using either a relative or absolute path. When the invoked from directory does not contain the files, such as after they have been copied elsewhere, paths are also resolved against the directory containing the audit file, being where the file really is and then where the path supplied for it is when that is a symbolic link, and then the current directory. An audit is matched through only one of these, the one through which the most files match their records, or the first of those in this order, so a file found only through another, such as a file moved to where the directory containing the audit file places its record, is reported as moved or new. A file counts towards every directory through which a record names it, except a file an absolute record names, and is checked against the record naming it through the chosen directory, so a file which another record also names through a different directory, such as `meta/README` named by `./README` through a manifest kept in `meta`, is still checked against its own record. When as many files match through another directory as through the first of them, which the paths are relative to is not decided by the files on disk, so the audit is checked through each and passes only when it passes through every one, with a warning naming the directory it fails through. Otherwise a tree copied with its manifest kept in `meta`, where `./README` and `./meta/README` both name `meta/README`, could pass after `README` was moved onto `meta/README`. Relative paths in `sum` files have no invoked from directory, so are resolved against the current directory first. Matching is case sensitive on every platform. Paths are always compared as absolute paths, so the path to audit may be supplied as relative or absolute, and `./file` and `file` are the same file. So a manifest stored at the root of a set of files, created from that directory, can be audited from anywhere after the files are copied or shipped elsewhere. Symbolic links in the path to audit are not resolved, so a manifest created through `real/` and audited through a link to it reports every file as moved, as `hashdeep` does. When the current directory was reached through a symbolic link, paths through where it, or a directory containing it, really is are compared through the link, so a manifest of absolute paths through `real/` audited with `.` from the link passes. A path containing `..`, such as `../dir` or `link/../dir`, names the directory the operating system reads, being the parent of the directory a symbolic link points to rather than the directory containing the link, in the paths supplied, the paths recorded in audit files and with `--absolute`. Where removing the `..` names the same directory, such as from a current directory reached through a symbolic link, the path is kept as written, A recorded path through a directory which no longer exists, such as the directory an audit file was created in, has its `..` removed as text, as a missing directory cannot be a symbolic link, while a recorded path with `..` after a link which no longer exists, a file, or a directory which cannot be searched never matches another file. When two files on disk match the same record, such as when the path to audit overlaps a copy of the files, the one matching through the invoked from directory is used and the other is reported as new. If the audit file is inside the directory being audited it is skipped, as it can never contain its own hash. `hashdeep` and `md5sum` do not do this, so when generating a file for them to verify, write it outside the directory being hashed, otherwise they will report the partially written file as changed. diff --git a/main_audit_test.go b/main_audit_test.go new file mode 100644 index 0000000..e99a8e2 --- /dev/null +++ b/main_audit_test.go @@ -0,0 +1,837 @@ +// SPDX-License-Identifier: MIT + +package main + +import ( + "bytes" + "fmt" + "io/fs" + "math/rand" + "os" + "os/exec" + "path/filepath" + "runtime" + "sort" + "strconv" + "strings" + "testing" +) + +// TestMain runs hashit itself when asked to, so the audit tests can run it as a separate process +// without building it first, as an audit exits the process with its result +func TestMain(m *testing.M) { + if os.Getenv("HASHIT_TEST_MAIN") == "1" { + main() + os.Exit(0) + } + os.Exit(m.Run()) +} + +// runHashit runs hashit in dir returning its exit code and combined output +func runHashit(t *testing.T, dir string, args ...string) (int, string) { + t.Helper() + // the test binary may have been run by a relative path, which the directory changes + self, err := os.Executable() + if err != nil { + t.Fatal(err) + } + cmd := exec.Command(self, args...) + cmd.Dir = dir + cmd.Env = append(os.Environ(), "HASHIT_TEST_MAIN=1") + var out bytes.Buffer + cmd.Stdout = &out + cmd.Stderr = &out + err = cmd.Run() + if err == nil { + return 0, out.String() + } + if e, ok := err.(*exec.ExitError); ok { + return e.ExitCode(), out.String() + } + t.Fatalf("unable to run hashit %v: %v", args, err) + return 0, "" +} + +// treeName is the name of the audited tree, which is also used for a directory inside it, so a +// path from the parent can name a different file through the tree itself +const treeName = "data" + +var ( + scenarioDirs = []string{"", "sub", treeName, "meta", "sub/deep", treeName + "/" + treeName} + scenarioNames = []string{"a", "b", "README", "x.txt", "hashes.md5", "m.hd", "m.db"} +) + +// auditScenario is a tree which has a manifest written for it, may be copied or moved, then is +// changed and audited. The expected result is worked out from what was changed, not from hashit +type auditScenario struct { + format string // hashdeep, sum or sqlite + invokedFrom string // for hashdeep, strip or sub to remove the invoked from line or point it at sub + absolute bool // manifest written with --absolute + fromParent bool // manifest written from the tree's parent with the tree as the path + location string // where the manifest is kept: out (beside the tree), root or meta + relocation string // none, copy (original kept) or move + auditFrom string // root, parent or sub, being the directory the audit is run from + allowNew bool + allowMoved bool + files map[string]string // path relative to the tree to content + changes []string +} + +func (s *auditScenario) String() string { + return fmt.Sprintf("format=%s invokedFrom=%s absolute=%v fromParent=%v location=%s relocation=%s auditFrom=%s allowNew=%v allowMoved=%v changes=%v files=%v", + s.format, s.invokedFrom, s.absolute, s.fromParent, s.location, s.relocation, s.auditFrom, s.allowNew, s.allowMoved, s.changes, s.files) +} + +func (s *auditScenario) manifestName() string { + switch s.format { + case "hashdeep": + return "m.hd" + case "sum": + return "hashes.md5" + } + return "m.db" +} + +// manifestRel is the path of the manifest relative to the tree, or empty when kept beside it +func (s *auditScenario) manifestRel() string { + switch s.location { + case "root": + return s.manifestName() + case "meta": + return "meta/" + s.manifestName() + } + return "" +} + +func newAuditScenario(seed uint64) *auditScenario { + r := rand.New(rand.NewSource(int64(seed))) + pick := func(xs ...string) string { return xs[r.Intn(len(xs))] } + s := &auditScenario{ + format: pick("hashdeep", "sum", "sqlite"), + absolute: r.Intn(8) == 0, + fromParent: r.Intn(3) == 0, + location: pick("out", "root", "meta"), + relocation: pick("none", "none", "copy", "move"), + auditFrom: pick("root", "root", "parent", "sub"), + allowNew: r.Intn(2) == 0, + allowMoved: r.Intn(3) != 0, + files: map[string]string{}, + } + if s.format == "sum" && s.absolute { + s.absolute = false + } + if s.format == "hashdeep" && r.Intn(3) == 0 { + s.invokedFrom = pick("strip", "sub") + } + // sub always exists so the audit can be run from it + s.files["sub/"+pick(scenarioNames...)] = "content 0\n" + for i, n := 1, 2+r.Intn(8); i <= n; i++ { + name := pick(scenarioNames...) + if used := s.paths(); r.Intn(2) == 0 { + // the same name in another directory, which another base may name + name = filepath.Base(used[r.Intn(len(used))]) + } + p := filepath.ToSlash(filepath.Join(pick(scenarioDirs...), name)) + if p == s.manifestRel() || s.isDir(p) || s.hasDirAt(p) { + continue + } + content := fmt.Sprintf("content %d\n", i) + if r.Intn(8) == 0 { + content = "content 0\n" // identical files + } + s.files[p] = content + } + + if r.Intn(2) == 0 { + // one name in several directories, so another base names a different file of that name + name := filepath.Base(pick(s.paths()...)) + for i, n := 0, 2+r.Intn(2); i < n; i++ { + p := filepath.ToSlash(filepath.Join(pick(scenarioDirs...), name)) + if _, ok := s.files[p]; ok || p == s.manifestRel() || s.isDir(p) || s.hasDirAt(p) { + continue + } + s.files[p] = fmt.Sprintf("content %s %d\n", name, i) + } + } + + paths := s.paths() + // files sharing a name with another are changed more often, as which record they are is decided + // between the directories records can be relative to + var shared []string + for _, p := range paths { + for _, q := range paths { + if p != q && filepath.Base(p) == filepath.Base(q) { + shared = append(shared, p) + break + } + } + } + file := func() string { + if len(shared) > 0 && r.Intn(4) != 0 { + return shared[r.Intn(len(shared))] + } + return paths[r.Intn(len(paths))] + } + for i, n := 0, r.Intn(4); i < n; i++ { + f, g := file(), file() + switch r.Intn(9) { + case 0: + s.changes = append(s.changes, "modify "+f) + case 1: + s.changes = append(s.changes, "delete "+f) + case 2: + s.changes = append(s.changes, "rename "+f+" "+f+".renamed") + case 3: + s.changes = append(s.changes, "rename "+f+" "+filepath.ToSlash(filepath.Join(pick(scenarioDirs...), filepath.Base(f)+".moved"))) + case 4: + s.changes = append(s.changes, "swap "+f+" "+g) + case 5: + s.changes = append(s.changes, "copy "+f+" "+f+".copy") + case 6: + s.changes = append(s.changes, "copy "+f+" "+filepath.ToSlash(filepath.Join(pick(scenarioDirs...), "new"))) + case 7: + // a backup is kept of a file before it is changed + s.changes = append(s.changes, "copy "+f+" "+f+".orig", "modify "+f) + case 8: + // moved onto the path of another known file + s.changes = append(s.changes, "rename "+f+" "+g+".old", "rename "+g+" "+f) + } + } + return s +} + +func (s *auditScenario) paths() []string { + var paths []string + for p := range s.files { + paths = append(paths, p) + } + sort.Strings(paths) + return paths +} + +// isDir reports if a file is already used as a directory +func (s *auditScenario) isDir(p string) bool { + for f := range s.files { + if strings.HasPrefix(f, p+"/") { + return true + } + } + return false +} + +// hasDirAt reports if a directory of a path is already used as a file +func (s *auditScenario) hasDirAt(p string) bool { + for d := filepath.Dir(p); d != "."; d = filepath.Dir(d) { + if _, ok := s.files[filepath.ToSlash(d)]; ok { + return true + } + } + return false +} + +func writeTree(t *testing.T, root string, files map[string]string) { + t.Helper() + for p, content := range files { + full := filepath.Join(root, filepath.FromSlash(p)) + if err := os.MkdirAll(filepath.Dir(full), 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(full, []byte(content), 0644); err != nil { + t.Fatal(err) + } + } +} + +// readTree returns every file under root with its content, skipping those excluded +func readTree(t *testing.T, root string, exclude map[string]bool) map[string]string { + t.Helper() + files := map[string]string{} + err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() || exclude[path] { + return nil + } + content, err := os.ReadFile(path) + if err != nil { + return err + } + rel, _ := filepath.Rel(root, path) + files[filepath.ToSlash(rel)] = string(content) + return nil + }) + if err != nil { + t.Fatal(err) + } + return files +} + +// applyChange makes a change to the tree, returning false when it cannot be made, such as when +// an earlier change removed the file +func applyChange(root string, change string) bool { + parts := strings.Fields(change) + full := func(p string) string { return filepath.Join(root, filepath.FromSlash(p)) } + exists := func(p string) bool { _, err := os.Lstat(full(p)); return err == nil } + switch parts[0] { + case "modify": + if !exists(parts[1]) { + return false + } + f, err := os.OpenFile(full(parts[1]), os.O_APPEND|os.O_WRONLY, 0) + if err != nil { + return false + } + _, err = f.WriteString("modified\n") + return f.Close() == nil && err == nil + case "delete": + return os.Remove(full(parts[1])) == nil + case "rename", "copy": + if !exists(parts[1]) || exists(parts[2]) { + return false + } + if err := os.MkdirAll(filepath.Dir(full(parts[2])), 0755); err != nil { + return false + } + if parts[0] == "rename" { + return os.Rename(full(parts[1]), full(parts[2])) == nil + } + content, err := os.ReadFile(full(parts[1])) + return err == nil && os.WriteFile(full(parts[2]), content, 0644) == nil + case "swap": + if parts[1] == parts[2] || !exists(parts[1]) || !exists(parts[2]) { + return false + } + tmp := full(parts[1]) + ".swap" + return os.Rename(full(parts[1]), tmp) == nil && + os.Rename(full(parts[2]), full(parts[1])) == nil && + os.Rename(tmp, full(parts[2])) == nil + } + return false +} + +// expectedAudit works out whether an audit should pass from the files known when the manifest was +// written and the files on disk afterwards. Files are matched by path first, a file at the path +// of a known file with other content being modified, then files which are not where they were are +// paired with known files which are gone by content, being moved, otherwise new or missing +func expectedAudit(known map[string]string, disk map[string]string, allowNew bool, allowMoved bool) (bool, string) { + var modified, missing, newFiles []string + missingByContent := map[string][]string{} + for p, content := range known { + got, ok := disk[p] + switch { + case !ok: + missingByContent[content] = append(missingByContent[content], p) + case got != content: + modified = append(modified, p) + } + } + moved := 0 + var unknown []string + for p := range disk { + if _, ok := known[p]; !ok { + unknown = append(unknown, p) + } + } + sort.Strings(unknown) + for _, p := range unknown { + if gone := missingByContent[disk[p]]; len(gone) > 0 { + missingByContent[disk[p]] = gone[1:] + moved++ + continue + } + newFiles = append(newFiles, p) + } + for _, gone := range missingByContent { + missing = append(missing, gone...) + } + pass := len(modified) == 0 && len(missing) == 0 && (allowNew || len(newFiles) == 0) && (allowMoved || moved == 0) + return pass, fmt.Sprintf("modified=%v missing=%v new=%v moved=%d", modified, missing, newFiles, moved) +} + +// ambiguous reports if which known file a file on disk is cannot be told from paths and content +// alone, being identical files or files of the same name in different directories, where a file +// may be matched through another directory than the one the audit is matched through +func ambiguous(known map[string]string, disk map[string]string) bool { + contents := map[string]int{} + names := map[string]map[string]bool{} + for _, files := range []map[string]string{known, disk} { + for p, content := range files { + contents[content]++ + name := filepath.Base(p) + if names[name] == nil { + names[name] = map[string]bool{} + } + names[name][p] = true + } + } + for content, n := range contents { + if n > 2 || n == 2 && !sameFile(known, disk, content) { + return true + } + } + for _, paths := range names { + if len(paths) > 1 { + return true + } + } + return false +} + +// sameFile reports if content appears once in each of known and disk, so is not a duplicate +func sameFile(known map[string]string, disk map[string]string, content string) bool { + count := func(files map[string]string) int { + n := 0 + for _, c := range files { + if c == content { + n++ + } + } + return n + } + return count(known) == 1 && count(disk) == 1 +} + +// runAuditScenario writes the manifest, relocates and changes the tree, audits it and returns what +// was wrong with the result, if anything. A pass is always checked, as an audit must never pass when +// a known file was modified or is missing, while a failure is only checked when which known file +// each file is is unambiguous, unless strict +func runAuditScenario(t *testing.T, s *auditScenario, strict bool) string { + if !s.resolvable() { + return "" + } + // removed when the scenario returns, as a sweep runs every seed in one test, where t.TempDir + // would keep every tree until the sweep ends + w, err := os.MkdirTemp("", "hashit-audit-") + if err != nil { + t.Fatal(err) + } + defer func() { + if err := os.RemoveAll(w); err != nil { + t.Errorf("removing scenario directory: %v", err) + } + }() + if real, err := filepath.EvalSymlinks(w); err == nil { + w = real + } + tree := filepath.Join(w, treeName) + writeTree(t, tree, s.files) + + manifest := filepath.Join(w, "out", s.manifestName()) + if s.location != "out" { + manifest = filepath.Join(tree, filepath.FromSlash(s.manifestRel())) + } + if err := os.MkdirAll(filepath.Dir(manifest), 0755); err != nil { + t.Fatal(err) + } + args := []string{"-f", s.format, "-o", manifest} + if s.format == "sum" { + args = append(args, "-c", "md5") + } + if s.absolute { + args = append(args, "--absolute") + } + writeDir, path := tree, "." + if s.fromParent { + writeDir, path = w, treeName + } + if rc, out := runHashit(t, writeDir, append(args, path)...); rc != 0 { + t.Fatalf("writing manifest failed rc=%d: %s\n%v", rc, out, s) + } + if s.invokedFrom != "" { + editInvokedFrom(t, manifest, s.invokedFrom, filepath.Join(tree, "sub")) + } + + // the tree keeps its name so manifests written from its parent still name its files + audited := tree + switch s.relocation { + case "copy", "move": + audited = filepath.Join(w, s.relocation, treeName) + if err := os.MkdirAll(filepath.Dir(audited), 0755); err != nil { + t.Fatal(err) + } + if s.relocation == "move" { + if err := os.Rename(tree, audited); err != nil { + t.Fatal(err) + } + } else if err := copyDir(tree, audited); err != nil { + t.Fatal(err) + } + } + if s.location != "out" { + manifest = filepath.Join(audited, filepath.FromSlash(s.manifestRel())) + } + + exclude := map[string]bool{manifest: true} + for _, suffix := range []string{"-wal", "-shm", "-journal"} { + exclude[manifest+suffix] = true + } + known := readTree(t, audited, exclude) + + var applied []string + for _, change := range s.changes { + if applyChange(audited, change) { + applied = append(applied, change) + } + } + disk := readTree(t, audited, exclude) + + auditDir, auditPath := audited, "." + switch s.auditFrom { + case "parent": + auditDir, auditPath = filepath.Dir(audited), treeName + case "sub": + auditDir, auditPath = filepath.Join(audited, "sub"), ".." + } + auditArgs := []string{"-v", "-a", manifest, auditPath} + if s.allowNew { + auditArgs = append(auditArgs, "--allow-new") + } + if s.allowMoved { + auditArgs = append(auditArgs, "--allow-moved") + } + rc, out := runHashit(t, auditDir, auditArgs...) + want, why := expectedAudit(known, disk, s.allowNew, s.allowMoved) + + problem := "" + switch { + case rc == 2: + problem = "audit error" + case rc != 0 && rc != 1: + // such as -1 when killed by a signal, so the audit never completed + problem = fmt.Sprintf("audit error (exit %d)", rc) + case rc == 0 && !want: + problem = "audit passed but should fail" + case rc == 1 && want && (strict || !ambiguous(known, disk)): + problem = "audit failed but should pass" + default: + return "" + } + return fmt.Sprintf("%s\n%v\napplied=%v expected %s\n%s", problem, s, applied, why, out) +} + +// resolvable reports if a directory hashit matches through names the audited files: the directory +// the manifest was written from, the manifest's directory or the directory the audit is run from. +// Otherwise nothing says where the records are relative to, so what an audit should find is unknown +func (s *auditScenario) resolvable() bool { + if s.absolute { + return s.relocation == "none" + } + // the directory the records are relative to, root or parent of the audited tree + target := "root" + if s.fromParent { + target = "parent" + } + // the directory the manifest was written from only names the audited tree if it was not moved + if s.format != "sum" && s.invokedFrom == "" && s.relocation == "none" { + return true + } + return s.location == "root" && target == "root" || s.auditFrom == target +} + +// editInvokedFrom removes the invoked from line of a hashdeep file, as some hashdeep versions and +// hand edited files have none, or points it at another directory, as when it is stale +func editInvokedFrom(t *testing.T, manifest string, edit string, other string) { + t.Helper() + content, err := os.ReadFile(manifest) + if err != nil { + t.Fatal(err) + } + var lines []string + for _, line := range strings.SplitAfter(string(content), "\n") { + if strings.HasPrefix(line, "## Invoked from: ") { + if edit == "strip" { + continue + } + line = "## Invoked from: " + other + "\n" + } + lines = append(lines, line) + } + if err := os.WriteFile(manifest, []byte(strings.Join(lines, "")), 0644); err != nil { + t.Fatal(err) + } +} + +func copyDir(src string, dst string) error { + return filepath.WalkDir(src, func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + rel, _ := filepath.Rel(src, path) + target := filepath.Join(dst, rel) + if d.IsDir() { + return os.MkdirAll(target, 0755) + } + content, err := os.ReadFile(path) + if err != nil { + return err + } + return os.WriteFile(target, content, 0644) + }) +} + +// FuzzAudit audits random trees which were changed after their manifest was written, in every +// format, comparing the result with what was changed. Run with go test -fuzz FuzzAudit +func FuzzAudit(f *testing.F) { + if runtime.GOOS == "windows" { + f.Skip("scenarios use / separated paths and moving open directories") + } + for _, seed := range auditSeeds { + f.Add(seed) + } + f.Fuzz(func(t *testing.T, seed uint64) { + if problem := runAuditScenario(t, newAuditScenario(seed), false); problem != "" { + t.Error(problem) + } + }) +} + +// TestAuditSweep runs HASHIT_AUDIT_SWEEP random scenarios from HASHIT_AUDIT_SEED, which finds more +// than go test -fuzz as the fuzzer mutates around a few seeds. Audits known to be wrong are found too +func TestAuditSweep(t *testing.T) { + n, _ := strconv.ParseUint(os.Getenv("HASHIT_AUDIT_SWEEP"), 10, 64) + if n == 0 { + t.Skip("set HASHIT_AUDIT_SWEEP to the number of scenarios") + } + start, _ := strconv.ParseUint(os.Getenv("HASHIT_AUDIT_SEED"), 10, 64) + for seed := start; seed < start+n; seed++ { + if problem := runAuditScenario(t, newAuditScenario(seed), false); problem != "" { + t.Errorf("seed %d: %s", seed, problem) + } + } +} + +// auditSeeds are run by go test without -fuzz +var auditSeeds = func() []uint64 { + var seeds []uint64 + for i := uint64(1); i <= 60; i++ { + seeds = append(seeds, i) + } + return seeds +}() + +// TestAuditMatrix audits a tree with no repeated names or content in every format, manifest +// location, relocation and directory the audit is run from, unchanged and after each kind of change +func TestAuditMatrix(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("scenarios use / separated paths and moving open directories") + } + files := map[string]string{"a": "a\n", "sub/b": "b\n", "meta/c": "c\n", "sub/deep/d": "d\n"} + changes := [][]string{ + nil, + {"modify a"}, + {"modify sub/deep/d"}, + {"delete sub/b"}, + {"rename a a.renamed"}, + {"rename sub/b meta/b"}, + {"swap a sub/b"}, + {"copy a sub/a.copy"}, + {"copy sub/b sub/b.orig", "modify sub/b"}, + {"rename sub/b a.old", "rename a sub/b"}, + } + for _, format := range []string{"hashdeep", "sum", "sqlite"} { + for _, location := range []string{"out", "root", "meta"} { + for _, relocation := range []string{"none", "copy", "move"} { + for _, auditFrom := range []string{"root", "parent", "sub"} { + for _, fromParent := range []bool{false, true} { + for i, change := range changes { + for flags := 0; flags < 4; flags++ { + s := &auditScenario{format: format, location: location, relocation: relocation, + auditFrom: auditFrom, fromParent: fromParent, files: files, changes: change, + allowNew: flags&1 != 0, allowMoved: flags&2 != 0} + if !s.resolvable() { + continue + } + name := fmt.Sprintf("%s/%s/%s/%s/parent=%v/change%d/flags%d", format, location, relocation, auditFrom, fromParent, i, flags) + t.Run(name, func(t *testing.T) { + t.Parallel() + if problem := runAuditScenario(t, s, true); problem != "" { + t.Error(problem) + } + }) + } + } + } + } + } + } + } +} + +// TestAuditUserScenario is a sum file written in the directory it lists, as in +// https://github.com/boyter/hashit/issues/12, with another manifest written beside it later +func TestAuditUserScenario(t *testing.T) { + files := map[string]string{"a": "a\n", "sub/b": "b\n"} + for _, allowNew := range []bool{false, true} { + s := &auditScenario{format: "sum", location: "root", relocation: "none", auditFrom: "root", + files: files, changes: []string{"copy a hashes2.md5"}, allowNew: allowNew} + if problem := runAuditScenario(t, s, true); problem != "" { + t.Error(problem) + } + } +} + +// auditRegressions are audits which were wrong, found by reviews and the sweep, see TestAuditSweep +var auditRegressions = []struct { + name string + strict bool + s *auditScenario +}{ + { + // the manifest's directory names meta/README as record ./README, so the record which names + // it through the directory the audit is matched through is never looked up + name: "file moved onto a known path of a name repeated below the manifest passes in a copy", + s: &auditScenario{format: "hashdeep", location: "meta", relocation: "copy", auditFrom: "root", allowMoved: true, + files: map[string]string{"README": "top\n", "meta/README": "meta\n", "w": "w\n", "sub/x": "x\n"}, + changes: []string{"rename meta/README meta/README.old", "rename w meta/README"}}, + }, + { + name: "file moved onto a known path of a name repeated below the manifest passes in a copy, sqlite", + s: &auditScenario{format: "sqlite", location: "meta", relocation: "copy", auditFrom: "root", allowMoved: true, + files: map[string]string{"README": "top\n", "meta/README": "meta\n", "w": "w\n", "sub/x": "x\n"}, + changes: []string{"rename meta/README meta/README.old", "rename w meta/README"}}, + }, + { + name: "file moved onto a known path of a name repeated below the manifest passes in a moved tree", + s: &auditScenario{format: "hashdeep", location: "meta", relocation: "move", auditFrom: "root", allowMoved: true, + files: map[string]string{"README": "top\n", "meta/README": "meta\n", "w": "w\n", "sub/x": "x\n"}, + changes: []string{"rename meta/README meta/README.old", "rename w meta/README"}}, + }, + { + name: "unchanged copy of a tree with a name repeated below the manifest fails", + strict: true, + s: &auditScenario{format: "hashdeep", location: "meta", relocation: "copy", auditFrom: "root", + files: map[string]string{"README": "top\n", "meta/README": "meta\n", "w": "w\n", "sub/x": "x\n"}}, + }, + { + name: "unchanged copy of a tree with a name repeated below the manifest fails, sqlite", + strict: true, + s: &auditScenario{format: "sqlite", location: "meta", relocation: "copy", auditFrom: "root", + files: map[string]string{"README": "top\n", "meta/README": "meta\n", "w": "w\n", "sub/x": "x\n"}}, + }, + { + name: "unchanged tree audited from a subdirectory without invoked from fails", + strict: true, + s: &auditScenario{format: "hashdeep", invokedFrom: "strip", location: "root", relocation: "none", auditFrom: "sub", + files: map[string]string{"b": "BBB\n", "sub/b": "SUBB\n", "sub/c": "C\n"}}, + }, + { + // with no invoked from line the working directory sub names sub/b as record ./b + name: "modified file with a backup passes audited from a subdirectory without invoked from", + s: &auditScenario{format: "hashdeep", invokedFrom: "strip", location: "root", relocation: "none", auditFrom: "sub", + allowNew: true, allowMoved: true, + files: map[string]string{"b": "BBB\n", "sub/b": "SUBB\n", "sub/c": "C\n"}, + changes: []string{"copy sub/b sub/b.orig", "modify sub/b"}}, + }, + { + // a stale invoked from line names some files through sub, which then outvotes the + // manifest's directory, as each file votes only for the first directory naming it + name: "modified file with a backup passes with a stale invoked from", + s: &auditScenario{format: "hashdeep", invokedFrom: "sub", location: "meta", relocation: "none", auditFrom: "root", + allowNew: true, allowMoved: true, + files: map[string]string{"data/README": "content 0\n", "data/b": "content 1\n", "data/data/README": "content README 0\n", + "data/hashes.md5": "content 9\n", "hashes.md5": "content 0\n", "sub/README": "content 8\n", + "sub/deep/README": "content README 1\n", "sub/hashes.md5": "content 3\n"}, + changes: []string{"copy sub/hashes.md5 sub/hashes.md5.orig", "modify sub/hashes.md5"}}, + }, + { + // through the working directory sub, ./x.txt names sub/x.txt, which is identical to x.txt, and + // ./deep/x.txt names sub/deep/x.txt, so they are not looked up through the sum file's directory + name: "file moved onto a known path of a repeated name passes for a sum file audited from a subdirectory", + s: &auditScenario{format: "sum", location: "root", relocation: "none", auditFrom: "sub", allowMoved: true, + files: map[string]string{"data/README": "content 6\n", "data/m.db": "content 2\n", "data/m.hd": "content 4\n", + "data/x.txt": "content 1\n", "meta/x.txt": "content 5\n", "sub/deep/x.txt": "content 3\n", + "sub/x.txt": "content 0\n", "x.txt": "content 0\n"}, + changes: []string{"rename sub/x.txt sub/deep/x.txt.old", "rename sub/deep/x.txt sub/x.txt"}}, + }, + { + // through the working directory ./data/hashes.md5 is the audit file, so is dropped as its + // own entry, although through the sum file's directory it is another file + name: "deleted file of the sum file's name below a directory of the tree's name passes", + s: &auditScenario{format: "sum", location: "root", relocation: "none", auditFrom: "parent", + files: map[string]string{"x": "x\n", treeName + "/hashes.md5": "inner\n"}, + changes: []string{"delete " + treeName + "/hashes.md5"}}, + }, + { + name: "unchanged file of the sum file's name below a directory of the tree's name is new", + strict: true, + s: &auditScenario{format: "sum", location: "root", relocation: "none", auditFrom: "parent", + files: map[string]string{"x": "x\n", treeName + "/hashes.md5": "inner\n"}}, + }, + { + // ./README through the working directory and ./sub/README through the sum file's directory + // are grouped as the same file before the directory is chosen, and their hashes conflict + name: "unchanged sum file at the root audited from a subdirectory with a repeated name fails", + strict: true, + s: &auditScenario{format: "sum", location: "root", relocation: "none", auditFrom: "sub", + files: map[string]string{"README": "top\n", "sub/README": "sub\n", "sub/c": "c\n"}}, + }, + { + // the stale invoked from sub and the working directory each name sub/m.hd, a tie which went + // to invoked from, through which sub/m.hd matches ./m.hd and ./sub/m.hd was moved + name: "file moved onto a known path passes with a stale invoked from naming as many files", + s: &auditScenario{format: "hashdeep", invokedFrom: "sub", location: "meta", relocation: "none", auditFrom: "root", + allowNew: true, allowMoved: true, + files: map[string]string{"m.hd": "content 2\n", "sub/m.hd": "content 0\n"}, + changes: []string{"rename sub/m.hd m.hd.old", "rename m.hd sub/m.hd"}}, + }, + { + // the manifest's directory and the working directory each name meta/README, a tie which went + // to the manifest's directory, through which meta/README matches ./README + name: "file moved onto a known path below the manifest passes in a copy naming as many files, hashdeep", + s: &auditScenario{format: "hashdeep", location: "meta", relocation: "copy", auditFrom: "root", allowMoved: true, + files: map[string]string{"README": "top\n", "meta/README": "meta\n"}, + changes: []string{"rename meta/README meta/README.old", "rename README meta/README"}}, + }, + { + // the manifest's directory and the working directory each name meta/README, a tie which went + // to the manifest's directory, through which meta/README matches ./README + name: "file moved onto a known path below the manifest passes in a copy naming as many files, sqlite", + s: &auditScenario{format: "sqlite", location: "meta", relocation: "copy", auditFrom: "root", allowMoved: true, + files: map[string]string{"README": "top\n", "meta/README": "meta\n"}, + changes: []string{"rename meta/README meta/README.old", "rename README meta/README"}}, + }, + { + // the manifest's directory and the working directory each name meta/README, a tie which went + // to the manifest's directory, through which meta/README matches ./README + name: "file moved onto a known path below the manifest passes in a copy naming as many files, sum", + s: &auditScenario{format: "sum", location: "meta", relocation: "copy", auditFrom: "root", allowMoved: true, + files: map[string]string{"README": "top\n", "meta/README": "meta\n"}, + changes: []string{"rename meta/README meta/README.old", "rename README meta/README"}}, + }, +} + +func TestAuditRegressions(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("scenarios use / separated paths and moving open directories") + } + for _, c := range auditRegressions { + t.Run(c.name, func(t *testing.T) { + if problem := runAuditScenario(t, c.s, c.strict); problem != "" { + t.Error(problem) + } + }) + } +} + +// knownAuditBugs are audits which are wrong and not yet fixed. Each is skipped while it is still +// wrong, and fails once it is right so it can be moved to auditRegressions +var knownAuditBugs []struct { + name string + strict bool + s *auditScenario +} + +func TestAuditKnownBugs(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("scenarios use / separated paths and moving open directories") + } + for _, bug := range knownAuditBugs { + t.Run(bug.name, func(t *testing.T) { + if problem := runAuditScenario(t, bug.s, bug.strict); problem != "" { + t.Skipf("known bug: %s", problem) + } + t.Errorf("known bug is fixed, move it to auditRegressions") + }) + } +} diff --git a/processor/audit.go b/processor/audit.go index 133a472..783cdae 100644 --- a/processor/audit.go +++ b/processor/audit.go @@ -12,6 +12,7 @@ import ( "net/url" "os" "path/filepath" + "slices" "sort" "strings" @@ -110,6 +111,55 @@ func fileHashToRecord(f database.FileHash) *AuditRecord { return r } +// hasCollateClause reports if SQL contains the keyword COLLATE, which hashit never writes, outside +// of strings, quoted names and comments, so a column named collateral or a comment mentioning it is +// not taken as one +func hasCollateClause(sql string) bool { + isWord := func(c byte) bool { + return c == '_' || c == '$' || c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= 0x80 + } + for i := 0; i < len(sql); { + c := sql[i] + switch { + case c == '\'' || c == '"' || c == '`' || c == '[': + // a quote is escaped by doubling it, which reads as the string ending then starting again + end := c + if c == '[' { + end = ']' + } + j := strings.IndexByte(sql[i+1:], end) + if j == -1 { + return false + } + i += j + 2 + case strings.HasPrefix(sql[i:], "--"): + j := strings.IndexByte(sql[i:], '\n') + if j == -1 { + return false + } + i += j + 1 + case strings.HasPrefix(sql[i:], "/*"): + j := strings.Index(sql[i+2:], "*/") + if j == -1 { + return false + } + i += j + 4 + case isWord(c): + j := i + for j < len(sql) && isWord(sql[j]) { + j++ + } + if strings.EqualFold(sql[i:j], "collate") { + return true + } + i = j + default: + i++ + } + } + return false +} + // sqliteAuditHashes returns the hashes stored in the audit database, strongest first. Every row // is written by the same run, so the first row is representative func sqliteAuditHashes(pathName string) ([]string, error) { @@ -140,15 +190,15 @@ func sqliteAuditHashes(pathName string) ([]string, error) { // rowid, so a table made some other way could have a path listed twice with only one audited, // a path matching a file differing in case or spelling of a number, a rowid column, which may // be generated, hiding the real one, or a row without a path - var keyed, shadowed, withoutRowid, text, collates, nullPath int - var collation sql.NullString + var keyed, shadowed, withoutRowid, text, nullPath int + var collation, tableSQL sql.NullString if err := db.QueryRow(`select (select count(*) = 1 and sum(name = 'filepath') = 1 from pragma_table_info('file_hashes') where pk > 0), (select count(*) from pragma_table_xinfo('file_hashes') where lower(name) in ('rowid', 'oid', '_rowid_')), (select count(*) from pragma_table_list where name = 'file_hashes' and wr = 1), (select count(*) from pragma_table_info('file_hashes') where name = 'filepath' and lower(type) = 'text'), - (select count(*) from sqlite_master where name = 'file_hashes' and lower(sql) like '%collate%'), - exists (select 1 from file_hashes where filepath is null)`).Scan(&keyed, &shadowed, &withoutRowid, &text, &collates, &nullPath); err != nil { + (select sql from sqlite_master where name = 'file_hashes'), + exists (select 1 from file_hashes where filepath is null)`).Scan(&keyed, &shadowed, &withoutRowid, &text, &tableSQL, &nullPath); err != nil { return nil, err } var index sql.NullString @@ -160,7 +210,7 @@ func sqliteAuditHashes(pathName string) ([]string, error) { return nil, err } } - if keyed != 1 || shadowed != 0 || withoutRowid != 0 || text != 1 || collates != 0 || nullPath != 0 || !strings.EqualFold(collation.String, "binary") { + if keyed != 1 || shadowed != 0 || withoutRowid != 0 || text != 1 || hasCollateClause(tableSQL.String) || nullPath != 0 || !strings.EqualFold(collation.String, "binary") { return nil, errors.New("audit database was not created by hashit, its file_hashes table must have a text filepath on every row as its primary key, compared exactly, and a rowid") } @@ -202,17 +252,20 @@ func sqliteAuditHashes(pathName string) ([]string, error) { // buildSqlitePathIndex fills temp.paths with the absolute path every record may refer to, in the // same priority order as other audit files: the directory hashit was invoked from, then the -// database's directory, then the working directory. A path takes the record from the most -// preferred directory, then the first record. Records written as hashit writes them, such as +// database's directory, then the working directory. Each directory has its own entry for a path, +// taking the first record naming it through that directory, as the record naming a file through +// the directory the audit is matched through may not be the one naming it through a directory +// earlier in priority order, see Candidate. Records written as hashit writes them, such as // sub/a or ./sub/a, are looked up directly by sqliteLookup, so only other spellings such as // sub//a are indexed. It is held in a temporary table rather than memory so databases larger // than memory can be audited func buildSqlitePathIndex(ctx context.Context, db *sql.DB, bases []string) error { if _, err := db.ExecContext(ctx, `create temp table paths ( - abs text primary key, + abs text not null, filepath text not null, level integer not null, - rid integer not null + rid integer not null, + primary key (abs, level) )`); err != nil { return err } @@ -224,7 +277,7 @@ func buildSqlitePathIndex(ctx context.Context, db *sql.DB, bases []string) error defer func() { _ = tx.Rollback() }() insert, err := tx.PrepareContext(ctx, `insert into temp.paths (abs, filepath, level, rid) values (?, ?, ?, ?) -on conflict (abs) do update set filepath = excluded.filepath, level = excluded.level, rid = excluded.rid where excluded.level < paths.level`) +on conflict (abs, level) do nothing`) if err != nil { return err } @@ -246,13 +299,8 @@ on conflict (abs) do update set filepath = excluded.filepath, level = excluded.l if direct && len(workingDirAncestors()) == 0 { continue } - var keys []string for level, base := range bases { k := absFrom(base, filePath) - if contains(keys, k) { - continue - } - keys = append(keys, k) // when the working directory was reached through a symlink a path can be compared // as another spelling, which sqliteLookup does not try, so only those are indexed if direct && k == absPath(base, filePath) { @@ -289,9 +337,18 @@ func isDirectSpelling(p string) bool { return filepath.Clean(p) == p } -// sqliteLookup finds the record for the absolute path of a file on disk, returning its path in -// the database and the priority of the directory it matched through, or false if none matches -func sqliteLookup(ctx context.Context, tx *sql.Tx, bases []string, abs string) (string, int, bool, error) { +// sqliteCandidate is a record naming a file on disk through one of the directories relative paths +// may be relative to, by its path in the database, see Candidate +type sqliteCandidate struct { + filePath string + level int +} + +// sqliteLookup finds the records for the absolute path of a file on disk, one for each directory +// through which a record names it, in priority order, as which is used depends on the directory the +// audit is matched through, see LookupLevels +func sqliteLookup(ctx context.Context, stmts *sqliteStatements, bases []string, abs string) ([]sqliteCandidate, error) { + var found []sqliteCandidate for level, base := range bases { var candidates []any if level == 0 { @@ -306,22 +363,88 @@ func sqliteLookup(ctx context.Context, tx *sql.Tx, bases []string, abs string) ( candidates = append(candidates, nil) } in := strings.Repeat("?, ", len(candidates)-1) + "?" - - var filePath string - err := tx.QueryRowContext(ctx, `select filepath from ( + stmt, err := stmts.get(ctx, `select filepath from ( select rowid as rid, filepath from file_hashes where filepath in (`+in+`) union all select rid, filepath from temp.paths where abs = ? and level = ? -) order by rid limit 1`, append(candidates, abs, level)...).Scan(&filePath) +) order by rid limit 1`) + if err != nil { + return nil, err + } + + var filePath string + err = stmt.QueryRowContext(ctx, append(candidates, abs, level)...).Scan(&filePath) if errors.Is(err, sql.ErrNoRows) { continue } if err != nil { - return "", 0, false, err + return nil, err } - return filePath, level, true, nil + found = append(found, sqliteCandidate{filePath: filePath, level: level}) + } + return found, nil +} + +// sqliteStatements prepares each statement once for a transaction, as a lookup is made through +// every directory for every file and parsing the statement each time costs more than running it +type sqliteStatements struct { + tx *sql.Tx + stmts map[string]*sql.Stmt +} + +func (s *sqliteStatements) get(ctx context.Context, query string) (*sql.Stmt, error) { + if stmt, ok := s.stmts[query]; ok { + return stmt, nil + } + stmt, err := s.tx.PrepareContext(ctx, query) + if err != nil { + return nil, err + } + if s.stmts == nil { + s.stmts = map[string]*sql.Stmt{} } - return "", 0, false, nil + s.stmts[query] = stmt + return stmt, nil +} + +// ExecContext, PrepareContext, QueryContext and QueryRowContext let the generated queries use the +// transaction, preparing the single row queries made for every file once +func (s *sqliteStatements) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) { + return s.tx.ExecContext(ctx, query, args...) +} + +func (s *sqliteStatements) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) { + return s.tx.PrepareContext(ctx, query) +} + +func (s *sqliteStatements) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) { + return s.tx.QueryContext(ctx, query, args...) +} + +func (s *sqliteStatements) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row { + stmt, err := s.get(ctx, query) + if err != nil { + return s.tx.QueryRowContext(ctx, query, args...) + } + return stmt.QueryRowContext(ctx, args...) +} + +func (s *sqliteStatements) close() { + for _, stmt := range s.stmts { + _ = stmt.Close() + } + s.stmts = nil +} + +// pickSqliteCandidate returns the first candidate, in priority order, which is kept once the +// directory the audit is matched through has been chosen, see pickCandidate +func pickSqliteCandidate(candidates []sqliteCandidate, chosen int) (sqliteCandidate, bool) { + for _, c := range candidates { + if keepsMatch(chosen, c.level, filepath.IsAbs(c.filePath)) { + return c, true + } + } + return sqliteCandidate{}, false } // claimSqliteMatches decides which file on disk claims each record once the directory the audit @@ -338,11 +461,16 @@ func claimSqliteMatches(ctx context.Context, tx *sql.Tx, chosen int) (int, int, )`); err != nil { return 0, 0, nil, err } + // each file takes the first record kept, in priority order, see pickCandidate, then each record + // the file matching through the earliest directory, then the first path if _, err := tx.ExecContext(ctx, `insert into temp.seen (filepath, status, disk_file) select filepath, status, disk_file from ( select filepath, status, disk_file, row_number() over (partition by filepath order by level, disk_file) as n - from temp.matches where independent = 1 or ? = -1 or level = ? -) where n = 1`, chosen, chosen); err != nil { + from temp.matches m where (independent = 1 or ?1 = -1 or level = ?1) and not exists ( + select 1 from temp.matches e where e.disk_file = m.disk_file and e.level < m.level + and (e.independent = 1 or ?1 = -1 or e.level = ?1) + ) +) where n = 1`, chosen); err != nil { return 0, 0, nil, err } @@ -369,7 +497,7 @@ select filepath, status, disk_file from ( } _ = rows.Close() - rows, err = tx.QueryContext(ctx, "select disk_file, result from temp.matches where disk_file not in (select disk_file from temp.seen)") + rows, err = tx.QueryContext(ctx, "select disk_file, min(result) from temp.matches where disk_file not in (select disk_file from temp.seen) group by disk_file") if err != nil { return 0, 0, nil, err } @@ -514,12 +642,13 @@ func doSqliteAudit(input chan Result) (string, bool) { // every file matching a record is held until the directory the audit is matched through is // chosen, see chooseLevel, with its result so it can be treated as new _, err = db.Exec(`create temp table matches ( - disk_file text primary key, + disk_file text not null, filepath text not null, status integer not null, level integer not null, independent integer not null, - result text not null + result text not null, + primary key (disk_file, level) )`) if err != nil { printError(fmt.Sprintf("failed to create temporary audit table: %s", err.Error())) @@ -538,28 +667,15 @@ func doSqliteAudit(input chan Result) (string, bool) { printError(fmt.Sprintf("failed to prepare audit statement: %s", err.Error())) return "", false } - txQueries := queries.WithTx(tx) + stmts := &sqliteStatements{tx: tx} + defer stmts.close() + txQueries := database.New(stmts) examinedCount := 0 // new files are usually few, so are held in memory indexed by hash to identify moves var newFileCandidates []Result - // lookupRecord finds the record for a file on disk by its absolute path, with the priority of - // the directory it matched through and whether its path names the file through every directory - lookupRecord := func(file string) (*AuditRecord, int, bool, error) { - abs := absFrom(cwd, file) - filePath, level, ok, err := sqliteLookup(ctx, tx, bases, abs) - if err != nil || !ok { - return nil, 0, false, err - } - row, err := txQueries.FileHashByFilePath(ctx, filePath) - if err != nil { - return nil, 0, false, err - } - // an absolute path names the same file through every directory, see baseLevel - return fileHashToRecord(row), level, filepath.IsAbs(filePath), nil - } votes := map[int]int{} seenFiles := map[string]bool{} @@ -570,36 +686,80 @@ func doSqliteAudit(input chan Result) (string, bool) { } examinedCount++ - record, level, independent, err := lookupRecord(res.File) + candidates, err := sqliteLookup(ctx, stmts, bases, absFrom(cwd, res.File)) if err != nil { printError(fmt.Sprintf("failed to query audit database for file %s: %s", res.File, err.Error())) continue } - if record == nil { + if len(candidates) == 0 { newFileCandidates = append(newFileCandidates, res) continue } - - status := FileModified - if recordMatches(record, res) { - status = FileMatched - } b, err := json.Marshal(res) if err != nil { printError(fmt.Sprintf("failed to record audit result for file %s: %s", res.File, err.Error())) continue } - if _, err := insertMatch.ExecContext(ctx, res.File, record.Filename, int(status), level, independent, string(b)); err != nil { - printError(fmt.Sprintf("failed to record audit result for file %s: %s", res.File, err.Error())) - continue + + // every record naming the file is held, with a vote for each directory, see voteLevels + var levels []Candidate + for _, c := range candidates { + levels = append(levels, Candidate{Level: c.level, Independent: filepath.IsAbs(c.filePath)}) } - if !independent { + for _, level := range voteLevels(levels) { votes[level]++ } + for _, c := range candidates { + row, err := txQueries.FileHashByFilePath(ctx, c.filePath) + if err != nil { + printError(fmt.Sprintf("failed to query audit database for file %s: %s", res.File, err.Error())) + break + } + status := FileModified + if recordMatches(fileHashToRecord(row), res) { + status = FileMatched + } + // an absolute path names the same file through every directory, see Candidate + independent := filepath.IsAbs(c.filePath) + if _, err := insertMatch.ExecContext(ctx, res.File, c.filePath, int(status), c.level, independent, string(b)); err != nil { + printError(fmt.Sprintf("failed to record audit result for file %s: %s", res.File, err.Error())) + break + } + } } _ = insertMatch.Close() chosen := chooseLevel(votes) + tied := tiedLevels(votes, chosen) + if len(tied) == 0 { + return judgeSqliteAudit(ctx, db, tx, stmts, bases, cwd, chosen, newFileCandidates, examinedCount) + } + return judgeTied(AuditFile, bases, chosen, tied, func(first bool, level int) (string, bool) { + if first { + return judgeSqliteAudit(ctx, db, tx, stmts, bases, cwd, level, slices.Clone(newFileCandidates), examinedCount) + } + // the tables of the last judgement, as temp.matches holds every directory + for _, table := range []string{"seen", "duplicates", "repeated"} { + if _, err := db.ExecContext(ctx, "drop table if exists temp."+table); err != nil { + printError(fmt.Sprintf("failed to clear temporary audit table: %s", err.Error())) + return "", false + } + } + tx, err := db.BeginTx(ctx, nil) + if err != nil { + printError(fmt.Sprintf("failed to begin audit transaction: %s", err.Error())) + return "", false + } + stmts := &sqliteStatements{tx: tx} + defer stmts.close() + return judgeSqliteAudit(ctx, db, tx, stmts, bases, cwd, level, slices.Clone(newFileCandidates), examinedCount) + }) +} + +// judgeSqliteAudit matches files on disk to rows through the chosen directory and reports the +// result, committing tx +func judgeSqliteAudit(ctx context.Context, db *sql.DB, tx *sql.Tx, stmts *sqliteStatements, bases []string, cwd string, + chosen int, newFileCandidates []Result, examinedCount int) (string, bool) { matched, filesModified, unclaimed, err := claimSqliteMatches(ctx, tx, chosen) if err != nil { _ = tx.Rollback() @@ -622,15 +782,16 @@ func doSqliteAudit(input chan Result) (string, bool) { sort.Strings(failedList) for _, f := range failedList { abs := absFrom(cwd, f) - filePath, level, ok, err := sqliteLookup(ctx, tx, bases, abs) + candidates, err := sqliteLookup(ctx, stmts, bases, abs) + c, ok := pickSqliteCandidate(candidates, chosen) if err == nil && ok { - unreadableAt[abs] = level + unreadableAt[abs] = c.level var claimed int - err = tx.QueryRowContext(ctx, "select count(*) from temp.seen where filepath = ?", filePath).Scan(&claimed) + err = tx.QueryRowContext(ctx, "select count(*) from temp.seen where filepath = ?", c.filePath).Scan(&claimed) ok = err == nil && claimed == 0 } if ok { - unreadable[filePath] = f + unreadable[c.filePath] = f } else { unreadableNew = append(unreadableNew, f) } diff --git a/processor/audit_fuzz_test.go b/processor/audit_fuzz_test.go new file mode 100644 index 0000000..8cc0889 --- /dev/null +++ b/processor/audit_fuzz_test.go @@ -0,0 +1,153 @@ +// SPDX-License-Identifier: MIT + +package processor + +import ( + "path/filepath" + "runtime" + "strings" + "testing" +) + +// FuzzSumLineRoundTrip checks every filename written to a sum file is read back unchanged +func FuzzSumLineRoundTrip(f *testing.F) { + for _, s := range []string{"a.txt", "back\\slash.txt", "new\nline.txt", "c \"quoted\", comma.txt", "cr\r", " lead", "MD5 (x) = y", "*star"} { + f.Add(s) + } + f.Fuzz(func(t *testing.T, file string) { + if file == "" { + return + } + line := strings.TrimSuffix(sumLine(testMD5, file), "\n") + name, value, filename, ok := parseSumLine(line, nil) + if !ok || name != "md5" || value != testMD5 || filename != file { + t.Errorf("%q: round trip failed got %v %q %q %q", file, ok, name, value, filename) + } + }) +} + +// FuzzParseSumLine checks any line is either rejected or gives a known hash of the right length +// and a filename +func FuzzParseSumLine(f *testing.F) { + for _, s := range []string{ + testMD5 + " a.txt", + testMD5 + " *a.txt", + "\\" + testMD5 + " back\\\\slash", + "MD5 (a.txt) = " + testMD5, + "SHA256 (a (1).txt) = " + testSHA256, + "MD4 (a) = " + testMD5, + testSHA1 + " ", + "", + } { + f.Add(s) + } + f.Fuzz(func(t *testing.T, line string) { + name, value, filename, ok := parseSumLine(line, nil) + if !ok { + return + } + if filename == "" { + t.Errorf("%q: empty filename accepted", line) + } + if !isHex(value) || len(value) != hashLengths[name] { + t.Errorf("%q: %s value %q is not %d hex digits", line, name, value, hashLengths[name]) + } + }) +} + +// FuzzSplitHashdeepLine checks a split line has every column and joins back to the line +func FuzzSplitHashdeepLine(f *testing.F) { + f.Add("2,abc,def,a.txt", 4, 3) + f.Add("2,abc,def,b, with comma.txt", 4, 3) + f.Add("2,abc,a,b.txt,2026-01-01 10:00:00", 4, 2) + f.Add(",,,", 4, 3) + f.Fuzz(func(t *testing.T, line string, columns int, filenameIdx int) { + if columns < 1 || columns > 16 || filenameIdx < 0 || filenameIdx >= columns { + return + } + fields, err := splitHashdeepLine(line, columns, filenameIdx) + if err != nil { + return + } + if len(fields) != columns { + t.Fatalf("%q: expected %d columns got %d", line, columns, len(fields)) + } + if fields[filenameIdx] == "" { + t.Errorf("%q: empty filename accepted", line) + } + if joined := strings.Join(fields, ","); joined != line { + t.Errorf("%q: columns join to %q", line, joined) + } + }) +} + +// FuzzNewAuditor checks any audit file is either refused or parsed without panicking, and that +// every record parsed can be looked up +func FuzzNewAuditor(f *testing.F) { + for _, s := range []string{ + "%%%% HASHDEEP-1.0\n%%%% size,md5,sha256,filename\n## Invoked from: /srv/media\n##\n2," + testMD5 + "," + testSHA256 + ",a.txt\n", + "%%%% HASHDEEP-1.0\r\n%%%% size,md5,filename\r\n##\r\n2," + testMD5 + ",./a\r\n2," + testMD5 + ",a\r\n", + testMD5 + " a.txt\n" + testMD5 + " ./a.txt\n" + testMD5 + " /srv/media/a.txt\n", + "MD5 (a.txt) = " + testMD5 + "\nSHA1 (a.txt) = " + testSHA1 + "\n", + "\\" + testMD5 + " new\\nline\n", + "", + } { + f.Add(s) + } + f.Fuzz(func(t *testing.T, input string) { + hdl, err := NewAuditor(input, "/hashit-fuzz/srv/media/hashes.txt") + if err != nil { + return + } + if hdl.Count() < 0 || hdl.Count() > len(hdl.Records()) { + t.Errorf("count %d with %d records", hdl.Count(), len(hdl.Records())) + } + for _, r := range hdl.Records() { + if r.Filename == "" { + t.Errorf("record with an empty filename") + } + } + }) +} + +// FuzzAbsFrom checks a path resolved against a directory is absolute and resolves to itself +func FuzzAbsFrom(f *testing.F) { + if runtime.GOOS == "windows" { + f.Skip("unix paths") + } + for _, s := range []string{"a.txt", "./sub/../a.txt", "../other/a.txt", "/abs/./a.txt", "..", "a/", "a/.", "//a", "../../../.."} { + f.Add(s) + } + f.Fuzz(func(t *testing.T, p string) { + if p == "" || strings.ContainsRune(p, 0) { + return + } + base := "/hashit-fuzz/srv/media" + got := absFrom(base, p) + if !filepath.IsAbs(got) { + t.Fatalf("%q: %q is not absolute", p, got) + } + if again := absFrom(base, got); again != got { + t.Errorf("%q: %q resolves again to %q", p, got, again) + } + if again := absFrom("/elsewhere", got); again != got { + t.Errorf("%q: absolute %q depends on the directory, got %q", p, got, again) + } + }) +} + +// FuzzOsClean checks cleaning a path twice gives the same path +func FuzzOsClean(f *testing.F) { + for _, s := range []string{"a/../b", "/a/./b/", "..", "a//b", "/../a", "./a"} { + f.Add(s) + } + f.Fuzz(func(t *testing.T, p string) { + if p == "" || strings.ContainsRune(p, 0) { + return + } + once := osClean(p) + if twice := osClean(once); twice != once { + t.Errorf("%q: cleaned to %q then %q", p, once, twice) + } + }) +} diff --git a/processor/audit_parser.go b/processor/audit_parser.go index b522e2d..991da2c 100644 --- a/processor/audit_parser.go +++ b/processor/audit_parser.go @@ -12,6 +12,7 @@ import ( "path/filepath" "regexp" "runtime" + "slices" "sort" "strconv" "strings" @@ -38,6 +39,7 @@ type AuditRecord struct { type Auditor struct { records []*AuditRecord pathLookup map[string]*AuditRecord // every path key a record can be found by + levelLookup []map[string]*AuditRecord // for each of bases, the path each record names through it hashLookup map[string][]*AuditRecord // "hashname:value" to records, used to find moved files hashNames []string // hashes present in the audit file which we are able to calculate bases []string // absolute directories relative paths may be relative to, in priority order @@ -46,6 +48,11 @@ type Auditor struct { duplicates []duplicateRecord // records dropped as listing the path of another, see restoreDuplicates sumFile bool // a sum file, where every line for a path is checked sameFile map[string][]*AuditRecord // sum file lines naming the same file through different paths, by its real path + ownEntries []*AuditRecord // records which may be the audit file listing itself, see settleOwnEntries + ownTarget auditFileTarget // the audit file, see settleOwnEntries + source string // the audit file's contents, see reparse + sourceName string // the audit file's path, see reparse + excluded []string // paths passed to Exclude, see reparse } type FileStatus int @@ -161,6 +168,8 @@ func NewAuditor(input string, auditFilename string) (*Auditor, error) { hashLookup: map[string][]*AuditRecord{}, } hdl.cwd = workingDir() + hdl.source = input + hdl.sourceName = auditFilename var err error if isHashdeepFormat(input) { @@ -176,8 +185,10 @@ func NewAuditor(input string, auditFilename string) (*Auditor, error) { // copied elsewhere, where the invoked from directory no longer applies hdl.bases = auditBases(hdl.primaryBase, auditFilename, hdl.cwd) hdl.removeDuplicates() - if conflicts := hdl.conflicts(); conflicts != 0 { - printWarn(fmt.Sprintf("audit file lists different hashes for the same path, which are reported as modified, paths: %d", conflicts)) + // lines of a sum file naming the same file are only known once the directory the audit is + // matched through is chosen, see GroupSameFile + if !hdl.sumFile { + hdl.warnConflicts() } if err != nil { return nil, err @@ -228,29 +239,72 @@ func (hdl *Auditor) Lookup(file string) *AuditRecord { return hdl.pathLookup[absFrom(hdl.cwd, file)] } -// LookupLevel finds the record for a file on disk, with the priority of the directory it matched -// through and whether the record names the same file through every directory, see baseLevel -func (hdl *Auditor) LookupLevel(file string) (*AuditRecord, int, bool) { - r := hdl.Lookup(file) - if r == nil { - return nil, 0, false +// Candidate is a record which names a file on disk through one of the directories relative paths +// may be relative to, with the priority of that directory and whether it is an absolute path, which +// names the same file through every directory. An audit is only ever matched through one directory, +// see chooseLevel. A relative path which happens to name the same file through every directory, +// such as ../y/a through sibling directories, is treated as relative, which can only report a move +type Candidate struct { + Record *AuditRecord + Level int + Independent bool +} + +// LookupLevels finds every record naming a file on disk, one for each directory through which a +// record names it, in priority order. Which is used depends on the directory the audit is matched +// through, see chooseLevel and pickCandidate, as the record naming a file through another +// directory, such as ./README naming meta/README through a manifest's directory meta, is a +// different file to the record naming it through the chosen one +func (hdl *Auditor) LookupLevels(file string) []Candidate { + abs := absFrom(hdl.cwd, file) + var candidates []Candidate + for level, lookup := range hdl.levelLookup { + if r := lookup[abs]; r != nil { + candidates = append(candidates, Candidate{Record: r, Level: level, Independent: filepath.IsAbs(r.Filename)}) + } + } + return candidates +} + +// reparse returns the audit file parsed again with nothing yet matched, so an audit can be judged +// through another directory, see judgeTied +func (hdl *Auditor) reparse() (*Auditor, error) { + fresh, err := NewAuditor(hdl.source, hdl.sourceName) + if err != nil { + return nil, err + } + for _, path := range hdl.excluded { + fresh.Exclude(path) + } + return fresh, nil +} + +// pickCandidate returns the first candidate, in priority order, which is kept once the directory +// the audit is matched through has been chosen, see keepsMatch +func pickCandidate(candidates []Candidate, chosen int) (Candidate, bool) { + for _, c := range candidates { + if keepsMatch(chosen, c.Level, c.Independent) { + return c, true + } } - level, independent := baseLevel(hdl.bases, r.Filename, absFrom(hdl.cwd, file)) - return r, level, independent + return Candidate{}, false } -// baseLevel returns the priority of the first directory through which the path of a record names -// the absolute path of a file, and whether it is an absolute path, which names the same file -// through every directory. An audit is only ever matched through one directory, see chooseLevel. -// A relative path which happens to name the same file through every directory, such as ../y/a -// through sibling directories, is treated as relative, which can only report a move -func baseLevel(bases []string, p string, abs string) (int, bool) { - for i, base := range bases { - if absFrom(base, p) == abs { - return i, filepath.IsAbs(p) +// voteLevels returns every directory through which a relative record names a file, see chooseLevel. +// A file an absolute record names does not vote, as which file it is does not depend on a directory, +// so a relative record naming it through another directory, such as a in a database invoked from D +// naming T/a through the working directory T, is not evidence for that directory +func voteLevels(candidates []Candidate) []int { + var levels []int + for _, c := range candidates { + if c.Independent { + return nil + } + if !slices.Contains(levels, c.Level) { + levels = append(levels, c.Level) } } - return -1, filepath.IsAbs(p) + return levels } // chooseLevel returns the directory an audit is matched through from the number of files on disk @@ -269,6 +323,23 @@ func chooseLevel(votes map[int]int) int { return chosen } +// tiedLevels returns every directory as many files matched through as the one chosen, see +// chooseLevel, when there is more than one, as then which the audit is matched through is not +// decided by the files on disk +func tiedLevels(votes map[int]int, chosen int) []int { + var tied []int + for level, n := range votes { + if chosen != -1 && n == votes[chosen] { + tied = append(tied, level) + } + } + if len(tied) < 2 { + return nil + } + sort.Ints(tied) + return tied +} + // judgingBases returns the directories through which records are judged to name the same path: the // one the audit is matched through, or every directory when none was chosen, as when every file // matched an absolute record nothing says which directory the relative records are relative to @@ -641,11 +712,20 @@ func auditBases(primary string, auditFile string, cwd string) []string { // Exclude removes any record which refers to the supplied path, which is used to remove the // audit file itself as it can never match its own hash func (hdl *Auditor) Exclude(path string) { + hdl.excluded = append(hdl.excluded, path) target := auditFileTarget{abs: absFrom(hdl.cwd, path), real: realPath(path)} + hdl.ownTarget = target var records []*AuditRecord for _, r := range hdl.records { - if !hdl.isOwnEntry(r, target) { + switch { + case hdl.isOwnEntry(r, target): + case hdl.primaryBase == "" && target.matches([]string{hdl.primaryKey(r)}): + // without the directory paths were created relative to, the working directory may not + // be the directory the audit is matched through, see settleOwnEntries + hdl.ownEntries = append(hdl.ownEntries, r) + records = append(records, r) + default: records = append(records, r) } } @@ -655,6 +735,7 @@ func (hdl *Auditor) Exclude(path string) { hdl.records = nil hdl.pathLookup = map[string]*AuditRecord{} + hdl.levelLookup = nil hdl.hashLookup = map[string][]*AuditRecord{} hdl.hashNames = nil for _, r := range records { @@ -676,18 +757,34 @@ func (hdl *Auditor) recordKeys(r *AuditRecord) []string { // isOwnEntry reports if the record is the audit file listing itself, which happens when it is // written by a shell redirect into the directory being hashed. The record must resolve to the -// audit file using the directory paths are relative to, being the invoked from directory for -// hashdeep files or the working directory otherwise. A record which only resolves to it some -// other way, such as through the audit file's own directory after a tree has been copied, must -// also describe an empty file, as the audit file was when it was hashed. Otherwise it may be a -// different file which happens to share the audit file's name, and must still be audited +// audit file using the invoked from directory of a hashdeep file. A record which only resolves to +// it some other way, such as through the audit file's own directory after a tree has been copied, +// must also describe an empty file, as the audit file was when it was hashed. Otherwise it may be +// a different file which happens to share the audit file's name, and must still be audited. Without +// an invoked from directory a record resolving to it through the working directory is decided once +// the directory the audit is matched through is chosen, see settleOwnEntries func (hdl *Auditor) isOwnEntry(r *AuditRecord, target auditFileTarget) bool { - if target.matches([]string{hdl.primaryKey(r)}) { + if hdl.primaryBase != "" && target.matches([]string{hdl.primaryKey(r)}) { return true } return target.matches(hdl.recordKeys(r)) && isEmptyRecord(r) } +// settleOwnEntries drops each record which names the audit file through the working directory, when +// there is no invoked from directory, if it also names the audit file through the directory the +// audit is matched through and no file on disk was checked against it, as it is the audit file +// listing itself. Otherwise it names another file, such as data/data/hashes.md5 for a sum file +// data/hashes.md5 written in data and audited from its parent, which is audited as any other +func (hdl *Auditor) settleOwnEntries(chosen int, claimed func(*AuditRecord) bool) { + base := hdl.bases[max(chosen, 0)] + for _, r := range hdl.ownEntries { + if !claimed(r) && hdl.ownTarget.matches([]string{absFrom(base, r.Filename)}) { + r.Matched = true + r.Duplicate = true + } + } +} + // auditFileTarget is the audit file being excluded, by absolute and real path, as it may be // supplied through a symlinked path which differs from the path its records were written with type auditFileTarget struct { @@ -722,7 +819,7 @@ func (hdl *Auditor) removeDuplicates() { key := hdl.primaryKey(r) if hdl.sumFile { // only lines naming the same path through every directory, as a relative line can be - // found through the sum file's directory while an absolute one cannot, see groupSameFile + // found through the sum file's directory while an absolute one cannot, see GroupSameFile key = strings.Join(hdl.recordKeys(r), "\x00") } if first, ok := seen[key]; ok { @@ -746,9 +843,6 @@ func (hdl *Auditor) removeDuplicates() { hdl.addRecord(r) } } - if hdl.sumFile { - hdl.groupSameFile() - } } // duplicateRecord is a record dropped as listing the path of the first record listing it @@ -786,6 +880,13 @@ func (hdl *Auditor) restoreDuplicates(chosen int) map[string]*AuditRecord { return restored } +// warnConflicts reports the paths listed with different hashes, which can never match +func (hdl *Auditor) warnConflicts() { + if conflicts := hdl.conflicts(); conflicts != 0 { + printWarn(fmt.Sprintf("audit file lists different hashes for the same path, which are reported as modified, paths: %d", conflicts)) + } +} + // warnDuplicates reports the records dropped as listing the path of another func (hdl *Auditor) warnDuplicates() { if len(hdl.duplicates) != 0 { @@ -793,24 +894,49 @@ func (hdl *Auditor) warnDuplicates() { } } -// groupSameFile groups the lines of a sum file which name the same file through different paths. -// A sum file has no directory its paths were created relative to, so lines can name the same file -// through the sum file's directory but not through the working directory, or through a symlinked -// directory. Each line is kept, as its own path may be the one which is scanned, and a line is only -// not reported on its own when another line was checked against the same file. Lines listing -// different values of a hash for the file can never match -func (hdl *Auditor) groupSameFile() { - // the records naming each path through any directory, so most records need no lookup on disk - counts := make(map[string]int, len(hdl.records)*len(hdl.bases)) +// GroupSameFile groups the lines of a sum file which name the same file through different paths, +// such as ./a, a and its absolute path, through the directory the audit is matched through, or every +// directory when none was chosen, see judgingBases. Lines naming the same file only through another +// directory, such as ./README through the working directory sub and ./sub/README through the sum +// file's directory, name different files. When as many files matched through other directories as +// through the chosen one, see tiedLevels, lines are grouped through each of them, as either could be +// the directory the sum file is relative to, so lines naming a file differently through them cannot +// both be right. Each line is kept, as its own path may be the one which is scanned, and a line is +// only not reported on its own when another line was checked against the same file. Lines listing +// different values of a hash for the file can never match, which is warned of once grouped +func (hdl *Auditor) GroupSameFile(chosen int, tied []int) { + if !hdl.sumFile { + return + } + defer hdl.warnConflicts() + bases := judgingBases(hdl.bases, chosen) + if len(tied) != 0 { + bases = nil + for _, level := range tied { + bases = append(bases, hdl.bases[level]) + } + } + keysOf := func(r *AuditRecord) []string { + var keys []string + for _, base := range bases { + if k := absFrom(base, r.Filename); !contains(keys, k) { + keys = append(keys, k) + } + } + return keys + } + + // the records naming each path, so most records need no lookup on disk + counts := make(map[string]int, len(hdl.records)*len(bases)) for _, r := range hdl.records { - for _, k := range hdl.recordKeys(r) { + for _, k := range keysOf(r) { counts[k]++ } } groups := map[string][]*AuditRecord{} for _, r := range hdl.records { - keys := hdl.recordKeys(r) + keys := keysOf(r) for _, k := range keys { if counts[k] > 1 { // the first file it names, by where it really is, as that is the file it is checked @@ -936,13 +1062,21 @@ func (hdl *Auditor) buildLookups() { // Every record's resolution against the directory paths were created relative to takes priority // over any other resolution, then against the next directory, so a record resolved through the // audit file's directory never takes the path of a different record. For each directory the - // first record wins - for _, base := range hdl.bases { + // first record wins. Each directory is also kept on its own, as which is used is only known + // once the directory the audit is matched through is chosen, see LookupLevels + hdl.levelLookup = make([]map[string]*AuditRecord, len(hdl.bases)) + for level, base := range hdl.bases { + lookup := make(map[string]*AuditRecord, len(hdl.records)) for _, r := range hdl.records { - if k := absFrom(base, r.Filename); hdl.pathLookup[k] == nil { + k := absFrom(base, r.Filename) + if lookup[k] == nil { + lookup[k] = r + } + if hdl.pathLookup[k] == nil { hdl.pathLookup[k] = r } } + hdl.levelLookup[level] = lookup } seen := map[string]bool{} diff --git a/processor/audit_test.go b/processor/audit_test.go index 757de26..bc0c629 100644 --- a/processor/audit_test.go +++ b/processor/audit_test.go @@ -304,3 +304,28 @@ func TestJoinText(t *testing.T) { } } } + +func TestHasCollateClause(t *testing.T) { + cases := []struct { + sql string + want bool + }{ + {"create table file_hashes (filepath text primary key, md5 text)", false}, + {"create table file_hashes (filepath text collate nocase primary key)", true}, + {"CREATE TABLE file_hashes (filepath TEXT COLLATE NOCASE PRIMARY KEY)", true}, + {"create table file_hashes (filepath text primary key, x text collate\tnocase)", true}, + {"create table file_hashes (filepath text primary key, collateral text)", false}, + {"create table file_hashes (filepath text primary key, \"collate\" text)", false}, + {"create table file_hashes (filepath text primary key, [collate] text, `collate` text)", false}, + {"create table file_hashes (filepath text primary key, note text default 'see collate list')", false}, + {"create table file_hashes (filepath text primary key, note text default 'it''s collate')", false}, + {"create table file_hashes (filepath text primary key -- collate nocase\n)", false}, + {"create table file_hashes (filepath text primary key /* collate */, x text collate binary)", true}, + {"create table file_hashes (filepath text primary key, \"a\"\"collate\" text) ", false}, + } + for _, c := range cases { + if got := hasCollateClause(c.sql); got != c.want { + t.Errorf("%q: expected %v got %v", c.sql, c.want, got) + } + } +} diff --git a/processor/formatters.go b/processor/formatters.go index 1a45386..ff3f69a 100644 --- a/processor/formatters.go +++ b/processor/formatters.go @@ -11,6 +11,7 @@ import ( "io" "os" "path/filepath" + "slices" "sort" "strings" "sync" @@ -66,6 +67,10 @@ func (c *checkedWriter) Write(p []byte) (int, error) { return n, err } +// warningsMuted stops printWarn, while an audit is judged again through another directory and +// would repeat the warnings already given, see judgeTied +var warningsMuted bool + // stdout is used for all results written to standard output var stdout = &checkedWriter{w: os.Stdout} @@ -104,6 +109,9 @@ func exitCode(valid bool) int { // Used for problems which do not stop processing, such as a flag being ignored func printWarn(msg string) { + if warningsMuted { + return + } _, _ = fmt.Fprintln(os.Stderr, fmt.Sprintf("WARN %s: %s", getFormattedTime(), msg)) } @@ -216,8 +224,118 @@ func auditFailed(modified, moved, newFiles, missing int) bool { return modified > 0 || missing > 0 } +// auditFound is a file on disk named by at least one record, with every record naming it +type auditFound struct { + res Result + candidates []Candidate +} + +// lookupResults finds the records naming each file on disk, returning the files with none as new +func lookupResults(results []Result) ([]auditFound, []Result) { + var founds []auditFound + var newFiles []Result + for _, res := range results { + candidates := auditor.LookupLevels(res.File) + if len(candidates) == 0 { + newFiles = append(newFiles, res) + continue + } + founds = append(founds, auditFound{res: res, candidates: candidates}) + } + return founds, newFiles +} + func doAudit(input chan Result) (string, bool) { - examinedCount := 0 + var results []Result + seen := map[string]bool{} + for res := range input { + // overlapping paths such as . and ./sub supply the same file twice + if isDuplicateFile(seen, res.File) { + continue + } + results = append(results, res) + } + + // The directory the audit is matched through is chosen once every file has arrived, see + // chooseLevel, so files matching a record are held until then with every record naming them + founds, newFileCandidates := lookupResults(results) + votes := map[int]int{} + for _, f := range founds { + // a file votes for every directory a record names it through, as voting only for the + // first would let a directory which happens to name some files through other records + // outvote the one naming every file + for _, level := range voteLevels(f.candidates) { + votes[level]++ + } + } + chosen := chooseLevel(votes) + tied := tiedLevels(votes, chosen) + if len(tied) == 0 { + return judgeAudit(founds, newFileCandidates, len(results), chosen, nil) + } + original := auditor + defer func() { auditor = original }() + return judgeTied(original.sourceName, original.bases, chosen, tied, func(first bool, level int) (string, bool) { + if first { + return judgeAudit(founds, newFileCandidates, len(results), level, tied) + } + fresh, err := original.reparse() + if err != nil { + printError(fmt.Sprintf("unable to parse audit file %s: %s", original.sourceName, err.Error())) + return "", false + } + auditor = fresh + founds, newFiles := lookupResults(results) + return judgeAudit(founds, newFiles, len(results), level, tied) + }) +} + +// judgeTied judges an audit through each directory as many files matched through as the one +// chosen, see tiedLevels, as which the paths were written relative to is then not decided by the +// files on disk. Judged only through the first, a file modified through one directory can match +// another record through the first, with the record it should have matched reported as moved, so +// the audit passes only when it passes through every one, reporting the first it fails through. +// judge is called with each directory in turn, the chosen one first with first set, then again +// for the one reported with first unset, so it starts again from the audit file +func judgeTied(auditName string, bases []string, chosen int, tied []int, judge func(first bool, level int) (string, bool)) (string, bool) { + levels := []int{chosen} + sorted := slices.Clone(tied) + slices.Sort(sorted) + for _, level := range sorted { + if level != chosen { + levels = append(levels, level) + } + } + + // each is judged with its report discarded, so no report is held in memory, then the one + // reported is judged again writing it, from the start as judging changes the audit's state + out := stdout + defer func() { stdout, warningsMuted = out, false }() + reported := chosen + for i, level := range levels { + // warnings were given when judged through the chosen directory + warningsMuted = i != 0 + stdout = &checkedWriter{w: io.Discard} + summary, passed := judge(i == 0, level) + if summary == "" { + // an error, which was printed + return "", false + } + if !passed { + reported = level + break + } + } + stdout, warningsMuted = out, false + if reported != chosen { + printWarn(fmt.Sprintf("the paths in %s name as many files through %s as through %s, so the audit is checked through each, and fails through %s", auditName, bases[chosen], bases[reported], bases[reported])) + } + warningsMuted = true + return judge(false, reported) +} + +// judgeAudit matches files on disk to records through the chosen directory and reports the result +func judgeAudit(founds []auditFound, newFileCandidates []Result, examinedCount int, chosen int, tied []int) (string, bool) { matched := 0 filesModified := 0 moved := 0 @@ -229,48 +347,27 @@ func doAudit(input chan Result) (string, bool) { file string // file on disk, which differs from the record for moved files } outcomes := map[*AuditRecord]outcome{} - var newFileCandidates []Result - // The directory the audit is matched through is chosen once every file has arrived, see - // chooseLevel, so files matching a record are held until then type claim struct { - res Result - r *AuditRecord - level int - independent bool + res Result + r *AuditRecord + level int } - var found []claim - votes := map[int]int{} - - seen := map[string]bool{} - for res := range input { - // overlapping paths such as . and ./sub supply the same file twice - if isDuplicateFile(seen, res.File) { - continue - } - examinedCount++ - - r, level, independent := auditor.LookupLevel(res.File) - if r == nil { - newFileCandidates = append(newFileCandidates, res) - continue - } - found = append(found, claim{res: res, r: r, level: level, independent: independent}) - if !independent { - votes[level]++ - } - } - chosen := chooseLevel(votes) + auditor.GroupSameFile(chosen, tied) // Two files on disk can resolve to the same record, so which claims it does not depend on the // order files were processed in. A file matching through a directory earlier in priority order // wins, being the record's own path before another directory, then the first path in sort order claims := map[*AuditRecord]claim{} - for _, c := range found { - if !keepsMatch(chosen, c.level, c.independent) { - newFileCandidates = append(newFileCandidates, c.res) + for _, f := range founds { + // the record naming the file through the chosen directory, not one naming it through + // another directory first + candidate, ok := pickCandidate(f.candidates, chosen) + if !ok { + newFileCandidates = append(newFileCandidates, f.res) continue } + c := claim{res: f.res, r: candidate.Record, level: candidate.Level} existing, ok := claims[c.r] if !ok { claims[c.r] = c @@ -300,6 +397,10 @@ func doAudit(input chan Result) (string, bool) { newFileCandidates = remaining } auditor.warnDuplicates() + auditor.settleOwnEntries(chosen, func(r *AuditRecord) bool { + _, ok := claims[r] + return ok + }) for r, c := range claims { r.Matched = true @@ -339,9 +440,9 @@ func doAudit(input chan Result) (string, bool) { failedFiles.Range(func(key, _ any) bool { // a record claimed by another file is reported for that file, so the unreadable file is // listed on its own, as it is when it has no record - if r := auditor.Lookup(key.(string)); r != nil { - if _, claimed := outcomes[r]; !claimed { - unreadable[r] = true + if c, ok := pickCandidate(auditor.LookupLevels(key.(string)), chosen); ok { + if _, claimed := outcomes[c.Record]; !claimed { + unreadable[c.Record] = true return true } } diff --git a/test-all.sh b/test-all.sh index 423f917..d11ad26 100755 --- a/test-all.sh +++ b/test-all.sh @@ -1450,6 +1450,9 @@ fi rm -rf "$AUDITDIR" +echo -e "${NC}Running audit scenarios..." +./test-audit.sh < /dev/null || exit + echo -e "${NC}Cleaning up..." rm ./hashit rm -f ./audit.txt diff --git a/test-audit.sh b/test-audit.sh new file mode 100755 index 0000000..c16beeb --- /dev/null +++ b/test-audit.sh @@ -0,0 +1,203 @@ +#!/bin/bash + +# Audit scenarios checked against hashdeep and md5sum where they apply. Audits which are known to be +# wrong are reported as known bugs without failing, and fail once they are right so they can be +# moved to the scenarios which must pass. Needs hashdeep, the coreutils sum tools and sqlite3 + +GREEN='\033[1;32m' +RED='\033[0;31m' +YELLOW='\033[1;33m' +NC='\033[0m' + +echo "Building application..." +WORK=$(mktemp -d) +go build -o "$WORK/hashit" . || exit 1 +HASHIT="$WORK/hashit" +KNOWN=0 + +fail() { + echo -e "${RED}=======================================================" + echo -e "FAILED $1" + echo -e "=======================================================${NC}" + rm -rf "$WORK" + exit 1 +} + +# expect_rc description exit-code command: the command must exit with the code +expect_rc() { + (eval "$3") > "$WORK/out" 2>&1 + local rc=$? + if [ "$rc" == "$2" ]; then + echo -e "${GREEN}PASSED $1" + else + cat "$WORK/out" + fail "$1, expected exit $2 got $rc" + fi +} + +# known_bug description exit-code command: the command should exit with the code but does not yet +known_bug() { + (eval "$3") > "$WORK/out" 2>&1 + local rc=$? + if [ "$rc" == "$2" ]; then + fail "$1 is fixed, move it to the scenarios which must pass" + fi + echo -e "${YELLOW}KNOWN BUG $1, expected exit $2 got $rc" + KNOWN=$((KNOWN + 1)) +} + +# A sum file written in the directory it lists, as in https://github.com/boyter/hashit/issues/12 +mkdir -p "$WORK/user/path/sub" +cd "$WORK/user/path" || exit 1 +echo a > a; echo b > sub/b +"$HASHIT" -c md5 -r -p --threads 2 -f sum -o hashes.md5 . > /dev/null 2>&1 +"$HASHIT" -c md5 -r -p --threads 2 -f sum -o hashes2.md5 > /dev/null 2>&1 +expect_rc "audit with a second sum file beside the first fails test" 1 "'$HASHIT' --threads 2 -a hashes.md5 ." +expect_rc "audit with a second sum file beside the first passes with --allow-new test" 0 "'$HASHIT' --threads 2 --allow-new -a hashes.md5 ." +expect_rc "audit of the second sum file passes test" 0 "'$HASHIT' --threads 2 -a hashes2.md5" +expect_rc "md5sum agrees the sum file passes test" 0 "md5sum --quiet -c hashes.md5" +echo changed >> sub/b +expect_rc "modified file fails with --allow-new test" 1 "'$HASHIT' --allow-new -a hashes.md5 ." +expect_rc "modified file fails with --allow-new and --allow-moved test" 1 "'$HASHIT' --allow-new --allow-moved -a hashes.md5 ." +echo b > sub/b +mv sub/b sub/b2 +expect_rc "moved file fails with --allow-new test" 1 "'$HASHIT' --allow-new -a hashes.md5 ." +expect_rc "moved file passes with --allow-new and --allow-moved test" 0 "'$HASHIT' --allow-new --allow-moved -a hashes.md5 ." +rm sub/b2 +expect_rc "missing file fails with --allow-new and --allow-moved test" 1 "'$HASHIT' --allow-new --allow-moved -a hashes.md5 ." + +# A sum file of every hash the coreutils tools check is verified by them, and audited by hashit, +# and fails both once a file is modified +mkdir -p "$WORK/tools/t/sub" +cd "$WORK/tools/t" || exit 1 +echo a > a; echo b > sub/b; echo "with space" > "sub/c d" +for pair in sha1:sha1sum:sha1 sha224:sha224sum:sha224 sha256:sha256sum:sha256 sha384:sha384sum:sha384 \ + sha512:sha512sum:sha512 blake2b512:b2sum:b2 blake2b256:b2sum:b2; do + IFS=: read -r hash tool ext <<< "$pair" + "$HASHIT" -c "$hash" -f sum -o "../$hash.$ext" . > /dev/null 2>&1 + expect_rc "$tool verifies the $hash sum file test" 0 "$tool --quiet -c '../$hash.$ext'" + expect_rc "$hash sum file passes test" 0 "'$HASHIT' -a '../$hash.$ext' ." +done +echo changed >> "sub/c d" +for pair in sha1:sha1sum:sha1 sha224:sha224sum:sha224 sha256:sha256sum:sha256 sha384:sha384sum:sha384 \ + sha512:sha512sum:sha512 blake2b512:b2sum:b2 blake2b256:b2sum:b2; do + IFS=: read -r hash tool ext <<< "$pair" + expect_rc "$tool fails a modified file in the $hash sum file test" 1 "$tool --quiet -c '../$hash.$ext'" + expect_rc "$hash sum file fails a modified file test" 1 "'$HASHIT' -a '../$hash.$ext' ." +done + +# A manifest kept below the root of a tree with a name repeated at the root and beside the manifest. +# Moving a file onto the path of a known file is a modification, as hashdeep reports +for fmt in hashdeep sqlite sum; do + case $fmt in hashdeep) M=meta/m.hd ;; sqlite) M=meta/m.db ;; sum) M=meta/m.md5 ;; esac + mkdir -p "$WORK/meta-$fmt/orig/meta" + cd "$WORK/meta-$fmt/orig" || exit 1 + echo top > README; echo meta > meta/README; echo w > w; echo y > y + "$HASHIT" -c md5 -f $fmt -o $M . > /dev/null + cp -r "$WORK/meta-$fmt/orig" "$WORK/meta-$fmt/copy" + expect_rc "$fmt manifest below the root passes in a copy test" 0 "cd '$WORK/meta-$fmt/copy' && '$HASHIT' -a $M ." + for tree in orig copy; do + (cd "$WORK/meta-$fmt/$tree" && mv meta/README meta/README.old && mv w meta/README) + done + expect_rc "$fmt file moved onto a known path fails with --allow-moved test" 1 "cd '$WORK/meta-$fmt/orig' && '$HASHIT' --allow-moved -a $M ." + expect_rc "$fmt file moved onto a known path fails with --allow-moved in a copy test" 1 "cd '$WORK/meta-$fmt/copy' && '$HASHIT' --allow-moved -a $M ." +done +expect_rc "hashdeep reports a file moved onto a known path test" 1 "cd '$WORK/meta-hashdeep/copy' && hashdeep -r -l -a -k meta/m.hd ." + +# As above with no other files, so the manifest's directory and the working directory each name +# meta/README, and the audit must fail through either +for fmt in hashdeep sqlite sum; do + case $fmt in hashdeep) M=meta/m.hd ;; sqlite) M=meta/m.db ;; sum) M=meta/m.md5 ;; esac + mkdir -p "$WORK/tie-$fmt/orig/meta" + cd "$WORK/tie-$fmt/orig" || exit 1 + echo top > README; echo meta > meta/README + "$HASHIT" -c md5 -f $fmt -o $M . > /dev/null + cp -r "$WORK/tie-$fmt/orig" "$WORK/tie-$fmt/copy" + cd "$WORK/tie-$fmt/copy" || exit 1 + expect_rc "$fmt manifest below the root naming as many files through either directory passes in a copy test" 0 "'$HASHIT' -a $M ." + mv meta/README meta/README.old && mv README meta/README + expect_rc "$fmt file moved onto a known path naming as many files fails with --allow-moved in a copy test" 1 "'$HASHIT' --allow-moved -a $M ." +done +expect_rc "hashdeep reports a file moved onto a known path naming as many files test" 1 "cd '$WORK/tie-hashdeep/copy' && hashdeep -r -l -a -k meta/m.hd ." +expect_rc "md5sum fails a file moved onto a known path naming as many files test" 1 "cd '$WORK/tie-sum/copy' && md5sum --quiet -c meta/m.md5" + +# A database not written by hashit with paths such as ././README, which are looked up through an +# index, kept below the root of a copied tree, where ././README and ././meta/README both name +# meta/README. Each directory must find its own record +mkdir -p "$WORK/spelled/orig/meta" +cd "$WORK/spelled/orig" || exit 1 +echo top > README; echo meta > meta/README; echo w > w; echo x > x +"$HASHIT" -c md5 -f sqlite -o meta/m.db . > /dev/null +sqlite3 meta/m.db "update file_hashes set filepath = '././' || substr(filepath, 3)" +cp -r "$WORK/spelled/orig" "$WORK/spelled/copy" +cd "$WORK/spelled/copy" || exit 1 +expect_rc "sqlite paths through the index pass in a copy test" 0 "'$HASHIT' -a meta/m.db ." +cp meta/README meta/README.bak && mv w meta/README +expect_rc "sqlite paths through the index fail a file moved onto a known path with a backup test" 1 "'$HASHIT' --allow-moved -a meta/m.db ." + +# A hashdeep file without an invoked from line audited from a subdirectory, where the working +# directory names sub/b as record ./b +mkdir -p "$WORK/noinv/tree/sub" +cd "$WORK/noinv/tree" || exit 1 +echo BBB > b; echo SUBB > sub/b; echo C > sub/c +hashdeep -l -r . | grep -v '^## Invoked from' > m.txt +expect_rc "hashdeep file without invoked from audited from a subdirectory passes test" 0 "cd sub && '$HASHIT' -a ../m.txt .." +cp sub/b sub/b.orig +echo MODIFIED > sub/b +expect_rc "hashdeep file without invoked from fails a modified file test" 1 "'$HASHIT' --allow-new --allow-moved -a m.txt ." +expect_rc "hashdeep fails a modified file test" 1 "hashdeep -l -r -a -k m.txt ." +expect_rc "hashdeep file without invoked from fails a modified file audited from a subdirectory test" 1 \ + "cd sub && '$HASHIT' --allow-new --allow-moved -a ../m.txt .." + +# A sum file whose tree has a directory of the tree's name holding a file of the sum file's name. +# Through the working directory that record is the sum file, through the sum file's directory it +# is the other file +mkdir -p "$WORK/nested/Q/data/data" +cd "$WORK/nested/Q/data" || exit 1 +echo x > x; echo inner > data/hashes.md5 +"$HASHIT" -c md5 -f sum -o hashes.md5 . > /dev/null +expect_rc "sum file listing a file of its own name passes test" 0 "'$HASHIT' -a hashes.md5 ." +expect_rc "md5sum passes a sum file listing a file of its own name test" 0 "md5sum --quiet -c hashes.md5" +expect_rc "sum file listing a file of its own name passes from the parent test" 0 "cd .. && '$HASHIT' -a data/hashes.md5 data" +rm data/hashes.md5 +expect_rc "deleted file of the sum file's name fails test" 1 "'$HASHIT' -a hashes.md5 ." +expect_rc "md5sum fails a deleted file of the sum file's name test" 1 "md5sum --quiet -c hashes.md5" +expect_rc "deleted file of the sum file's name fails from the parent test" 1 "cd .. && '$HASHIT' -a data/hashes.md5 data" + +# A sum file at the root of the files it lists, audited from a subdirectory, with a name repeated +# in the subdirectory +mkdir -p "$WORK/root-sum/R/sub" +cd "$WORK/root-sum/R" || exit 1 +echo top > README; echo sub > sub/README; echo c > sub/c +"$HASHIT" -c md5 -f sum -o hashes.md5 . > /dev/null +expect_rc "sum file at the root passes test" 0 "'$HASHIT' -a hashes.md5 ." +expect_rc "md5sum passes the sum file at the root test" 0 "md5sum --quiet -c hashes.md5" +expect_rc "sum file at the root passes from a subdirectory with a repeated name test" 0 "cd sub && '$HASHIT' -a ../hashes.md5 .." +echo changed >> sub/README +expect_rc "sum file at the root fails a modified file from a subdirectory test" 1 "cd sub && '$HASHIT' --allow-new --allow-moved -a ../hashes.md5 .." + +# A SQLite database is only read by an audit +mkdir -p "$WORK/ro/t" +cd "$WORK/ro" || exit 1 +echo a > t/a +"$HASHIT" -f sqlite -o m.db t > /dev/null +BEFORE=$(md5sum m.db; ls -a) +expect_rc "sqlite audit passes test" 0 "'$HASHIT' -a m.db t" +echo b > t/b +expect_rc "sqlite audit with a new file fails test" 1 "'$HASHIT' -a m.db t" +expect_rc "sqlite audit leaves the database unchanged test" 0 "[ \"\$(md5sum m.db; ls -a)\" == \"$BEFORE\" ]" + +# A SQLite database with an extra column whose name contains collate is still created by hashit +cp m.db collate.db +sqlite3 collate.db "alter table file_hashes add column collateral text" +expect_rc "sqlite audit accepts a column named collateral test" 0 "'$HASHIT' --allow-new -a collate.db t" +cp m.db real-collate.db +sqlite3 real-collate.db "alter table file_hashes add column note text collate nocase" +expect_rc "sqlite audit refuses a collate clause test" 2 "'$HASHIT' -a real-collate.db t" + +cd / || exit 1 +rm -rf "$WORK" + +echo -e "${GREEN}=================================================" +echo -e "ALL AUDIT SCENARIOS PASSED, ${KNOWN} KNOWN BUGS" +echo -e "=================================================${NC}"