diff --git a/flake.nix b/flake.nix index d5320e6ad..9efc697df 100644 --- a/flake.nix +++ b/flake.nix @@ -64,6 +64,7 @@ rjc-gates-image = "sha256-WJ+DzF3TydFNjIOq2MAQxEDI62G8xJcjTCAyMZtwgP0="; run-cd = "sha256-s9UTOYZs+Y7UQUbQuANYejHSr2QJb/GdqelRT8z0gOA="; ssh-orphan-reap = null; + transcript-archive = "sha256-vTUY8s1LAmccPFBLiJsOk/rAnXe3/980mpXEKSPdL1c="; wave-dreamer = "sha256-7K17JaXFsjf163g5PXCb5ng2gYdotnZ2IDKk8KFjNj0="; wave-host = "sha256-3/tNPMYKxKjwprceoPRjRJuTNBwJSJE4LD8grnh+haI="; wave-ledger = "sha256-9TnmijwY7K3fhUngJXQRcn+eoYEKMKo5qd2YYgpHnN8="; @@ -137,6 +138,8 @@ [ pkgs.jujutsu pkgs.util-linux pkgs.procps ] ++ lib.optional ((packagesFor manifest pkgs.stdenv.hostPlatform.system) ? jj-vine) (packagesFor manifest pkgs.stdenv.hostPlatform.system).jj-vine; + # transcript-archive's tests drive real restic repositories. + transcript-archive = pkgs: [ pkgs.restic ]; # zellij-rss-watchdog's process tests start a grandchild with setsid. zellij-rss-watchdog = pkgs: [ pkgs.util-linux ]; }; @@ -497,6 +500,10 @@ host-bao-seal = pkgs.mkShell { packages = basePackages ++ checkTools.host-bao-seal pkgs; }; + # The transcript-archive tests drive restic repositories; the default shell stays lean. + transcript-archive = pkgs.mkShell { + packages = basePackages ++ [ pkgs.restic ]; + }; }); }; } diff --git a/tools/transcript-archive/.golangci.yml b/tools/transcript-archive/.golangci.yml new file mode 100644 index 000000000..297c756a8 --- /dev/null +++ b/tools/transcript-archive/.golangci.yml @@ -0,0 +1,49 @@ +version: "2" + +linters: + default: all + disable: + # Parser format constants are intentionally numeric; tests mirror the TS suite verbatim. + - mnd + # The Go standard library's short local names and blank-line style are retained. + - varnamelen + - wsl + - wsl_v5 + # The parser's single-pass state machine is easier to review as a direct port. + - cyclop + - gocognit + - gocyclo + - maintidx + # Long tests and repeated diff snippets preserve one-to-one parity with TypeScript. + - funlen + - dupl + - goconst + # This API is frozen by the design contract; interface-count heuristics do not apply. + - ireturn + # Default rules reject imports of this module's required internal text package. + - depguard + # Use the v2 replacement for the deprecated legacy linter. + - gomodguard + - nlreturn + - exhaustruct + settings: + gomoddirectives: + # The command builds against the sibling tools/go-lib module through a local replace. + replace-local: true + enable: + - gomodguard_v2 + exclusions: + rules: + - path: '_test\.go' + linters: + - gochecknoglobals + - paralleltest + - testpackage + - funlen + - goconst + - dupl + - gosec + +issues: + max-issues-per-linter: 0 + max-same-issues: 0 diff --git a/tools/transcript-archive/LICENSE-APACHE b/tools/transcript-archive/LICENSE-APACHE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/tools/transcript-archive/LICENSE-APACHE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/tools/transcript-archive/LICENSE-MIT b/tools/transcript-archive/LICENSE-MIT new file mode 100644 index 000000000..dfb986acc --- /dev/null +++ b/tools/transcript-archive/LICENSE-MIT @@ -0,0 +1,19 @@ +Copyright (c) 2026 Rigel AI Software Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/transcript-archive/README.md b/tools/transcript-archive/README.md new file mode 100644 index 000000000..e700c9050 --- /dev/null +++ b/tools/transcript-archive/README.md @@ -0,0 +1,86 @@ +# transcript-archive + +Inventories agent transcript files and archives them to a restic repository. + +## Commands + +```sh +transcript-archive inventory --host --config --out [--previous ] [--delta ] +transcript-archive pass --host --config --state-dir --repo --escrow-out --escrow-recipient [--restic ] +transcript-archive coverage --state-dir --scope --repo [--restic ] +transcript-archive get --repo --escrow --identity --snapshot --record --out +transcript-archive fence [--agent-dir ]... [--wait ] +transcript-archive rawcap --repo --state-dir --cap-bytes +``` + +## Required inputs + +Every deployment value is a flag with no default. The tool refuses to run +without it, and a missing required flag exits non-zero. + +| Input | Flag | Used by | Rule | +| --- | --- | --- | --- | +| Host config | `--config` | `inventory`, `pass` | Required. A CUE file that declares `hosts`. The schema is compiled into the binary, so no schema file sits beside it. | +| Host name | `--host` | `inventory`, `pass` | Required. A key under `hosts` in the config. | +| Escrow recipient | `--escrow-recipient` | `pass` | Required. An age X25519 public key. Nothing is baked into the binary. | +| Repository | `--repo` | `pass`, `coverage`, `get`, `rawcap` | Required. A local path or any restic backend URL. | + +Bucket names, endpoints and secret paths are inputs too. The binary has no +default for any of them. + +## Config + +The host config is CUE. Each host sets `state` (`measured`, `unmeasured` or +`empty`) and lists `sources`, `watch`, `exclude` and `finalOnly`. The config in +`testdata/archive.cue` is a synthetic example (`example-host`) for tests. Use +your own config for a real host; keep it out of this repository. + +## Host timer: `pass` + +A host's user timer runs one pass per tick. A systemd user unit does not expand `~`, so use `%h` or absolute paths: + +```ini +ExecStart=/path/to/transcript-archive pass \ + --host \ + --config /path/to/archive.cue \ + --state-dir %h/.local/state/transcript-archive/ \ + --repo \ + --escrow-out /path/to/escrow/.age \ + --escrow-recipient +``` + +Optional: `--restic /path/to/restic`. The repository may be a local path or any restic backend (`s3:`, `rest:`, `b2:`, `azure:`, `gs:`, `sftp:`, `swift:`, `rclone:`). + +Each run takes these steps: + +1. Take the state directory's lock, so a second run fails instead of interleaving. +2. Open the scope state. The first run generates the repository password. +3. Walk the host's configured sources under `HOME` against the last committed scan. +4. Recover any pass that started without an outcome. +5. Record the scan and run one `restic backup`. On success the journal gets one `path-acked` line per pending path. + +- **Credentials.** For an S3 repository, export `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`. They pass through to restic. All `RESTIC_*` variables are ignored; the password comes only from `/password`. +- **Escrow.** Before the repository is created, the password is age-encrypted to `--escrow-recipient` and written to `--escrow-out`, create-exclusive and fsynced. `.sha256` records the plaintext digest. A later run reuses the file only if the digest matches. A different password is refused, and the file is never overwritten. +- **Exit status.** 0 means the pass was acked. Any other result exits non-zero with one line on stderr. The next run recovers it. +- **`--restic`** selects the restic binary; the default is `restic` on `PATH`. `coverage` takes the same flag. + +## Before deleting: `coverage` + +Run `coverage` against the repository before you delete any local transcript. It needs only the state directory: + +```sh +transcript-archive coverage --state-dir --scope --repo [--restic ] +``` + +It reads `scan-current.jsonl`, `journal.jsonl` and `password`. It certifies the last scan's content, not the live file: a file changed after the last pass can still pass, so a deleter must re-check each file's size and mtime against its scan line first. + +`pass` refuses to start if the state or scratch directory resolves (following symlinks) under a source root. + +## Development + +```sh +go test ./... +``` + +Tests build their own throwaway age keys and fixtures. None of them need a +real host, repository or escrow key. diff --git a/tools/transcript-archive/cmd/transcript-archive/coverage.go b/tools/transcript-archive/cmd/transcript-archive/coverage.go new file mode 100644 index 000000000..4bf20d606 --- /dev/null +++ b/tools/transcript-archive/cmd/transcript-archive/coverage.go @@ -0,0 +1,183 @@ +package main + +import ( + "bufio" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strings" + + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/coverage" + "github.com/spf13/cobra" +) + +type coverageOptions struct { + final, baseline, digests, vanished string + scope, snapshot, repo, passwordFile string + restic, stateDir, cacheDir string + deltas, journals []string + chained bool +} + +func newCoverageCmd() *cobra.Command { + var opts coverageOptions + command := &cobra.Command{ + Use: "coverage", + Short: "Check transcript archive coverage", + Args: cobra.NoArgs, + RunE: func(command *cobra.Command, _ []string) error { + return runCoverage(command.OutOrStdout(), opts) + }, + } + command.Flags().StringVar(&opts.final, "final", "", "final inventory JSONL path") + command.Flags().StringVar(&opts.baseline, "baseline", "", "baseline inventory JSONL path") + command.Flags().StringArrayVar(&opts.deltas, "deltas", nil, "scan delta JSONL path (repeat for pass order)") + command.Flags().BoolVar(&opts.chained, "chained", false, "check a chained seat lifecycle") + command.Flags().StringVar(&opts.scope, "scope", "", "archive scope") + command.Flags().StringVar(&opts.snapshot, "snapshot", "", "final snapshot ID") + command.Flags().StringVar(&opts.repo, "repo", "", "restic repository") + command.Flags().StringVar(&opts.passwordFile, "password-file", "", "restic password file") + command.Flags().StringArrayVar(&opts.journals, "journal", nil, "pass journal JSONL path (repeat for each journal)") + command.Flags().StringVar(&opts.digests, "digests", "", "snapshot path digest JSON file") + command.Flags().StringVar(&opts.vanished, "vanished", "", "journaled vanished paths file") + command.Flags().StringVar(&opts.restic, "restic", "restic", "restic binary (default resolves restic on PATH)") + command.Flags().StringVar(&opts.stateDir, "state-dir", "", "pass state directory: check every live file against the latest acked snapshot (dumps only unverified files)") + return command +} + +func runCoverage(out io.Writer, opts coverageOptions) error { + if opts.stateDir != "" { + if opts.scope == "" || opts.repo == "" { + return errors.New("coverage --state-dir requires scope and repo") + } + return runStateCoverage(out, opts) + } + if opts.final == "" || opts.baseline == "" || opts.snapshot == "" || opts.scope == "" || opts.repo == "" || opts.passwordFile == "" || len(opts.journals) == 0 || opts.digests == "" || opts.vanished == "" || len(opts.deltas) == 0 { + return errors.New("coverage requires --state-dir, or final, baseline, deltas, scope, snapshot, repo, password-file, journal, digests and vanished") + } + final, err := readInventory(opts.final) + if err != nil { + return fmt.Errorf("read final inventory: %w", err) + } + baseline, err := readInventory(opts.baseline) + if err != nil { + return fmt.Errorf("read baseline inventory: %w", err) + } + digests, err := readDigests(opts.digests) + if err != nil { + return err + } + vanished, err := readVanished(opts.vanished) + if err != nil { + return fmt.Errorf("read vanished paths: %w", err) + } + listing, err := resticListing(opts, opts.snapshot, digests) + if err != nil { + return err + } + if listing.StateFiles, err = stateFiles(opts); err != nil { + return err + } + history, err := resticHistory(opts) + if err != nil { + return err + } + readers := make([]*os.File, 0, len(opts.deltas)) + for _, path := range opts.deltas { + file, err := os.Open(path) //nolint:gosec // Operator-supplied delta path. + if err != nil { + return errors.Join(fmt.Errorf("open scan delta: %w", err), closeFiles(readers)) + } + readers = append(readers, file) + } + inputs := make([]coverage.Delta, len(readers)) + for i, reader := range readers { + name := filepath.Base(opts.deltas[i]) + passID := strings.TrimSuffix(strings.TrimPrefix(name, "delta-"), ".jsonl") + if name != "delta-"+passID+".jsonl" || passID == "" { + return errors.Join(errors.New("invalid scan delta filename"), closeFiles(readers)) + } + inputs[i] = coverage.Delta{PassID: passID, R: reader} + } + report := coverage.Check(*final, *baseline, inputs, opts.chained, listing, digests, history, vanished) + if err := closeFiles(readers); err != nil { + return fmt.Errorf("close scan deltas: %w", err) + } + return writeCoverageReport(out, report) +} + +// stateFiles names the archive's own files that a pass backs up; coverage exempts exactly these. +func stateFiles(opts coverageOptions) (map[string]struct{}, error) { + files := make(map[string]struct{}, len(opts.deltas)+len(opts.journals)) + for _, path := range append(append([]string(nil), opts.deltas...), opts.journals...) { + abs, err := filepath.Abs(path) + if err != nil { + return nil, fmt.Errorf("resolve state file: %w", err) + } + files[filepath.ToSlash(abs)] = struct{}{} + } + return files, nil +} + +func writeCoverageReport(out io.Writer, report coverage.Report) error { + output, err := json.Marshal(report) + if err != nil { + return fmt.Errorf("encode coverage report: %w", err) + } + if _, err := out.Write(append(output, '\n')); err != nil { + return fmt.Errorf("write coverage report: %w", err) + } + if !report.Pass { + return errors.New("transcript archive coverage failed") + } + return nil +} + +func readDigests(path string) (map[string]coverage.FileDigest, error) { + file, err := os.Open(path) //nolint:gosec // Path is an operator-supplied CLI flag. + if err != nil { + return nil, err + } + defer func() { + _ = file.Close() + }() + var digests map[string]coverage.FileDigest + if err := json.NewDecoder(file).Decode(&digests); err != nil { + return nil, err + } + return digests, nil +} + +func readVanished(path string) ([]string, error) { + file, err := os.Open(path) //nolint:gosec // Path is an operator-supplied CLI flag. + if err != nil { + return nil, err + } + defer func() { + _ = file.Close() + }() + paths := []string{} + scanner := bufio.NewScanner(file) + for scanner.Scan() { + if scanner.Text() != "" { + paths = append(paths, scanner.Text()) + } + } + if err := scanner.Err(); err != nil { + return nil, err + } + return paths, nil +} + +func closeFiles(files []*os.File) error { + var errs []error + for _, file := range files { + if err := file.Close(); err != nil { + errs = append(errs, err) + } + } + return errors.Join(errs...) +} diff --git a/tools/transcript-archive/cmd/transcript-archive/coverage_restic.go b/tools/transcript-archive/cmd/transcript-archive/coverage_restic.go new file mode 100644 index 000000000..296eed0e9 --- /dev/null +++ b/tools/transcript-archive/cmd/transcript-archive/coverage_restic.go @@ -0,0 +1,191 @@ +package main + +import ( + "bufio" + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "os/exec" //nolint:depguard // coverage lists restic snapshots; stderr is discarded and no secret is in argv. + "path/filepath" + "sort" + "strings" + "time" + + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/coverage" + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/resticenv" +) + +type historyPass struct { + ID string `json:"passId"` + Event string `json:"event"` +} + +type resticSnapshot struct { + ID string `json:"id"` + Time time.Time `json:"time"` + Tags []string `json:"tags"` + PassID string `json:"-"` + Outcome string `json:"-"` +} + +func resticOutput(opts coverageOptions, subcommand string, args ...string) ([]byte, error) { + cmd, err := resticCommand(opts, subcommand, args...) + if err != nil { + return nil, err + } + output, err := cmd.Output() + if err != nil { + return nil, fmt.Errorf("restic %s: %w", subcommand, err) + } + return output, nil +} + +// resticCommand builds a restic child with a filtered environment and the password file by base name. +func resticCommand(opts coverageOptions, subcommand string, args ...string) (*exec.Cmd, error) { + repo := opts.repo + var err error + if localPath, ok := strings.CutPrefix(repo, "local:"); ok { + repo, err = filepath.Abs(localPath) + if err == nil { + repo = "local:" + repo + } + } else if !resticenv.IsBackend(repo) { + repo, err = filepath.Abs(repo) + } + if err != nil { + return nil, fmt.Errorf("resolve restic repository: %w", err) + } + arguments := make([]string, 0, 7+len(args)) + arguments = append(arguments, "--repo", repo, "--password-file", filepath.Base(opts.passwordFile)) + // State-dir coverage caches tree blobs in the state dir, so each batch's tree walk reads S3 once. + if opts.cacheDir != "" { + arguments = append(arguments, "--cache-dir", opts.cacheDir, subcommand) + } else { + arguments = append(arguments, "--no-cache", subcommand) + } + arguments = append(arguments, args...) + binary := opts.restic + if binary == "" { + binary = "restic" + } + cmd := exec.Command(binary, arguments...) //nolint:gosec // Arguments are separate and supplied by the operator. + cmd.Dir = filepath.Dir(opts.passwordFile) + cmd.Env = resticenv.Filter("") + cmd.Stderr = io.Discard + return cmd, nil +} + +func resticListing(opts coverageOptions, snapshot string, digests map[string]coverage.FileDigest) (coverage.SnapshotListing, error) { + output, err := resticOutput(opts, "ls", "--json", "--no-lock", snapshot) + if err != nil { + return coverage.SnapshotListing{}, err + } + listing := coverage.SnapshotListing{SnapshotID: snapshot, PathsOnly: digests == nil, Files: map[string][32]byte{}} + decoder := json.NewDecoder(bytes.NewReader(output)) + missing := 0 + for { + var node struct { + StructType string `json:"struct_type"` + Type string `json:"type"` + Path string `json:"path"` + } + if err := decoder.Decode(&node); err != nil { + if err == io.EOF { + break + } + return coverage.SnapshotListing{}, fmt.Errorf("decode restic listing: %w", err) + } + if node.StructType != "node" || node.Type != "file" { + continue + } + if digests == nil { + listing.Files[node.Path] = [32]byte{} + continue + } + digest, ok := digests[node.Path] + if !ok { + missing++ + continue + } + listing.Files[node.Path] = digest.SHA256 + } + if missing != 0 { + return coverage.SnapshotListing{}, fmt.Errorf("missing digests for %d snapshot path(s)", missing) + } + return listing, nil +} + +func readHistoryPasses(path string) (passes []historyPass, err error) { + file, err := os.Open(path) //nolint:gosec // Operator-supplied journal path. + if err != nil { + return nil, fmt.Errorf("open journal: %w", err) + } + defer func() { err = errors.Join(err, file.Close()) }() + passes = []historyPass{} + scanner := bufio.NewScanner(file) + scanner.Buffer(make([]byte, 64*1024), 4*1024*1024) + for scanner.Scan() { + var pass historyPass + if err := json.Unmarshal(scanner.Bytes(), &pass); err != nil { + return nil, fmt.Errorf("decode journal: %w", err) + } + switch pass.Event { + case "pass-acked", "pass-incomplete", "pass-stored": + if pass.ID == "" { + return nil, fmt.Errorf("journal %s missing pass ID", pass.Event) + } + passes = append(passes, pass) + } + } + if err := scanner.Err(); err != nil { + return nil, fmt.Errorf("read journal: %w", err) + } + return passes, nil +} + +func resticHistory(opts coverageOptions) ([]coverage.SnapshotListing, error) { + passes := make(map[string]string) + for _, journal := range opts.journals { + items, err := readHistoryPasses(journal) + if err != nil { + return nil, err + } + for _, pass := range items { + passes[pass.ID] = pass.Event + } + } + output, err := resticOutput(opts, "snapshots", "--json", "--no-lock", "--host", opts.scope) + if err != nil { + return nil, err + } + var found []resticSnapshot + if err := json.Unmarshal(output, &found); err != nil { + return nil, fmt.Errorf("decode restic snapshots: %w", err) + } + snapshots := make([]resticSnapshot, 0, len(found)) + for _, snapshot := range found { + for _, tag := range snapshot.Tags { + id, ok := strings.CutPrefix(tag, "pass-") + if outcome, exists := passes[id]; ok && exists { + snapshot.Outcome, snapshot.PassID = outcome, id + snapshots = append(snapshots, snapshot) + break + } + } + } + sort.SliceStable(snapshots, func(i, j int) bool { return snapshots[i].Time.After(snapshots[j].Time) }) + history := make([]coverage.SnapshotListing, 0, len(snapshots)) + for _, snapshot := range snapshots { + listing, err := resticListing(opts, snapshot.ID, nil) + if err != nil { + return nil, err + } + listing.Outcome = snapshot.Outcome + listing.PassID = snapshot.PassID + history = append(history, listing) + } + return history, nil +} diff --git a/tools/transcript-archive/cmd/transcript-archive/coverage_restic_test.go b/tools/transcript-archive/cmd/transcript-archive/coverage_restic_test.go new file mode 100644 index 000000000..2b4edc15b --- /dev/null +++ b/tools/transcript-archive/cmd/transcript-archive/coverage_restic_test.go @@ -0,0 +1,271 @@ +package main + +import ( + "archive/tar" + "bytes" + "crypto/sha256" + "encoding/json" + "errors" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/coverage" + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/inventory" +) + +func testRestic(t *testing.T, repo, password string, args ...string) { + t.Helper() + arguments := append([]string{"--repo", repo, "--password-file", password}, args...) + out, err := exec.Command("restic", arguments...).CombinedOutput() + if err != nil { + t.Fatalf("restic %v: %v: %s", args, err, out) + } +} + +func TestResticOutputRelativeRepo(t *testing.T) { + dir := t.TempDir() + bin := filepath.Join(dir, "restic") + if err := os.WriteFile(bin, []byte("#!/bin/sh\nprintf '%s' \"$2\"\n"), 0700); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + want, err := filepath.Abs("relative-repo") + if err != nil { + t.Fatal(err) + } + got, err := resticOutput(coverageOptions{repo: "relative-repo", passwordFile: filepath.Join(dir, "password")}, "ls") + if err != nil || string(got) != want { + t.Fatalf("repo = %q, %v; want %q", got, err, want) + } +} + +func TestResticOutputLocalRepo(t *testing.T) { + dir := t.TempDir() + bin := filepath.Join(dir, "restic") + if err := os.WriteFile(bin, []byte("#!/bin/sh\nprintf '%s' \"$2\"\n"), 0700); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + want, err := filepath.Abs("relative-repo") + if err != nil { + t.Fatal(err) + } + got, err := resticOutput(coverageOptions{repo: "local:relative-repo", passwordFile: filepath.Join(dir, "password")}, "ls") + if err != nil || string(got) != "local:"+want { + t.Fatalf("repo = %q, %v; want %q", got, err, "local:"+want) + } +} + +func TestResticOutputBackendRepo(t *testing.T) { + dir := t.TempDir() + bin := filepath.Join(dir, "restic") + if err := os.WriteFile(bin, []byte("#!/bin/sh\nprintf '%s' \"$2\"\n"), 0700); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + + for _, tt := range []struct { + name string + repo string + }{ + {name: "s3", repo: "s3:https://acct.example/bucket/repo"}, + {name: "rest", repo: "rest:http://127.0.0.1:8000/repo"}, + } { + t.Run(tt.name, func(t *testing.T) { + got, err := resticOutput(coverageOptions{repo: tt.repo, passwordFile: filepath.Join(dir, "password")}, "ls") + if err != nil || string(got) != tt.repo { + t.Fatalf("repo = %q, %v; want %q", got, err, tt.repo) + } + }) + } +} + +// TestStreamedDigestsBadTarKillsRestic: a bad tar header while restic keeps writing must fail fast, not hang or verify. +func TestStreamedDigestsBadTarKillsRestic(t *testing.T) { + dir := t.TempDir() + bin := filepath.Join(dir, "restic") + // 512 bytes of 'x' fail the tar header checksum; `yes` then fills the pipe forever. + if err := os.WriteFile(bin, []byte("#!/bin/sh\nhead -c 512 /dev/zero | tr '\\0' x\nexec yes\n"), 0o700); err != nil { + t.Fatal(err) + } + opts := coverageOptions{repo: filepath.Join(dir, "repo"), passwordFile: filepath.Join(dir, "password"), restic: bin} + type result struct { + digests map[string][32]byte + err error + } + done := make(chan result, 1) + go func() { + digests, err := streamedDigests(opts, "snap", []verifiedEntry{{Path: "/a"}}) + done <- result{digests, err} + }() + select { + case got := <-done: + if !errors.Is(got.err, tar.ErrHeader) || got.digests != nil { + t.Fatalf("streamedDigests = %v, %v; want tar.ErrHeader and no digests", got.digests, got.err) + } + case <-time.After(10 * time.Second): + t.Fatal("streamedDigests hung on a bad tar stream") + } +} + +func TestResticHistoryMultipleJournals(t *testing.T) { + dir := t.TempDir() + for name, content := range map[string]string{ + "one": "{\"event\":\"pass-acked\",\"passId\":\"one\"}\n", + "two": "{\"event\":\"pass-stored\",\"passId\":\"two\"}\n", + "restic": "#!/bin/sh\ncase \" $* \" in\n*' snapshots '*) case \" $* \" in *' --host test '*) echo '[{\"id\":\"one\",\"tags\":[\"pass-one\"]},{\"id\":\"two\",\"tags\":[\"pass-two\"]}]';; *) exit 1;; esac;;\n*) echo '{\"struct_type\":\"node\",\"type\":\"file\",\"path\":\"/file\"}';;\nesac\n", + } { + if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o700); err != nil { + t.Fatal(err) + } + } + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + list, err := resticHistory(coverageOptions{repo: dir, scope: "test", passwordFile: filepath.Join(dir, "password"), journals: []string{filepath.Join(dir, "one"), filepath.Join(dir, "two")}}) + if err != nil || len(list) != 2 { + t.Fatalf("history: %+v, %v", list, err) + } +} + +func TestCoverageRealResticHistory(t *testing.T) { + fixture := historyFixture(t, "test password", "source") + checkHistoryCase(t, fixture.args, fixture.line) + checkUnexplainedCase(t, fixture.args, fixture.deltas[0], fixture.line, fixture.source) +} + +// historyCase carries the coverage arguments and the deleted-file line for one history fixture. +type historyCase struct { + args []string + line inventory.Line + deltas []string + source string +} + +// historyFixture builds a repo with a file deleted after two pass-tagged snapshots. +// The source directory is named sourceName, and the password file holds passwordBytes. +func historyFixture(t *testing.T, passwordBytes, sourceName string) historyCase { + t.Helper() + dir := t.TempDir() + repo, password := filepath.Join(dir, "repo"), filepath.Join(dir, "password") + source := filepath.Join(dir, sourceName) + if err := os.Mkdir(source, 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(password, []byte(passwordBytes), 0o600); err != nil { + t.Fatal(err) + } + testRestic(t, repo, password, "init") + deleted := filepath.Join(source, "deleted") + if err := os.WriteFile(deleted, []byte("old"), 0o600); err != nil { + t.Fatal(err) + } + testRestic(t, repo, password, "backup", "--host", "test", "--tag", "pass-acked", source) + testRestic(t, repo, password, "backup", "--host", "test", "--tag", "pass-stored", source) + if err := os.Remove(deleted); err != nil { + t.Fatal(err) + } + testRestic(t, repo, password, "backup", "--tag", "final", source) + line := inventory.Line{Path: deleted, Type: "file", Class: "normal", Size: 3, SHA256: sha256.Sum256([]byte("old"))} + row, err := json.Marshal(inventory.DeltaRow{Event: "added", Line: &line}) + if err != nil { + t.Fatal(err) + } + files := map[string]string{"final": "", "baseline": "", "delta-acked.jsonl": string(row) + "\n", "delta-stored.jsonl": "{\"event\":\"summary\"}\n", "digests": "{}", "vanished": "", "journal": "{\"event\":\"pass-acked\",\"passId\":\"acked\"}\n{\"event\":\"pass-stored\",\"passId\":\"stored\"}\n"} + for name, value := range files { + if err := os.WriteFile(filepath.Join(dir, name), []byte(value), 0o600); err != nil { + t.Fatal(err) + } + } + opts := coverageOptions{final: filepath.Join(dir, "final"), baseline: filepath.Join(dir, "baseline"), deltas: []string{filepath.Join(dir, "delta-acked.jsonl"), filepath.Join(dir, "delta-stored.jsonl")}, scope: "test", snapshot: "latest", repo: repo, passwordFile: password, journals: []string{filepath.Join(dir, "journal")}, digests: filepath.Join(dir, "digests"), vanished: filepath.Join(dir, "vanished")} + args := []string{"--final", opts.final, "--baseline", opts.baseline, "--deltas", opts.deltas[0], "--deltas", opts.deltas[1], "--scope", opts.scope, "--snapshot", opts.snapshot, "--repo", opts.repo, "--password-file", opts.passwordFile, "--journal", opts.journals[0], "--digests", opts.digests, "--vanished", opts.vanished} + return historyCase{args: args, line: line, deltas: opts.deltas, source: source} +} + +// TestCoverageHistoryArgvAndEnvHideSourceAndPassword checks that no restic child sees the source path or the password. +func TestCoverageHistoryArgvAndEnvHideSourceAndPassword(t *testing.T) { + const passwordSentinel = "history-password-sentinel-9006" + const sourceSentinel = "history-source-sentinel-9006" + fixture := historyFixture(t, passwordSentinel, sourceSentinel) + real, err := exec.LookPath("restic") + if err != nil { + t.Fatal(err) + } + calls := filepath.Join(t.TempDir(), "calls") + wrapper := t.TempDir() + body := "#!/bin/sh\n{ printf 'cmd '; tr '\\000' ' ' < /proc/$$/cmdline; printf '\\n'; cat /proc/$$/environ; printf '\\n'; } >> 'CALLS_LOG'\nexec 'REAL_RESTIC' \"$@\"\n" + body = strings.NewReplacer("CALLS_LOG", calls, "REAL_RESTIC", real).Replace(body) + if err := os.WriteFile(filepath.Join(wrapper, "restic"), []byte(body), 0o700); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", wrapper+string(os.PathListSeparator)+os.Getenv("PATH")) + checkHistoryCase(t, fixture.args, fixture.line) + checkUnexplainedCase(t, fixture.args, fixture.deltas[0], fixture.line, fixture.source) + records, err := os.ReadFile(calls) + if err != nil { + t.Fatal(err) + } + snapshots, lists := 0, 0 + for record := range bytes.SplitSeq(records, []byte{'\n'}) { + rest, ok := strings.CutPrefix(string(record), "cmd ") + if !ok { + continue + } + padded := " " + rest + " " + if strings.Contains(padded, " snapshots ") { + snapshots++ + } + if strings.Contains(padded, " ls ") { + lists++ + } + } + t.Logf("healthy-subject: snapshots invocations=%d ls invocations=%d", snapshots, lists) + if snapshots == 0 || lists == 0 { + t.Fatalf("expected at least one snapshots and one ls invocation, got snapshots=%d ls=%d", snapshots, lists) + } + if bytes.Contains(records, []byte(passwordSentinel)) { + t.Fatal("password bytes appeared in restic argv or environment") + } + if bytes.Contains(records, []byte(sourceSentinel)) { + t.Fatal("source sentinel appeared in restic argv or environment") + } +} + +func checkHistoryCase(t *testing.T, args []string, line inventory.Line) { + t.Helper() + var out bytes.Buffer + command := newCoverageCmd() + command.SetOut(&out) + command.SetArgs(args) + if err := command.Execute(); err != nil { + t.Fatalf("coverage: %v: %s", err, out.String()) + } + var report coverage.Report + if err := json.Unmarshal(out.Bytes(), &report); err != nil { + t.Fatal(err) + } + if len(report.History) != 1 || report.History[0].SHA256 != line.SHA256 { + t.Fatalf("history: %+v", report) + } +} + +func checkUnexplainedCase(t *testing.T, args []string, delta string, line inventory.Line, source string) { + t.Helper() + line.Path = filepath.Join(source, "unexplained") + row, err := json.Marshal(inventory.DeltaRow{Event: "added", Line: &line}) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(delta, append(row, '\n'), 0o600); err != nil { + t.Fatal(err) + } + var out bytes.Buffer + command := newCoverageCmd() + command.SetOut(&out) + command.SetArgs(args) + if err := command.Execute(); err == nil || !strings.Contains(out.String(), "unexplained") { + t.Fatalf("expected unexplained loss: %v: %s", err, out.String()) + } +} diff --git a/tools/transcript-archive/cmd/transcript-archive/coverage_state.go b/tools/transcript-archive/cmd/transcript-archive/coverage_state.go new file mode 100644 index 000000000..d712c43af --- /dev/null +++ b/tools/transcript-archive/cmd/transcript-archive/coverage_state.go @@ -0,0 +1,464 @@ +package main + +import ( + "archive/tar" + "bufio" + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "sort" + "strings" + "time" + + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/coverage" + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/inventory" +) + +// verifiedName holds archived digests already proven, so a check restores only new or changed files. +const verifiedName = "verified.jsonl" + +// archivedNode is restic's change-detection metadata for one file in a snapshot. +// restic reuses a parent's content only when these match, so equal nodes mean bytes already proven. +type archivedNode struct { + Size int64 `json:"size"` + Mtime time.Time `json:"mtime"` + Ctime time.Time `json:"ctime"` + Inode uint64 `json:"inode"` +} + +// same compares instants, so a time-zone change between passes still hits the cache. +func (n archivedNode) same(o archivedNode) bool { + return n.Size == o.Size && n.Inode == o.Inode && n.Mtime.Equal(o.Mtime) && n.Ctime.Equal(o.Ctime) +} + +// verifiedEntry records that path, at this local version and archived node, matched the archive in snapshot. +type verifiedEntry struct { + Path string `json:"path"` + Size int64 `json:"size"` + MtimeNs int64 `json:"mtimeNs"` + SHA256 [32]byte `json:"sha256"` + Node archivedNode `json:"node"` + Snapshot string `json:"snapshot"` +} + +// runStateCoverage checks that every live normal file is in the latest acked snapshot with matching bytes. +// Each pass backs up the whole tree, so the latest snapshot alone decides whether a delete is safe. +func runStateCoverage(out io.Writer, opts coverageOptions) error { + dir, err := filepath.Abs(opts.stateDir) + if err != nil { + return fmt.Errorf("resolve state directory: %w", err) + } + opts.passwordFile = filepath.Join(dir, "password") + opts.cacheDir = filepath.Join(dir, "restic-cache") + final, err := readInventory(filepath.Join(dir, "scan-current.jsonl")) + if err != nil { + return fmt.Errorf("read final inventory: %w", err) + } + snapshot, err := latestAcked(filepath.Join(dir, "journal.jsonl")) + if err != nil { + return err + } + wanted := make(map[string]inventory.Line, len(final.Lines)) + for _, line := range final.Lines { + if line.Type == "file" && line.Class == "normal" { + wanted[line.Path] = line + } + } + archived, totalBytes, err := listedNodes(opts, snapshot, wanted) + if err != nil { + return err + } + verified, err := readVerified(filepath.Join(dir, verifiedName)) + if err != nil { + return err + } + report := coverage.Report{Missing: []string{}, Extra: []string{}, Unexplained: []string{}, Truncated: []string{}, Rewritten: []string{}, HashMismatch: []string{}, History: []coverage.HistoryEntry{}} + next := make([]verifiedEntry, 0, len(wanted)) + var unverified []verifiedEntry + var unverifiedBytes int64 + for _, path := range sortedKeys(wanted) { + line := wanted[path] + node, ok := archived[path] + if !ok { + report.Missing = append(report.Missing, path) + continue + } + if node.Size != line.Size { + report.HashMismatch = append(report.HashMismatch, path) + continue + } + entry := verifiedEntry{Path: path, Size: line.Size, MtimeNs: line.MtimeNs, SHA256: line.SHA256, Node: node, Snapshot: snapshot} + if old, ok := verified[path]; ok && old.Size == entry.Size && old.MtimeNs == entry.MtimeNs && old.SHA256 == entry.SHA256 && old.Node.same(node) { + next = append(next, old) + continue + } + unverified = append(unverified, entry) + unverifiedBytes += entry.Size + } + var digests map[string][32]byte + // One tar stream reads each byte once. Restore costs one restic pass per batch, and each pass matches every snapshot node, + // so stream when unverified files outnumber one batch, or when most bytes are unverified. + if len(unverified) > 0 && (len(unverified) > restoreFiles || 2*unverifiedBytes >= totalBytes) { + digests, err = streamedDigests(opts, snapshot, unverified) + } else { + digests, err = restoredDigests(opts, filepath.Join(dir, "coverage-scratch"), snapshot, unverified) + } + if err != nil { + return err + } + for _, entry := range unverified { + if digests[entry.Path] != entry.SHA256 { + report.HashMismatch = append(report.HashMismatch, entry.Path) + continue + } + next = append(next, entry) + } + for _, item := range final.Errors { + report.Unexplained = append(report.Unexplained, item.Path) + } + if err := writeVerified(filepath.Join(dir, verifiedName), next); err != nil { + return err + } + report.Pass = len(report.Missing)+len(report.HashMismatch)+len(report.Unexplained) == 0 + return writeCoverageReport(out, report) +} + +// latestAcked streams the journal (no line-length cap) and returns the newest acked snapshot. +func latestAcked(path string) (snapshot string, err error) { + file, err := os.Open(path) //nolint:gosec // Journal inside the operator-supplied state directory. + if err != nil { + return "", fmt.Errorf("open journal: %w", err) + } + defer func() { err = errors.Join(err, file.Close()) }() + reader := bufio.NewReader(file) + for { + line, readErr := reader.ReadBytes('\n') + // A final line without a newline is a torn append; skip it, never truncate. + if len(line) > 0 && line[len(line)-1] == '\n' { + var event struct { + Event string `json:"event"` + SnapshotID string `json:"snapshotId"` + } + if err := json.Unmarshal(line, &event); err != nil { + return "", fmt.Errorf("decode journal: %w", err) + } + if event.Event == "pass-acked" { + snapshot = event.SnapshotID + } + } + if errors.Is(readErr, io.EOF) { + break + } + if readErr != nil { + return "", fmt.Errorf("read journal: %w", readErr) + } + } + if snapshot == "" { + return "", errors.New("state journal has no acked pass") + } + return snapshot, nil +} + +// listedNodes streams `restic ls` for one snapshot, keeps the nodes of wanted files, and sums every file's size. +func listedNodes(opts coverageOptions, snapshot string, wanted map[string]inventory.Line) (nodes map[string]archivedNode, totalBytes int64, err error) { + cmd, err := resticCommand(opts, "ls", "--json", "--no-lock", snapshot) + if err != nil { + return nil, 0, err + } + stdout, err := cmd.StdoutPipe() + if err != nil { + return nil, 0, fmt.Errorf("restic ls: %w", err) + } + if err := cmd.Start(); err != nil { + return nil, 0, fmt.Errorf("restic ls: %w", err) + } + nodes = make(map[string]archivedNode, len(wanted)) + decoder := json.NewDecoder(stdout) + for { + var node struct { + archivedNode + StructType string `json:"struct_type"` + Type string `json:"type"` + Path string `json:"path"` + } + if err := decoder.Decode(&node); errors.Is(err, io.EOF) { + break + } else if err != nil { + return nil, 0, errors.Join(fmt.Errorf("decode restic listing: %w", err), cmd.Wait()) + } + if node.StructType != "node" || node.Type != "file" { + continue + } + totalBytes += node.Size + if _, ok := wanted[node.Path]; ok { + nodes[node.Path] = node.archivedNode + } + } + if err := cmd.Wait(); err != nil { + return nil, 0, fmt.Errorf("restic ls: %w", err) + } + return nodes, totalBytes, nil +} + +// streamedDigests hashes the unverified files from one `restic dump --archive tar` of the whole snapshot. +// Missing files keep the zero digest, which reports a mismatch. +func streamedDigests(opts coverageOptions, snapshot string, entries []verifiedEntry) (digests map[string][32]byte, err error) { + want := make(map[string]struct{}, len(entries)) + for _, entry := range entries { + want[entry.Path] = struct{}{} + } + cmd, err := resticCommand(opts, "dump", "--no-lock", "--archive", "tar", snapshot, "/") + if err != nil { + return nil, err + } + stdout, err := cmd.StdoutPipe() + if err != nil { + return nil, fmt.Errorf("restic dump: %w", err) + } + if err := cmd.Start(); err != nil { + return nil, fmt.Errorf("restic dump: %w", err) + } + digests = make(map[string][32]byte, len(entries)) + archive := tar.NewReader(stdout) + for { + header, err := archive.Next() + if errors.Is(err, io.EOF) { + break + } + if err != nil { + return nil, errors.Join(fmt.Errorf("read restic dump: %w", err), killAndWait(cmd)) + } + path := "/" + strings.TrimPrefix(strings.TrimPrefix(header.Name, "./"), "/") + if _, ok := want[path]; !ok || header.Typeflag != tar.TypeReg { + continue + } + hash := sha256.New() + if _, err := io.Copy(hash, archive); err != nil { + return nil, errors.Join(fmt.Errorf("read restic dump: %w", err), killAndWait(cmd)) + } + digests[path] = [32]byte(hash.Sum(nil)) + } + // Drain any trailing padding so restic exits cleanly. + if _, err := io.Copy(io.Discard, stdout); err != nil { + return nil, errors.Join(fmt.Errorf("read restic dump: %w", err), killAndWait(cmd)) + } + if err := cmd.Wait(); err != nil { + return nil, fmt.Errorf("restic dump: %w", err) + } + return digests, nil +} + +// killAndWait stops a restic child we stopped reading; a live restic blocks on the full pipe, so Wait alone can hang. +func killAndWait(cmd *exec.Cmd) error { + if err := cmd.Process.Kill(); err != nil && !errors.Is(err, os.ErrProcessDone) { + return errors.Join(fmt.Errorf("kill restic: %w", err), cmd.Wait()) + } + return cmd.Wait() +} + +// Restore batches cap scratch disk use at about restoreBytes (or one file, if larger). +// Include matching costs patterns × snapshot nodes, so batches stay near 5000 patterns (~41 s on 200k nodes). +const ( + restoreFiles = 5000 + restoreBytes = 8 << 30 +) + +// restoredDigests restores only the unverified files, batch by batch, so restic fetches only their blobs. +func restoredDigests(opts coverageOptions, scratch, snapshot string, entries []verifiedEntry) (map[string][32]byte, error) { + digests := make(map[string][32]byte, len(entries)) + for start := 0; start < len(entries); { + end, size := start, int64(0) + for end < len(entries) && end-start < restoreFiles && (end == start || size+entries[end].Size <= restoreBytes) { + size += entries[end].Size + end++ + } + if err := restoreBatch(opts, scratch, snapshot, entries[start:end], digests); err != nil { + return nil, err + } + start = end + } + return digests, nil +} + +func restoreBatch(opts coverageOptions, scratch, snapshot string, batch []verifiedEntry, digests map[string][32]byte) (resultErr error) { + if err := os.RemoveAll(scratch); err != nil { + return fmt.Errorf("clear coverage scratch: %w", err) + } + target := filepath.Join(scratch, "target") + if err := os.MkdirAll(target, 0o700); err != nil { + return fmt.Errorf("create coverage scratch: %w", err) + } + defer func() { + if err := os.RemoveAll(scratch); err != nil { + resultErr = errors.Join(resultErr, fmt.Errorf("remove coverage scratch: %w", err)) + } + }() + var list strings.Builder + var direct []verifiedEntry + for _, entry := range batch { + line, ok := includePattern(entry.Path) + if !ok { + direct = append(direct, entry) + continue + } + list.WriteString(line + "\n") + } + for _, entry := range direct { + digest, err := dumpDigest(opts, snapshot, entry.Path) + if err != nil { + return err + } + digests[entry.Path] = digest + } + if list.Len() == 0 { + return nil + } + include := filepath.Join(scratch, "include.txt") + if err := os.WriteFile(include, []byte(list.String()), 0o600); err != nil { + return fmt.Errorf("write restore list: %w", err) + } + cmd, err := resticCommand(opts, "restore", "--no-lock", "--target", target, "--include-file", include, snapshot) + if err != nil { + return err + } + if err := cmd.Run(); err != nil { + return fmt.Errorf("restic restore: %w", err) + } + for _, entry := range batch { + if _, done := digests[entry.Path]; done { + continue + } + digest, err := fileDigest(filepath.Join(target, entry.Path)) + if errors.Is(err, os.ErrNotExist) { + continue // Not restored: the zero digest reports a mismatch. + } + if err != nil { + return err + } + digests[entry.Path] = digest + } + return nil +} + +// includePattern escapes path for a restic --include-file line; false means no escape exists. +func includePattern(path string) (string, bool) { + if strings.ContainsAny(path, "\r\n") || strings.TrimSpace(path) != path { + return "", false + } + var line strings.Builder + for _, r := range path { + switch r { + case '\\', '*', '?', '[': + line.WriteByte('\\') + case '$': + line.WriteByte('$') + } + line.WriteRune(r) + } + return line.String(), true +} + +// dumpDigest streams one archived file through sha256, for names no include pattern can match. +func dumpDigest(opts coverageOptions, snapshot, path string) (digest [32]byte, err error) { + cmd, err := resticCommand(opts, "dump", "--no-lock", snapshot, path) + if err != nil { + return digest, err + } + stdout, err := cmd.StdoutPipe() + if err != nil { + return digest, fmt.Errorf("restic dump: %w", err) + } + if err := cmd.Start(); err != nil { + return digest, fmt.Errorf("restic dump: %w", err) + } + hash := sha256.New() + if _, err := io.Copy(hash, stdout); err != nil { + return digest, errors.Join(fmt.Errorf("read restic dump: %w", err), cmd.Wait()) + } + if err := cmd.Wait(); err != nil { + return digest, fmt.Errorf("restic dump: %w", err) + } + return [32]byte(hash.Sum(nil)), nil +} + +func fileDigest(path string) (digest [32]byte, err error) { + file, err := os.Open(path) //nolint:gosec // Restored file inside the coverage scratch directory. + if err != nil { + return digest, err + } + defer func() { err = errors.Join(err, file.Close()) }() + hash := sha256.New() + if _, err := io.Copy(hash, file); err != nil { + return digest, fmt.Errorf("hash restored file: %w", err) + } + return [32]byte(hash.Sum(nil)), nil +} + +func readVerified(path string) (entries map[string]verifiedEntry, err error) { + entries = map[string]verifiedEntry{} + file, err := os.Open(path) //nolint:gosec // Verified cache inside the state directory. + if errors.Is(err, os.ErrNotExist) { + return entries, nil + } + if err != nil { + return nil, fmt.Errorf("open verified digests: %w", err) + } + defer func() { err = errors.Join(err, file.Close()) }() + decoder := json.NewDecoder(file) + for { + var entry verifiedEntry + if err := decoder.Decode(&entry); errors.Is(err, io.EOF) { + return entries, nil + } else if err != nil { + return nil, fmt.Errorf("decode verified digests: %w", err) + } + entries[entry.Path] = entry + } +} + +// writeVerified replaces the cache atomically; a crash leaves the previous cache, which only costs re-dumps. +func writeVerified(path string, entries []verifiedEntry) (resultErr error) { + temp, err := os.CreateTemp(filepath.Dir(path), ".verified-*") + if err != nil { + return fmt.Errorf("create verified digests: %w", err) + } + defer func() { + if err := os.Remove(temp.Name()); err != nil && !errors.Is(err, os.ErrNotExist) { + resultErr = errors.Join(resultErr, fmt.Errorf("remove verified temp: %w", err)) + } + }() + writer := bufio.NewWriter(temp) + encoder := json.NewEncoder(writer) + for _, entry := range entries { + if err := encoder.Encode(entry); err != nil { + return errors.Join(fmt.Errorf("encode verified digests: %w", err), temp.Close()) + } + } + if err := writer.Flush(); err != nil { + return errors.Join(fmt.Errorf("write verified digests: %w", err), temp.Close()) + } + if err := temp.Sync(); err != nil { + return errors.Join(fmt.Errorf("sync verified digests: %w", err), temp.Close()) + } + if err := temp.Close(); err != nil { + return fmt.Errorf("close verified digests: %w", err) + } + if err := os.Rename(temp.Name(), path); err != nil { + return fmt.Errorf("install verified digests: %w", err) + } + return nil +} + +func sortedKeys(lines map[string]inventory.Line) []string { + keys := make([]string, 0, len(lines)) + for key := range lines { + keys = append(keys, key) + } + sort.Strings(keys) + return keys +} diff --git a/tools/transcript-archive/cmd/transcript-archive/coverage_test.go b/tools/transcript-archive/cmd/transcript-archive/coverage_test.go new file mode 100644 index 000000000..57cdc337e --- /dev/null +++ b/tools/transcript-archive/cmd/transcript-archive/coverage_test.go @@ -0,0 +1,55 @@ +package main + +import ( + "bytes" + "crypto/sha256" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/inventory" +) + +func TestCoverageCommandHistoryAndAssignment(t *testing.T) { + dir := t.TempDir() + digest := sha256.Sum256([]byte("old")) + line := inventory.Line{Path: "/old", Type: "file", Class: "normal", Size: 3, SHA256: digest} + row, err := json.Marshal(inventory.DeltaRow{Event: "added", Line: &line}) + if err != nil { + t.Fatal(err) + } + files := map[string]string{ + "final": "{\"outsideTargets\":0}\n", "baseline": "{\"outsideTargets\":0}\n", + "delta-1.jsonl": string(row) + "\n", "journal": "{\"event\":\"pass-stored\",\"passId\":\"1\"}\n", + "digests": "{}", "vanished": "", "password": "secret", + "restic": "#!/bin/sh\ncase \" $* \" in\n*' snapshots '*) echo '[{\"id\":\"old\",\"time\":\"2026-01-01T00:00:00Z\",\"tags\":[\"pass-1\"]}]';;\n*' old '*) echo '{\"struct_type\":\"node\",\"type\":\"file\",\"path\":\"/old\"}';;\n*) echo '{\"struct_type\":\"snapshot\"}';;\nesac\n", + } + for name, content := range files { + if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o700); err != nil { + t.Fatal(err) + } + } + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + args := []string{"--final", filepath.Join(dir, "final"), "--baseline", filepath.Join(dir, "baseline"), "--deltas", filepath.Join(dir, "delta-1.jsonl"), "--scope", "test", "--snapshot", "final", "--repo", dir, "--password-file", filepath.Join(dir, "password"), "--journal", filepath.Join(dir, "journal"), "--digests", filepath.Join(dir, "digests"), "--vanished", filepath.Join(dir, "vanished")} + command := newCoverageCmd() + var output bytes.Buffer + command.SetOut(&output) + command.SetArgs(args) + if err := command.Execute(); err != nil { + t.Fatalf("history should explain missing version: %v: %s", err, output.String()) + } + if !strings.Contains(output.String(), `"snapshotId":"old"`) { + t.Fatalf("history missing: %s", output.String()) + } + if err := os.WriteFile(filepath.Join(dir, "final"), []byte("{\"error\":{\"path\":\"/unknown\",\"reason\":\"unknown\"}}\n"), 0o600); err != nil { + t.Fatal(err) + } + command = newCoverageCmd() + command.SetOut(&output) + command.SetArgs(args) + if err := command.Execute(); err == nil { + t.Fatal("assignment error should fail coverage") + } +} diff --git a/tools/transcript-archive/cmd/transcript-archive/escrow.go b/tools/transcript-archive/cmd/transcript-archive/escrow.go new file mode 100644 index 000000000..9ddabfa64 --- /dev/null +++ b/tools/transcript-archive/cmd/transcript-archive/escrow.go @@ -0,0 +1,113 @@ +package main + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "os" + "path/filepath" + + "filippo.io/age" +) + +// fileEscrower age-encrypts the scope password to one file and records the plaintext sha256 beside it. +type fileEscrower struct { + out string + recipient age.Recipient +} + +func newFileEscrower(out, recipient string) (*fileEscrower, error) { + parsed, err := age.ParseX25519Recipient(recipient) + if err != nil { + return nil, fmt.Errorf("parse escrow recipient: %w", err) + } + return &fileEscrower{out: out, recipient: parsed}, nil +} + +// Put writes the escrow once; an existing escrow is accepted only for the same password. +func (e *fileEscrower) Put(ctx context.Context, _ string, body []byte) ([32]byte, error) { + if err := ctx.Err(); err != nil { + return [32]byte{}, err + } + plain := sha256.Sum256(body) + digest := []byte(hex.EncodeToString(plain[:]) + "\n") + if err := installOnce(e.out+".sha256", digest); err != nil { + return [32]byte{}, err + } + var ciphertext bytes.Buffer + writer, err := age.Encrypt(&ciphertext, e.recipient) + if err != nil { + return [32]byte{}, fmt.Errorf("encrypt escrow: %w", err) + } + if _, err := writer.Write(body); err != nil { + return [32]byte{}, fmt.Errorf("encrypt escrow: %w", err) + } + if err := writer.Close(); err != nil { + return [32]byte{}, fmt.Errorf("encrypt escrow: %w", err) + } + if err := installFile(e.out, ciphertext.Bytes()); err != nil && !errors.Is(err, os.ErrExist) { + return [32]byte{}, err + } + // The sidecar matched, so an existing escrow file holds this password; report its bytes. + stored, err := os.ReadFile(e.out) + if err != nil { + return [32]byte{}, fmt.Errorf("read escrow: %w", err) + } + return sha256.Sum256(stored), nil +} + +// installOnce writes data at path, or accepts an existing file with identical bytes. +func installOnce(path string, data []byte) error { + err := installFile(path, data) + if !errors.Is(err, os.ErrExist) { + return err + } + existing, readErr := os.ReadFile(path) //nolint:gosec // Operator-supplied escrow path. + if readErr != nil { + return fmt.Errorf("read escrow digest: %w", readErr) + } + if !bytes.Equal(existing, data) { + return errors.New("escrow-out already holds a different password; refusing to overwrite") + } + return nil +} + +// installFile fsyncs data to a temp file and hard-links it into place, failing with os.ErrExist. +func installFile(path string, data []byte) (resultErr error) { + dir := filepath.Dir(path) + if err := os.MkdirAll(dir, 0o700); err != nil { + return fmt.Errorf("create escrow directory: %w", err) + } + temp, err := os.CreateTemp(dir, ".escrow-*") + if err != nil { + return fmt.Errorf("create escrow: %w", err) + } + defer func() { + if err := os.Remove(temp.Name()); err != nil && !errors.Is(err, os.ErrNotExist) { + resultErr = errors.Join(resultErr, fmt.Errorf("remove escrow temp: %w", err)) + } + }() + if _, err := temp.Write(data); err != nil { + return errors.Join(fmt.Errorf("write escrow: %w", err), temp.Close()) + } + if err := temp.Sync(); err != nil { + return errors.Join(fmt.Errorf("sync escrow: %w", err), temp.Close()) + } + if err := temp.Close(); err != nil { + return fmt.Errorf("close escrow: %w", err) + } + if err := os.Link(temp.Name(), path); err != nil { + if errors.Is(err, os.ErrExist) { + return os.ErrExist + } + return fmt.Errorf("install escrow: %w", err) + } + directory, err := os.Open(dir) //nolint:gosec // Escrow directory for fsync. + if err != nil { + return fmt.Errorf("open escrow directory: %w", err) + } + return errors.Join(directory.Sync(), directory.Close()) +} diff --git a/tools/transcript-archive/cmd/transcript-archive/fence.go b/tools/transcript-archive/cmd/transcript-archive/fence.go new file mode 100644 index 000000000..139403884 --- /dev/null +++ b/tools/transcript-archive/cmd/transcript-archive/fence.go @@ -0,0 +1,31 @@ +package main + +import ( + "os" + "os/signal" + "syscall" + "time" + + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/fence" + "github.com/spf13/cobra" +) + +func newFenceCmd() *cobra.Command { + var agentDirs []string + var wait time.Duration + command := &cobra.Command{ + Use: "fence", + Short: "Hold OMP garbage collection locks", + Args: cobra.NoArgs, + SilenceErrors: true, + SilenceUsage: true, + RunE: func(command *cobra.Command, _ []string) error { + ctx, stop := signal.NotifyContext(command.Context(), os.Interrupt, syscall.SIGTERM, syscall.SIGHUP) + defer stop() + return fence.Run(ctx, fence.Options{AgentDirs: agentDirs, Wait: wait}) + }, + } + command.Flags().StringArrayVar(&agentDirs, "agent-dir", nil, "agent directory to fence (repeat for multiple directories)") + command.Flags().DurationVar(&wait, "wait", 30*time.Minute, "maximum time to wait for an existing lock") + return command +} diff --git a/tools/transcript-archive/cmd/transcript-archive/get.go b/tools/transcript-archive/cmd/transcript-archive/get.go new file mode 100644 index 000000000..cfd53d67e --- /dev/null +++ b/tools/transcript-archive/cmd/transcript-archive/get.go @@ -0,0 +1,46 @@ +package main + +import ( + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/retrieve" + "github.com/spf13/cobra" +) + +func newGetCmd() *cobra.Command { + var options retrieve.Options + command := &cobra.Command{ + Use: "get", + Short: "Restore one archived transcript record", + Args: cobra.NoArgs, + SilenceErrors: true, + SilenceUsage: true, + RunE: func(cmd *cobra.Command, _ []string) error { + return retrieve.Get(cmd.Context(), options) + }, + } + flags := command.Flags() + flags.StringVar(&options.Repo, "repo", "", "restic repository path or URL") + flags.StringVar(&options.Escrow, "escrow", "", "age-encrypted escrow file") + flags.StringVar(&options.Identity, "identity", "", "age identity file") + flags.StringVar(&options.Snapshot, "snapshot", "", "restic snapshot id") + flags.StringVar(&options.Record, "record", "", "OMP record stem") + flags.StringVar(&options.Output, "out", "", "output directory") + if err := command.MarkFlagRequired("repo"); err != nil { + return command + } + if err := command.MarkFlagRequired("escrow"); err != nil { + return command + } + if err := command.MarkFlagRequired("identity"); err != nil { + return command + } + if err := command.MarkFlagRequired("snapshot"); err != nil { + return command + } + if err := command.MarkFlagRequired("record"); err != nil { + return command + } + if err := command.MarkFlagRequired("out"); err != nil { + return command + } + return command +} diff --git a/tools/transcript-archive/cmd/transcript-archive/inventory.go b/tools/transcript-archive/cmd/transcript-archive/inventory.go new file mode 100644 index 000000000..ebd363054 --- /dev/null +++ b/tools/transcript-archive/cmd/transcript-archive/inventory.go @@ -0,0 +1,206 @@ +package main + +import ( + "bufio" + "encoding/json" + "errors" + "fmt" + "io" + "os" + + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/config" + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/inventory" + "github.com/spf13/cobra" +) + +func newInventoryCmd() *cobra.Command { + var host, configPath, previousPath, deltaPath, outPath string + command := &cobra.Command{ + Use: "inventory", + Short: "Inventory transcript source files", + Args: cobra.NoArgs, + PreRunE: func(command *cobra.Command, _ []string) error { + if host == "" || configPath == "" || outPath == "" { + return errors.New("inventory requires host, config and out") + } + return nil + }, + RunE: func(command *cobra.Command, _ []string) error { + return runInventory(host, configPath, previousPath, deltaPath, outPath) + }, + } + command.Flags().StringVar(&host, "host", "", "host name from the archive config") + command.Flags().StringVar(&configPath, "config", "", "archive CUE config path (required)") + command.Flags().StringVar(&previousPath, "previous", "", "previous inventory JSONL path") + command.Flags().StringVar(&deltaPath, "delta", "", "scan delta output path") + command.Flags().StringVar(&outPath, "out", "", "inventory output path") + return command +} + +func runInventory(host, configPath, previousPath, deltaPath, outPath string) error { + var previous *inventory.Inventory + if previousPath != "" { + var err error + previous, err = readInventory(previousPath) + if err != nil { + return fmt.Errorf("read previous inventory: %w", err) + } + } + current, delta, empty, err := walkHost(host, configPath, previous) + if err != nil { + return err + } + if empty { + return writeEmptyInventory(outPath) + } + output, err := os.Create(outPath) //nolint:gosec // Operator-supplied output path. + if err != nil { + return fmt.Errorf("create inventory output: %w", err) + } + if err := errors.Join(writeInventory(output, current), output.Close()); err != nil { + return fmt.Errorf("write inventory output: %w", err) + } + if deltaPath != "" { + return writeDelta(deltaPath, delta) + } + return nil +} + +// hostWalk loads a host's walk set rooted at HOME; empty reports an empty-state host with no sources. +func hostWalk(host, configPath string) (walk config.Walk, empty bool, err error) { + loaded, err := config.Load(configPath) + if err != nil { + return walk, false, err + } + walk, err = loaded.Walk(host) + if err != nil { + return walk, false, err + } + if walk.State == "empty" && len(walk.Sources) == 0 { + return walk, true, nil + } + walk.Root, err = os.UserHomeDir() + if err != nil { + return walk, false, fmt.Errorf("resolve home directory: %w", err) + } + return walk, false, nil +} + +// walkHost inventories a host's configured sources under HOME; empty reports an empty-state host with no sources. +func walkHost(host, configPath string, previous *inventory.Inventory) (current inventory.Inventory, delta inventory.Delta, empty bool, err error) { + walk, empty, err := hostWalk(host, configPath) + if err != nil || empty { + return current, delta, empty, err + } + current, delta, err = inventory.Walk(walk, previous) + return current, delta, false, err +} + +func readInventory(path string) (*inventory.Inventory, error) { + file, err := os.Open(path) //nolint:gosec // Path is an operator-supplied CLI flag. + if err != nil { + return nil, err + } + defer func() { + _ = file.Close() + }() + result := inventory.Inventory{Lines: []inventory.Line{}, Dangling: []inventory.Dangling{}, Excluded: []inventory.Excluded{}, Errors: []inventory.AssignError{}} + scanner := bufio.NewScanner(file) + scanner.Buffer(make([]byte, 64*1024), 4*1024*1024) + for scanner.Scan() { + var row struct { + Error *inventory.AssignError `json:"error"` + Dangling *inventory.Dangling `json:"dangling"` + Excluded *inventory.Excluded `json:"excluded"` + OutsideTargets *int `json:"outsideTargets"` + } + if err := json.Unmarshal(scanner.Bytes(), &row); err != nil { + return nil, err + } + var line inventory.Line + if err := json.Unmarshal(scanner.Bytes(), &line); err != nil { + return nil, err + } + if line.Path != "" { + result.Lines = append(result.Lines, line) + } + if row.Error != nil { + result.Errors = append(result.Errors, *row.Error) + } + if row.Dangling != nil { + result.Dangling = append(result.Dangling, *row.Dangling) + } + if row.Excluded != nil { + result.Excluded = append(result.Excluded, *row.Excluded) + } + if row.OutsideTargets != nil { + result.OutsideTargets = *row.OutsideTargets + } + } + if err := scanner.Err(); err != nil { + return nil, err + } + return &result, nil +} + +func writeInventory(writer io.Writer, inv inventory.Inventory) error { + encoder := json.NewEncoder(writer) + for _, line := range inv.Lines { + if err := encoder.Encode(line); err != nil { + return err + } + } + for _, excluded := range inv.Excluded { + if err := encoder.Encode(struct { + Excluded inventory.Excluded `json:"excluded"` + }{Excluded: excluded}); err != nil { + return err + } + } + for _, dangling := range inv.Dangling { + if err := encoder.Encode(struct { + Dangling inventory.Dangling `json:"dangling"` + }{Dangling: dangling}); err != nil { + return err + } + } + for _, assignment := range inv.Errors { + if err := encoder.Encode(struct { + Error inventory.AssignError `json:"error"` + }{Error: assignment}); err != nil { + return err + } + } + return encoder.Encode(struct { + OutsideTargets int `json:"outsideTargets"` + }{OutsideTargets: inv.OutsideTargets}) +} + +// writeEmptyInventory records an empty-state host with no sources as a zero-line inventory. +func writeEmptyInventory(outPath string) error { + output, err := os.Create(outPath) //nolint:gosec // Operator-supplied output path. + if err != nil { + return fmt.Errorf("create inventory output: %w", err) + } + empty := inventory.Inventory{Lines: []inventory.Line{}, Dangling: []inventory.Dangling{}, Excluded: []inventory.Excluded{}, Errors: []inventory.AssignError{}} + if err := errors.Join(writeInventory(output, empty), output.Close()); err != nil { + return fmt.Errorf("write inventory output: %w", err) + } + return nil +} + +func writeDelta(path string, delta inventory.Delta) error { + file, err := os.Create(path) //nolint:gosec // Path is an operator-supplied CLI flag. + if err != nil { + return fmt.Errorf("create delta output: %w", err) + } + encoder := json.NewEncoder(file) + if err := inventory.WriteDelta(encoder, delta); err != nil { + closeErr := file.Close() + return errors.Join(fmt.Errorf("encode delta: %w", err), closeErr) + } + if err := file.Close(); err != nil { + return fmt.Errorf("close delta output: %w", err) + } + return nil +} diff --git a/tools/transcript-archive/cmd/transcript-archive/inventory_rows_test.go b/tools/transcript-archive/cmd/transcript-archive/inventory_rows_test.go new file mode 100644 index 000000000..759cc671d --- /dev/null +++ b/tools/transcript-archive/cmd/transcript-archive/inventory_rows_test.go @@ -0,0 +1,31 @@ +package main + +import ( + "os" + "path/filepath" + "testing" + + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/inventory" +) + +func TestInventoryRowsRoundTrip(t *testing.T) { + path := filepath.Join(t.TempDir(), "inventory") + file, err := os.Create(path) + if err != nil { + t.Fatal(err) + } + want := inventory.Inventory{Lines: []inventory.Line{{Path: "/file"}}, Errors: []inventory.AssignError{{Path: "/unknown", Reason: "unknown"}}, Dangling: []inventory.Dangling{{Path: "/file", Reason: "missing"}}, Excluded: []inventory.Excluded{{Count: 2, Bytes: 3}}, OutsideTargets: 4} + if err := writeInventory(file, want); err != nil { + t.Fatal(err) + } + if err := file.Close(); err != nil { + t.Fatal(err) + } + got, err := readInventory(path) + if err != nil { + t.Fatal(err) + } + if len(got.Lines) != 1 || len(got.Errors) != 1 || len(got.Dangling) != 1 || len(got.Excluded) != 1 || got.OutsideTargets != 4 { + t.Fatalf("incomplete inventory: %+v", got) + } +} diff --git a/tools/transcript-archive/cmd/transcript-archive/inventory_test.go b/tools/transcript-archive/cmd/transcript-archive/inventory_test.go new file mode 100644 index 000000000..ef8ed4a5b --- /dev/null +++ b/tools/transcript-archive/cmd/transcript-archive/inventory_test.go @@ -0,0 +1,74 @@ +package main + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// fixtureConfig is the synthetic archive config under testdata/. +const fixtureConfig = "../../testdata/archive.cue" + +func TestInventoryEmptyHostWritesEmptyInventory(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + out := filepath.Join(t.TempDir(), "inventory.jsonl") + if err := runInventory("example-empty", fixtureConfig, "", "", out); err != nil { + t.Fatalf("empty host failed: %v", err) + } + got, err := readInventory(out) + if err != nil { + t.Fatal(err) + } + if len(got.Lines) != 0 || len(got.Errors) != 0 { + t.Fatalf("empty host inventory = %+v, want no lines or errors", got) + } +} + +func TestInventoryNonEmptyHostWithNoSourcesFails(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + configPath := filepath.Join(t.TempDir(), "archive.cue") + if err := os.WriteFile(configPath, []byte(`package archive +hosts: bare: { + state: "unmeasured" + sources: [] + watch: [] + exclude: [] + finalOnly: [] +} +`), 0o600); err != nil { + t.Fatal(err) + } + out := filepath.Join(t.TempDir(), "inventory.jsonl") + if err := runInventory("bare", configPath, "", "", out); err == nil { + t.Fatal("unmeasured host with no sources accepted") + } +} + +func TestInventoryRequiresConfig(t *testing.T) { + t.Parallel() + command := newInventoryCmd() + command.SilenceUsage = true + command.SilenceErrors = true + command.SetArgs([]string{"--host", "example-host", "--out", filepath.Join(t.TempDir(), "inventory.jsonl")}) + err := command.ExecuteContext(t.Context()) + if err == nil { + t.Fatal("inventory without --config exited zero") + } + if msg := err.Error(); !strings.HasPrefix(msg, "inventory requires ") { + t.Fatalf("inventory error = %q, want the required-flag error", msg) + } +} + +// TestInventoryConfigFlagHasNoDefault pins the empty default: a default would +// let inventory start without the config that the required-flag check demands. +func TestInventoryConfigFlagHasNoDefault(t *testing.T) { + t.Parallel() + flag := newInventoryCmd().Flags().Lookup("config") + if flag == nil { + t.Fatal("inventory has no --config flag") + } + if flag.DefValue != "" { + t.Fatalf("--config default = %q, want empty", flag.DefValue) + } +} diff --git a/tools/transcript-archive/cmd/transcript-archive/main.go b/tools/transcript-archive/cmd/transcript-archive/main.go new file mode 100644 index 000000000..34f9f46ef --- /dev/null +++ b/tools/transcript-archive/cmd/transcript-archive/main.go @@ -0,0 +1,41 @@ +package main + +import ( + "context" + "errors" + "fmt" + "os" + "os/signal" + "syscall" + + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/fence" + "github.com/spf13/cobra" +) + +func main() { + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + err := newRootCmd().ExecuteContext(ctx) + stop() + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(exitCode(err)) + } +} + +func newRootCmd() *cobra.Command { + command := &cobra.Command{ + Use: "transcript-archive", + Short: "Inventory and verify transcript archives", + SilenceUsage: true, + SilenceErrors: true, + } + command.AddCommand(newInventoryCmd(), newCoverageCmd(), newGetCmd(), newFenceCmd(), newPassCmd(), newRawCapCmd()) + return command +} + +func exitCode(err error) int { + if exitErr, ok := errors.AsType[*fence.ExitError](err); ok { + return exitErr.Code + } + return 1 +} diff --git a/tools/transcript-archive/cmd/transcript-archive/main_test.go b/tools/transcript-archive/cmd/transcript-archive/main_test.go new file mode 100644 index 000000000..c20268a30 --- /dev/null +++ b/tools/transcript-archive/cmd/transcript-archive/main_test.go @@ -0,0 +1,202 @@ +package main + +import ( + "context" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "testing" + "time" + + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/fence" +) + +func TestRootCommandRegistersFence(t *testing.T) { + command, _, err := newRootCmd().Find([]string{"fence"}) + if err != nil { + t.Fatal(err) + } + if command.Name() != "fence" { + t.Fatalf("command = %q, want fence", command.Name()) + } + if command.Flags().Lookup("agent-dir") == nil { + t.Fatal("fence command is missing --agent-dir") + } + if command.Flags().Lookup("wait") == nil { + t.Fatal("fence command is missing --wait") + } +} + +func TestFenceCommandReturnsExitCodeThreeWhenOMPUnavailable(t *testing.T) { + // The fence command must surface Run's error instead of swallowing it. With + // OMP absent, Run fails before any lock is taken, so the command must return + // an error that maps to exit 3. The cancel contract is covered in the fence + // package, where Run is driven directly. + t.Setenv("PATH", t.TempDir()) + command := newFenceCmd() + command.SetArgs([]string{"--agent-dir", t.TempDir()}) + err := command.ExecuteContext(t.Context()) + if err == nil { + t.Fatal("fence returned nil with OMP unavailable, want non-zero exit") + } + if exitCode(err) != 3 { + t.Fatalf("exitCode(%v) = %d, want 3 for unavailable OMP", err, exitCode(err)) + } +} + +func TestExitCode(t *testing.T) { + externalErr := exec.Command("/bin/sh", "-c", "exit 3").Run() + if externalErr == nil { + t.Fatal("child process unexpectedly succeeded") + } + if _, ok := errors.AsType[*exec.ExitError](externalErr); !ok { + t.Fatalf("child error = %T, want *exec.ExitError", externalErr) + } + + tests := []struct { + name string + err error + want int + }{ + { + name: "unsupported OMP version", + err: fmt.Errorf("fence: %w", &fence.ExitError{Code: 3, Message: "unsupported omp version"}), + want: 3, + }, + { + name: "live PID lock", + err: fmt.Errorf("fence: %w", &fence.ExitError{Code: 4, Message: "live lock"}), + want: 4, + }, + { + name: "wrapped external process error", + err: fmt.Errorf("restic backup: %w", externalErr), + want: 1, + }, + { + name: "ordinary error", + err: errors.New("failed to fence agent directory"), + want: 1, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := exitCode(test.err); got != test.want { + t.Fatalf("exitCode(%v) = %d, want %d", test.err, got, test.want) + } + }) + } +} + +func TestFenceCommandCancelDuringAcquireExitsNonZero(t *testing.T) { + installFakeOMP(t) + root := t.TempDir() + heldDir := filepath.Join(root, "held") + liveDir := filepath.Join(root, "live") + writeLiveLock(t, liveDir) + + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + command := newFenceCmd() + command.SetArgs([]string{"--agent-dir", heldDir, "--agent-dir", liveDir, "--wait", "1h"}) + done := make(chan error, 1) + go func() { + done <- command.ExecuteContext(ctx) + }() + // held is free, so the fence takes it. live is held by a live PID, so the + // fence waits on it until the cancel below. + waitForGCLock(t, filepath.Join(heldDir, "gc.lock")) + cancel() + err := awaitFence(t, done) + if err == nil { + t.Fatal("fence returned nil after cancel during acquire, want non-zero exit") + } + if exitCode(err) == 0 { + t.Fatalf("exitCode(%v) = 0, want non-zero", err) + } +} + +func TestFenceCommandCancelDuringHoldExitsZero(t *testing.T) { + installFakeOMP(t) + root := t.TempDir() + firstDir := filepath.Join(root, "first") + secondDir := filepath.Join(root, "second") + + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + command := newFenceCmd() + command.SetArgs([]string{"--agent-dir", firstDir, "--agent-dir", secondDir, "--wait", "1h"}) + done := make(chan error, 1) + go func() { + done <- command.ExecuteContext(ctx) + }() + // Wait for both locks before cancelling, so the cancel lands in the hold phase. + waitForGCLock(t, filepath.Join(firstDir, "gc.lock")) + waitForGCLock(t, filepath.Join(secondDir, "gc.lock")) + cancel() + if err := awaitFence(t, done); err != nil { + t.Fatalf("cancel during hold returned %v, want nil (exit 0)", err) + } +} + +func installFakeOMP(t *testing.T) { + t.Helper() + binDir := t.TempDir() + fakeOMP := filepath.Join(binDir, "omp") + script := "#!/bin/sh\nprintf '%s\\n' '" + fence.OMPVersion + "'\n" + if err := os.WriteFile(fakeOMP, []byte(script), 0o600); err != nil { + t.Fatal("write fake OMP") + } + if err := os.Chmod(fakeOMP, 0o700); err != nil { + t.Fatal("make fake OMP executable") + } + t.Setenv("PATH", binDir) +} + +// writeLiveLock writes agentDir's gc.lock with this test process's PID and a +// fresh timestamp, so the fence sees a lock held by a live process. +func writeLiveLock(t *testing.T, agentDir string) { + t.Helper() + if err := os.MkdirAll(agentDir, 0o700); err != nil { + t.Fatal("create live agent directory fixture") + } + contents := fmt.Sprintf("%d\n%s\n", os.Getpid(), time.Now().UTC().Format(time.RFC3339Nano)) + if err := os.WriteFile(filepath.Join(agentDir, "gc.lock"), []byte(contents), 0o600); err != nil { + t.Fatal("write live gc lock fixture") + } +} + +// waitForGCLock polls until path exists, so a cancel lands after the fence has +// taken that lock. +func waitForGCLock(t *testing.T, path string) { + t.Helper() + timer := time.NewTimer(5 * time.Second) + defer timer.Stop() + ticker := time.NewTicker(10 * time.Millisecond) + defer ticker.Stop() + for { + if _, err := os.Stat(path); err == nil { + return + } + select { + case <-timer.C: + t.Fatalf("fence did not take %s", path) + case <-ticker.C: + } + } +} + +// awaitFence waits for the fence command to return after its context is cancelled. +func awaitFence(t *testing.T, done <-chan error) error { + t.Helper() + select { + case err := <-done: + return err + case <-time.After(5 * time.Second): + t.Fatal("fence did not return after cancel") + return nil + } +} diff --git a/tools/transcript-archive/cmd/transcript-archive/pass.go b/tools/transcript-archive/cmd/transcript-archive/pass.go new file mode 100644 index 000000000..d0b44f265 --- /dev/null +++ b/tools/transcript-archive/cmd/transcript-archive/pass.go @@ -0,0 +1,168 @@ +package main + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "time" + + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/client" + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/config" + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/fence" + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/inventory" + "github.com/spf13/cobra" +) + +type passOptions struct { + host, configPath, stateDir, repo string + escrowOut, escrowRecipient string + restic string +} + +func newPassCmd() *cobra.Command { + var opts passOptions + command := &cobra.Command{ + Use: "pass", + Short: "Inventory this host and archive changed transcripts in one restic pass", + Long: `pass inventories the host, opens the scope state in --state-dir, recovers any +unfinished pass, records a scan and runs one restic backup. Run it from a timer. + +The repository password is generated once in --state-dir and escrowed, +age-encrypted, to --escrow-out before the repository is initialized. RESTIC_* +variables in the environment are ignored. For an S3 (s3:) repository, set +AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY; they are passed through to restic. + +Exit 0 means the pass was acked. Any other result exits non-zero with one line +on stderr; the next run recovers.`, + Args: cobra.NoArgs, + RunE: func(command *cobra.Command, _ []string) error { + return runPass(command.Context(), opts) + }, + } + command.Flags().StringVar(&opts.host, "host", "", "host name from the archive config (also the archive scope)") + command.Flags().StringVar(&opts.configPath, "config", "", "archive CUE config path (required)") + command.Flags().StringVar(&opts.stateDir, "state-dir", "", "private scope state directory") + command.Flags().StringVar(&opts.repo, "repo", "", "restic repository") + command.Flags().StringVar(&opts.escrowOut, "escrow-out", "", "age-encrypted password escrow file (written once)") + command.Flags().StringVar(&opts.escrowRecipient, "escrow-recipient", "", "age recipient for the escrow (required)") + command.Flags().StringVar(&opts.restic, "restic", "restic", "restic binary (default resolves restic on PATH)") + return command +} + +func runPass(ctx context.Context, opts passOptions) (err error) { + if opts.host == "" || opts.configPath == "" || opts.stateDir == "" || opts.repo == "" || opts.escrowOut == "" || opts.escrowRecipient == "" { + return errors.New("pass requires host, config, state-dir, repo, escrow-out and escrow-recipient") + } + escrow, err := newFileEscrower(opts.escrowOut, opts.escrowRecipient) + if err != nil { + return err + } + walk, empty, err := hostWalk(opts.host, opts.configPath) + if err != nil || empty { + return err + } + scratch := filepath.Join(opts.stateDir, "scratch") + for _, dir := range []string{opts.stateDir, scratch} { + if err := refuseUnderSource(walk, dir); err != nil { + return err + } + } + // One pass per state dir: a manual run beside the timer must not interleave journal writes. + release, err := fence.Lock(ctx, opts.stateDir, time.Now()) + if err != nil { + return fmt.Errorf("lock state directory: %w", err) + } + defer func() { err = errors.Join(err, release()) }() + c, err := client.Open(opts.stateDir, client.RepoRef{Scope: opts.host, Repository: opts.repo}, escrow, + client.WithScratch(scratch), client.WithRestic(opts.restic)) + if err != nil { + return err + } + // Open replays and republishes scan-current.jsonl, so it is the last committed scan. + var previous *inventory.Inventory + if prior, err := readInventory(filepath.Join(opts.stateDir, "scan-current.jsonl")); err == nil { + previous = prior + } else if !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("read previous inventory: %w", err) + } + current, delta, err := inventory.Walk(walk, previous) + if err != nil { + return err + } + if err := c.Recover(ctx); err != nil { + return err + } + if err := c.Scan(ctx, current, delta); err != nil { + return err + } + // Every live non-final-only file goes in, so a file left pending by a failed pass is retried; restic skips unchanged ones. + files := make([]string, 0, len(current.Lines)) + for _, line := range current.Lines { + if line.Type == "file" && line.Class != "final-only" { + files = append(files, line.Path) + } + } + outcome, err := c.Pass(ctx, files, nil) + if err != nil { + return err + } + if outcome.Kind != client.Acked { + return fmt.Errorf("pass %s not acked (kind %d, restic exit %d)", outcome.PassID, outcome.Kind, outcome.ExitCode) + } + return nil +} + +// refuseUnderSource rejects dir when it or any ancestor matches a source root, so a pass never archives its own state. +func refuseUnderSource(walk config.Walk, dir string) error { + real, err := resolveExisting(dir) + if err != nil { + return err + } + for _, source := range walk.Sources { + pattern, err := inventory.SourcePath(walk, source.Path) + if err != nil { + return err + } + patterns := []string{pattern} + if resolved, err := resolveExisting(pattern); err == nil && resolved != pattern { + patterns = append(patterns, resolved) + } + for path := real; ; path = filepath.Dir(path) { + for _, pattern := range patterns { + if matched, err := filepath.Match(pattern, path); err != nil { + return fmt.Errorf("source %q pattern: %w", source.Name, err) + } else if matched { + return fmt.Errorf("%s is under source %q; move it outside the walked roots", real, source.Name) + } + } + if parent := filepath.Dir(path); parent == path { + break + } + } + } + return nil +} + +// resolveExisting makes path absolute and resolves symlinks in its longest existing prefix. +func resolveExisting(path string) (string, error) { + abs, err := filepath.Abs(path) + if err != nil { + return "", fmt.Errorf("resolve %s: %w", path, err) + } + rest := "" + for prefix := abs; ; prefix = filepath.Dir(prefix) { + resolved, err := filepath.EvalSymlinks(prefix) + if err == nil { + return filepath.Join(resolved, rest), nil + } + if !errors.Is(err, os.ErrNotExist) { + return "", fmt.Errorf("resolve %s: %w", prefix, err) + } + if filepath.Dir(prefix) == prefix { + return abs, nil + } + rest = filepath.Join(filepath.Base(prefix), rest) + } +} diff --git a/tools/transcript-archive/cmd/transcript-archive/pass_test.go b/tools/transcript-archive/cmd/transcript-archive/pass_test.go new file mode 100644 index 000000000..26e214007 --- /dev/null +++ b/tools/transcript-archive/cmd/transcript-archive/pass_test.go @@ -0,0 +1,492 @@ +package main + +import ( + "bytes" + "encoding/json" + "fmt" + "os" + "os/exec" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "filippo.io/age" + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/coverage" + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/fence" +) + +type passFixture struct { + opts passOptions + identity *age.X25519Identity + session string + calls string +} + +// newPassFixture writes a one-source config under a temp HOME and a wrapper restic that logs each call. +func newPassFixture(t *testing.T) passFixture { + t.Helper() + home := t.TempDir() + t.Setenv("HOME", home) + sessions := filepath.Join(home, "sessions") + if err := os.MkdirAll(sessions, 0o700); err != nil { + t.Fatal(err) + } + session := filepath.Join(sessions, "one.jsonl") + if err := os.WriteFile(session, []byte("{\"a\":1}\n"), 0o600); err != nil { + t.Fatal(err) + } + dir := t.TempDir() + cfg := "package archive\nhosts: testhost: {\n\tstate: \"measured\"\n\tsources: [{name: \"s\", path: \"sessions\"}]\n\twatch: []\n\texclude: []\n\tfinalOnly: []\n}\n" + if err := os.WriteFile(filepath.Join(dir, "archive.cue"), []byte(cfg), 0o600); err != nil { + t.Fatal(err) + } + real, err := exec.LookPath("restic") + if err != nil { + t.Fatalf("restic must be on PATH: %v", err) + } + calls := filepath.Join(dir, "calls") + wrapper := filepath.Join(dir, "restic-wrapper") + // The wrapper logs argv and each --include-file list, so tests see exactly which files a restore fetched. + body := "#!/bin/sh\necho \"$@\" >> '" + calls + "'\nprev=\nfor a in \"$@\"; do\n if [ \"$prev\" = --include-file ]; then sed 's/^/include /' \"$a\" >> '" + calls + "'; fi\n prev=$a\ndone\nexec '" + real + "' \"$@\"\n" + if err := os.WriteFile(wrapper, []byte(body), 0o700); err != nil { + t.Fatal(err) + } + identity, err := age.GenerateX25519Identity() + if err != nil { + t.Fatal(err) + } + opts := passOptions{ + host: "testhost", configPath: filepath.Join(dir, "archive.cue"), stateDir: filepath.Join(dir, "state", "testhost"), + repo: filepath.Join(dir, "repo"), escrowOut: filepath.Join(dir, "escrow", "testhost.age"), + escrowRecipient: identity.Recipient().String(), restic: wrapper, + } + return passFixture{opts: opts, identity: identity, session: session, calls: calls} +} + +func decryptEscrow(t *testing.T, f passFixture) []byte { + t.Helper() + data, err := os.ReadFile(f.opts.escrowOut) + if err != nil { + t.Fatal(err) + } + reader, err := age.Decrypt(bytes.NewReader(data), f.identity) + if err != nil { + t.Fatal(err) + } + var plain bytes.Buffer + if _, err := plain.ReadFrom(reader); err != nil { + t.Fatal(err) + } + return plain.Bytes() +} + +func journalCount(t *testing.T, state, event string) int { + t.Helper() + data, err := os.ReadFile(filepath.Join(state, "journal.jsonl")) + if err != nil { + t.Fatal(err) + } + return strings.Count(string(data), `"event":"`+event+`"`) +} + +func TestPassFirstAndSecondRun(t *testing.T) { + f := newPassFixture(t) + t.Setenv("RESTIC_PASSWORD", "wrong-env-password") + t.Setenv("RESTIC_REPOSITORY", filepath.Join(t.TempDir(), "elsewhere")) + if err := runPass(t.Context(), f.opts); err != nil { + t.Fatalf("first pass: %v", err) + } + password, err := os.ReadFile(filepath.Join(f.opts.stateDir, "password")) + if err != nil { + t.Fatal(err) + } + if got := decryptEscrow(t, f); !bytes.Equal(got, password) { + t.Fatal("escrow does not decrypt to the state password") + } + escrowBefore, err := os.Stat(f.opts.escrowOut) + if err != nil { + t.Fatal(err) + } + if n := journalCount(t, f.opts.stateDir, "pass-acked"); n != 1 { + t.Fatalf("acked passes after first run = %d", n) + } + if err := os.WriteFile(f.session, []byte("{\"a\":1}\n{\"b\":2}\n"), 0o600); err != nil { + t.Fatal(err) + } + if err := runPass(t.Context(), f.opts); err != nil { + t.Fatalf("second pass: %v", err) + } + if n := journalCount(t, f.opts.stateDir, "pass-acked"); n != 2 { + t.Fatalf("acked passes after second run = %d", n) + } + escrowAfter, err := os.Stat(f.opts.escrowOut) + if err != nil { + t.Fatal(err) + } + if !os.SameFile(escrowBefore, escrowAfter) || !escrowAfter.ModTime().Equal(escrowBefore.ModTime()) { + t.Fatal("escrow rewritten on second run") + } + calls, err := os.ReadFile(f.calls) + if err != nil { + t.Fatalf("--restic wrapper never called: %v", err) + } + if !strings.Contains(string(calls), " init") || strings.Count(string(calls), " backup") != 2 { + t.Fatalf("wrapper calls: %s", calls) + } + if _, err := os.Stat(filepath.Join(filepath.Dir(f.opts.repo), "elsewhere")); err == nil { + t.Fatal("RESTIC_REPOSITORY from env was honoured") + } + checkPassCoverage(t, f) +} + +func TestPassRefusesEscrowForOtherPassword(t *testing.T) { + f := newPassFixture(t) + if err := runPass(t.Context(), f.opts); err != nil { + t.Fatal(err) + } + before, err := os.ReadFile(f.opts.escrowOut) + if err != nil { + t.Fatal(err) + } + other := f.opts + other.stateDir = filepath.Join(t.TempDir(), "state", "testhost") + other.repo = filepath.Join(t.TempDir(), "repo") + if err := runPass(t.Context(), other); err == nil || !strings.Contains(err.Error(), "different password") { + t.Fatalf("second scope with same escrow-out = %v, want refusal", err) + } + after, err := os.ReadFile(f.opts.escrowOut) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(before, after) { + t.Fatal("escrow overwritten") + } + if _, err := os.Stat(other.repo); err == nil { + t.Fatal("repository initialized despite escrow refusal") + } +} + +// stateCoverage runs `coverage --state-dir` before a delete. +func stateCoverage(t *testing.T, f passFixture) (coverage.Report, error) { + t.Helper() + var out bytes.Buffer + command := newCoverageCmd() + command.SetOut(&out) + command.SetArgs([]string{"--state-dir", f.opts.stateDir, "--scope", f.opts.host, "--repo", f.opts.repo, "--restic", f.opts.restic}) + err := command.Execute() + var report coverage.Report + // On failure cobra appends usage after the report; decode the report only. + if jsonErr := json.NewDecoder(bytes.NewReader(out.Bytes())).Decode(&report); jsonErr != nil { + t.Fatalf("coverage output %q: %v (run error %v)", out.String(), jsonErr, err) + } + return report, err +} + +func checkPassCoverage(t *testing.T, f passFixture) { + t.Helper() + before := strings.Count(readString(t, f.calls), " restore") + strings.Count(readString(t, f.calls), "dump --no-lock --archive tar") + report, err := stateCoverage(t, f) + if err != nil || !report.Pass { + t.Fatalf("coverage --state-dir = %+v, %v", report, err) + } + if after := strings.Count(readString(t, f.calls), " restore") + strings.Count(readString(t, f.calls), "dump --no-lock --archive tar"); after <= before { + t.Fatal("coverage did not read the snapshot through the --restic binary") + } +} + +// restoredPaths returns the paths coverage asked restic to restore after offset bytes of the call log. +func restoredPaths(t *testing.T, f passFixture, offset int) []string { + t.Helper() + var paths []string + for line := range strings.Lines(readString(t, f.calls)[offset:]) { + if path, ok := strings.CutPrefix(strings.TrimSuffix(line, "\n"), "include "); ok { + paths = append(paths, path) + } + } + return paths +} + +// TestCoverageStateDirIncremental: a second check restores nothing; after a change only the changed file is restored. +func TestCoverageStateDirIncremental(t *testing.T) { + f := newPassFixture(t) + other := filepath.Join(filepath.Dir(f.session), "other.json") + // Large enough that one changed session stays under half the snapshot, so the include path runs. + if err := os.WriteFile(other, []byte(strings.Repeat("{\"o\":1}\n", 512)), 0o600); err != nil { + t.Fatal(err) + } + if err := runPass(t.Context(), f.opts); err != nil { + t.Fatal(err) + } + checkPassCoverage(t, f) + offset := len(readString(t, f.calls)) + if report, err := stateCoverage(t, f); err != nil || !report.Pass { + t.Fatalf("second coverage = %+v, %v", report, err) + } + if paths := restoredPaths(t, f, offset); len(paths) != 0 { + t.Fatalf("second coverage restored unchanged files %v", paths) + } + if err := os.WriteFile(f.session, []byte("{\"a\":1}\n{\"c\":3}\n"), 0o600); err != nil { + t.Fatal(err) + } + if err := runPass(t.Context(), f.opts); err != nil { + t.Fatal(err) + } + offset = len(readString(t, f.calls)) + checkPassCoverage(t, f) + if paths := restoredPaths(t, f, offset); !slices.Equal(paths, []string{f.session}) { + t.Fatalf("coverage after one change restored %v, want only %s", paths, f.session) + } +} + +// TestCoverageStateDirFirstRunStreams: when every file is unverified, coverage streams the snapshot once instead of include batches. +func TestCoverageStateDirFirstRunStreams(t *testing.T) { + f := newPassFixture(t) + // The snapshot also holds the pass's delta file; a real transcript outweighs it, as on a host. + if err := os.WriteFile(f.session, []byte(strings.Repeat("{\"a\":1}\n", 512)), 0o600); err != nil { + t.Fatal(err) + } + if err := runPass(t.Context(), f.opts); err != nil { + t.Fatal(err) + } + offset := len(readString(t, f.calls)) + if report, err := stateCoverage(t, f); err != nil || !report.Pass { + t.Fatalf("first coverage = %+v, %v", report, err) + } + calls := readString(t, f.calls)[offset:] + if !strings.Contains(calls, "dump --no-lock --archive tar") || strings.Contains(calls, " restore") { + t.Fatalf("first coverage did not stream the snapshot: %s", calls) + } +} + +// TestCoverageStateDirTornJournalTail: coverage skips a torn final journal line and leaves the journal untouched. +func TestCoverageStateDirTornJournalTail(t *testing.T) { + f := newPassFixture(t) + if err := runPass(t.Context(), f.opts); err != nil { + t.Fatal(err) + } + journal := filepath.Join(f.opts.stateDir, "journal.jsonl") + torn := readString(t, journal) + `{"event":"pass-ack` + if err := os.WriteFile(journal, []byte(torn), 0o600); err != nil { + t.Fatal(err) + } + if report, err := stateCoverage(t, f); err != nil || !report.Pass { + t.Fatalf("coverage with torn journal tail = %+v, %v", report, err) + } + if got := readString(t, journal); got != torn { + t.Fatal("coverage modified the journal") + } +} + +// TestCoverageStateDirPatternNames: on the include path, glob and $VAR names are escaped and a space-edged name is dumped. +func TestCoverageStateDirPatternNames(t *testing.T) { + f := newPassFixture(t) + dir := filepath.Dir(f.session) + // A large verified sibling keeps the new names under half the snapshot, so the include path runs. + if err := os.WriteFile(filepath.Join(dir, "other.json"), []byte(strings.Repeat("{\"o\":1}\n", 512)), 0o600); err != nil { + t.Fatal(err) + } + if err := runPass(t.Context(), f.opts); err != nil { + t.Fatal(err) + } + checkPassCoverage(t, f) + for _, name := range []string{"a[1].jsonl", "x$HOME.jsonl", "q*?.jsonl", "trail .jsonl "} { + if err := os.WriteFile(filepath.Join(dir, name), []byte(name+"\n"), 0o600); err != nil { + t.Fatal(err) + } + } + if err := runPass(t.Context(), f.opts); err != nil { + t.Fatal(err) + } + offset := len(readString(t, f.calls)) + if report, err := stateCoverage(t, f); err != nil || !report.Pass { + t.Fatalf("coverage with pattern-like names = %+v, %v", report, err) + } + paths := restoredPaths(t, f, offset) + slices.Sort(paths) + want := []string{dir + `/a\[1].jsonl`, dir + `/q\*\?.jsonl`, dir + `/x$$HOME.jsonl`} + slices.Sort(want) + if !slices.Equal(paths, want) { + t.Fatalf("include list = %q, want %q", paths, want) + } + dumped := false + for line := range strings.Lines(readString(t, f.calls)[offset:]) { + line = strings.TrimSuffix(line, "\n") + if strings.Contains(line, " dump --no-lock ") && !strings.Contains(line, "--archive") && strings.HasSuffix(line, " "+dir+"/trail .jsonl ") { + dumped = true + } + } + if !dumped { + t.Fatalf("no single-file dump for the space-edged name: %s", readString(t, f.calls)[offset:]) + } +} + +// TestCoverageStateDirCacheBoundToSnapshot: a cached proof must not certify a newer snapshot holding other bytes. +func TestCoverageStateDirCacheBoundToSnapshot(t *testing.T) { + f := newPassFixture(t) + if err := runPass(t.Context(), f.opts); err != nil { + t.Fatal(err) + } + checkPassCoverage(t, f) + original := readString(t, f.session) + planted := strings.Repeat("z", len(original)-1) + "\n" + if err := os.WriteFile(f.session, []byte(planted), 0o600); err != nil { + t.Fatal(err) + } + backup := exec.Command(f.opts.restic, "--repo", f.opts.repo, "--password-file", filepath.Join(f.opts.stateDir, "password"), "backup", "--host", f.opts.host, f.session) + if output, err := backup.CombinedOutput(); err != nil { + t.Fatalf("plant same-size snapshot: %v: %s", err, output) + } + plantAckedSnapshot(t, f) + if err := os.WriteFile(f.session, []byte(original), 0o600); err != nil { + t.Fatal(err) + } + report, err := stateCoverage(t, f) + if err == nil || report.Pass || !slices.Contains(report.HashMismatch, f.session) { + t.Fatalf("coverage with cache and planted bytes = %+v, %v", report, err) + } +} + +// TestPassFirstRunManyPendingBoundedJournal: 60k files all pending on the first pass keep every journal line small, and coverage still runs. +func TestPassFirstRunManyPendingBoundedJournal(t *testing.T) { + f := newPassFixture(t) + home, err := os.UserHomeDir() + if err != nil { + t.Fatal(err) + } + dir := filepath.Join(home, "sessions", "bulk") + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatal(err) + } + for i := range 60000 { + if err := os.WriteFile(filepath.Join(dir, fmt.Sprintf("file-with-a-long-enough-name-%05d.json", i)), []byte{byte(i)}, 0o600); err != nil { + t.Fatal(err) + } + } + if err := runPass(t.Context(), f.opts); err != nil { + t.Fatal(err) + } + journal, err := os.ReadFile(filepath.Join(f.opts.stateDir, "journal.jsonl")) + if err != nil { + t.Fatal(err) + } + for line := range bytes.SplitSeq(journal, []byte{'\n'}) { + if len(line) > 64*1024 { + t.Fatalf("journal line of %d bytes: %.120s", len(line), line) + } + } + if report, err := stateCoverage(t, f); err != nil || !report.Pass { + t.Fatalf("coverage after 60k-file first pass = %+v, %v", report.Missing[:min(3, len(report.Missing))], err) + } +} + +// TestCoverageStateDirDetectsArchivedMismatch swaps the archived bytes; coverage must hash the snapshot, not trust the inventory. +func TestCoverageStateDirDetectsArchivedMismatch(t *testing.T) { + f := newPassFixture(t) + if err := runPass(t.Context(), f.opts); err != nil { + t.Fatal(err) + } + original := readString(t, f.session) + if err := os.WriteFile(f.session, []byte("{\"x\":9}\n"), 0o600); err != nil { + t.Fatal(err) + } + backup := exec.Command(f.opts.restic, "--repo", f.opts.repo, "--password-file", filepath.Join(f.opts.stateDir, "password"), "backup", "--host", f.opts.host, f.session) + if output, err := backup.CombinedOutput(); err != nil { + t.Fatalf("plant mismatched snapshot: %v: %s", err, output) + } + // Tag-free snapshot is newest but not journaled; make the journal point at it as the acked pass. + plantAckedSnapshot(t, f) + if err := os.WriteFile(f.session, []byte(original), 0o600); err != nil { + t.Fatal(err) + } + report, err := stateCoverage(t, f) + if err == nil || report.Pass || !slices.Contains(report.HashMismatch, f.session) { + t.Fatalf("coverage with mismatched archived bytes = %+v, %v", report, err) + } +} + +// plantAckedSnapshot appends a pass-acked event naming the newest snapshot. +func plantAckedSnapshot(t *testing.T, f passFixture) { + t.Helper() + output, err := exec.Command(f.opts.restic, "--repo", f.opts.repo, "--password-file", filepath.Join(f.opts.stateDir, "password"), "snapshots", "--json", "latest").Output() + if err != nil { + t.Fatal(err) + } + var snapshots []struct { + ID string `json:"id"` + } + if err := json.Unmarshal(output, &snapshots); err != nil || len(snapshots) != 1 { + t.Fatalf("latest snapshot %s: %v", output, err) + } + journal, err := os.OpenFile(filepath.Join(f.opts.stateDir, "journal.jsonl"), os.O_APPEND|os.O_WRONLY, 0o600) + if err != nil { + t.Fatal(err) + } + if _, err := journal.WriteString(`{"event":"pass-acked","passId":"planted","snapshotId":"` + snapshots[0].ID + "\"}\n"); err != nil { + t.Fatal(err) + } + if err := journal.Close(); err != nil { + t.Fatal(err) + } +} + +func readString(t *testing.T, path string) string { + t.Helper() + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + return string(data) +} + +func TestPassRefusesStateUnderSourceRoot(t *testing.T) { + f := newPassFixture(t) + home, err := os.UserHomeDir() + if err != nil { + t.Fatal(err) + } + inside := f.opts + inside.stateDir = filepath.Join(home, "sessions", "state") + if err := runPass(t.Context(), inside); err == nil || !strings.Contains(err.Error(), "under source") { + t.Fatalf("state dir under a source root = %v, want refusal", err) + } + if _, err := os.Stat(inside.stateDir); err == nil { + t.Fatal("state dir created despite refusal") + } +} + +// A state dir reached through a symlink into a source root is refused (L1). +func TestPassRefusesSymlinkedStateUnderSourceRoot(t *testing.T) { + f := newPassFixture(t) + home, err := os.UserHomeDir() + if err != nil { + t.Fatal(err) + } + link := filepath.Join(t.TempDir(), "link") + if err := os.Symlink(filepath.Join(home, "sessions"), link); err != nil { + t.Fatal(err) + } + inside := f.opts + inside.stateDir = filepath.Join(link, "state") + if err := runPass(t.Context(), inside); err == nil || !strings.Contains(err.Error(), "under source") { + t.Fatalf("symlinked state dir under a source root = %v, want refusal", err) + } +} + +// A live holder of the state-dir lock stops a second pass (L3). +func TestPassRefusesLockedStateDir(t *testing.T) { + f := newPassFixture(t) + release, err := fence.Lock(t.Context(), f.opts.stateDir, time.Now()) + if err != nil { + t.Fatal(err) + } + defer func() { + if err := release(); err != nil { + t.Error(err) + } + }() + if err := runPass(t.Context(), f.opts); err == nil || !strings.Contains(err.Error(), "lock state directory") { + t.Fatalf("pass with a held state lock = %v, want refusal", err) + } +} diff --git a/tools/transcript-archive/cmd/transcript-archive/rawcap.go b/tools/transcript-archive/cmd/transcript-archive/rawcap.go new file mode 100644 index 000000000..b3714538a --- /dev/null +++ b/tools/transcript-archive/cmd/transcript-archive/rawcap.go @@ -0,0 +1,67 @@ +package main + +import ( + "bytes" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/rawcap" + "github.com/spf13/cobra" +) + +// resticExitNoRepo is restic's exit status when the repository does not exist yet. +const resticExitNoRepo = 10 + +func newRawCapCmd() *cobra.Command { + var repo, stateDir string + var capBytes uint64 + command := &cobra.Command{ + Use: "rawcap", + Short: "Refuse a pass when the repository holds at least the cap in raw bytes", + Args: cobra.NoArgs, + SilenceErrors: true, + SilenceUsage: true, + RunE: func(cmd *cobra.Command, _ []string) error { + return runRawCap(cmd, repo, stateDir, capBytes) + }, + } + flags := command.Flags() + flags.StringVar(&repo, "repo", "", "restic repository path or URL") + flags.StringVar(&stateDir, "state-dir", "", "pass state directory holding the repository password") + flags.Uint64Var(&capBytes, "cap-bytes", 0, "refuse when raw-data bytes are at or above this") + for _, name := range []string{"repo", "state-dir", "cap-bytes"} { + if err := command.MarkFlagRequired(name); err != nil { + return command + } + } + return command +} + +// runRawCap reads restic's raw-data size and returns rawcap's refusal as the command error. +// A first-ever run (no password yet, or no repository) holds 0 bytes; every other failure refuses. +func runRawCap(cmd *cobra.Command, repo, stateDir string, capBytes uint64) error { + passwordFile := filepath.Join(stateDir, "password") + if _, err := os.ReadFile(passwordFile); err != nil { //nolint:gosec // Password is in the operator-supplied state directory. + if os.IsNotExist(err) { + return nil + } + return fmt.Errorf("read password: %w", err) + } + restic, err := resticCommand(coverageOptions{repo: repo, passwordFile: passwordFile}, "stats", "--mode", "raw-data", "--json", "--no-lock") + if err != nil { + return err + } + var stdout bytes.Buffer + restic.Stdout = &stdout + if err := restic.Run(); err != nil { + var exit *exec.ExitError + if errors.As(err, &exit) && exit.ExitCode() == resticExitNoRepo { + return nil + } + return fmt.Errorf("restic stats: %w", err) + } + return rawcap.Check(stdout.Bytes(), capBytes) +} diff --git a/tools/transcript-archive/cmd/transcript-archive/rawcap_test.go b/tools/transcript-archive/cmd/transcript-archive/rawcap_test.go new file mode 100644 index 000000000..97a6b239e --- /dev/null +++ b/tools/transcript-archive/cmd/transcript-archive/rawcap_test.go @@ -0,0 +1,120 @@ +package main + +import ( + "errors" + "os" + "path/filepath" + "strconv" + "testing" + + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/rawcap" +) + +const fakeRepo = "s3:fake/repo" + +func TestRootCommandRegistersRawCap(t *testing.T) { + command, _, err := newRootCmd().Find([]string{"rawcap"}) + if err != nil { + t.Fatal(err) + } + if command.Name() != "rawcap" { + t.Fatalf("command = %q, want rawcap", command.Name()) + } + for _, flag := range []string{"repo", "state-dir", "cap-bytes"} { + if command.Flags().Lookup(flag) == nil { + t.Fatalf("rawcap command is missing --%s", flag) + } + } +} + +// installFakeRestic puts a restic on PATH that checks its argv, then prints stats JSON and exits with code. +func installFakeRestic(t *testing.T, statsJSON string, code int) { + t.Helper() + binDir := t.TempDir() + script := "#!/bin/sh\n" + + "case \" $* \" in *' --repo " + fakeRepo + " '*) ;; *) echo missing repo >&2; exit 99;; esac\n" + + "case \" $* \" in *' --password-file password '*) ;; *) echo missing password-file >&2; exit 99;; esac\n" + + "printf '%s' '" + statsJSON + "'\n" + + "exit " + strconv.Itoa(code) + "\n" + if err := os.WriteFile(filepath.Join(binDir, "restic"), []byte(script), 0o700); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH")) +} + +// stateDirWithPassword returns a state dir holding a password file. +func stateDirWithPassword(t *testing.T) string { + t.Helper() + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "password"), []byte("secret\n"), 0o600); err != nil { + t.Fatal(err) + } + return dir +} + +func runRawCapArgs(stateDir string) error { + command := newRootCmd() + command.SetArgs([]string{"rawcap", "--repo", fakeRepo, "--state-dir", stateDir, "--cap-bytes", "100"}) + return command.Execute() +} + +func TestRawCapCommandRefusesAtAndOverCap(t *testing.T) { + cases := []struct { + name string + stats string + wantOver bool + }{ + {name: "under cap passes", stats: `{"total_size": 99}`}, + {name: "at cap refuses", stats: `{"total_size": 100}`, wantOver: true}, + {name: "over cap refuses", stats: `{"total_size": 101}`, wantOver: true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + installFakeRestic(t, tc.stats, 0) + err := runRawCapArgs(stateDirWithPassword(t)) + if tc.wantOver { + if !errors.Is(err, rawcap.ErrOverCap) { + t.Fatalf("Execute() error = %v, want ErrOverCap", err) + } + return + } + if err != nil { + t.Fatalf("Execute() error = %v, want nil", err) + } + }) + } +} + +func TestRawCapFirstRunPasses(t *testing.T) { + t.Run("restic exit 10 passes", func(t *testing.T) { + installFakeRestic(t, "", 10) + if err := runRawCapArgs(stateDirWithPassword(t)); err != nil { + t.Fatalf("Execute() error = %v, want nil", err) + } + }) + t.Run("missing password file passes", func(t *testing.T) { + installFakeRestic(t, "", 1) + if err := runRawCapArgs(t.TempDir()); err != nil { + t.Fatalf("Execute() error = %v, want nil", err) + } + }) +} + +func TestRawCapFailsClosed(t *testing.T) { + t.Run("other restic failure refuses", func(t *testing.T) { + installFakeRestic(t, "", 1) + if err := runRawCapArgs(stateDirWithPassword(t)); err == nil { + t.Fatal("Execute() error = nil, want restic failure") + } + }) + t.Run("unreadable password refuses", func(t *testing.T) { + installFakeRestic(t, `{"total_size": 1}`, 0) + dir := t.TempDir() + if err := os.Mkdir(filepath.Join(dir, "password"), 0o700); err != nil { + t.Fatal(err) + } + if err := runRawCapArgs(dir); err == nil { + t.Fatal("Execute() error = nil, want password read failure") + } + }) +} diff --git a/tools/transcript-archive/cmd/transcript-archive/required_flags_test.go b/tools/transcript-archive/cmd/transcript-archive/required_flags_test.go new file mode 100644 index 000000000..804c92319 --- /dev/null +++ b/tools/transcript-archive/cmd/transcript-archive/required_flags_test.go @@ -0,0 +1,76 @@ +package main + +import ( + "path/filepath" + "strings" + "testing" + + "filippo.io/age" +) + +// TestPassRequiresConfigAndEscrowRecipient checks that pass refuses to run when a +// deployment input is missing. Nothing is baked in, so each case must fail before +// the state directory or repository is touched. +func TestPassRequiresConfigAndEscrowRecipient(t *testing.T) { + t.Parallel() + identity, err := age.GenerateX25519Identity() + if err != nil { + t.Fatal(err) + } + recipient := identity.Recipient().String() + base := []string{ + "--host", "example-host", + "--state-dir", filepath.Join(t.TempDir(), "state"), + "--repo", filepath.Join(t.TempDir(), "repo"), + "--escrow-out", filepath.Join(t.TempDir(), "escrow.age"), + } + tests := []struct { + name string + args []string + missingFlag string + }{ + { + name: "missing config", + args: append([]string{"--escrow-recipient", recipient}, base...), + missingFlag: "config", + }, + { + name: "missing escrow recipient", + args: append([]string{"--config", fixtureConfig}, base...), + missingFlag: "escrow-recipient", + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + command := newPassCmd() + command.SilenceUsage = true + command.SilenceErrors = true + command.SetArgs(test.args) + runErr := command.ExecuteContext(t.Context()) + if runErr == nil { + t.Fatalf("pass accepted %s", test.name) + } + msg := runErr.Error() + if !strings.HasPrefix(msg, "pass requires ") || !strings.Contains(msg, test.missingFlag) { + t.Fatalf("pass error = %q, want the required-flag error naming %s", msg, test.missingFlag) + } + }) + } +} + +// TestPassRequiredFlagsHaveNoDefault pins the empty defaults: a default would +// let pass start without the input that the required-flag check demands. +func TestPassRequiredFlagsHaveNoDefault(t *testing.T) { + t.Parallel() + command := newPassCmd() + for _, name := range []string{"config", "escrow-recipient"} { + flag := command.Flags().Lookup(name) + if flag == nil { + t.Fatalf("pass has no --%s flag", name) + } + if flag.DefValue != "" { + t.Fatalf("--%s default = %q, want empty", name, flag.DefValue) + } + } +} diff --git a/tools/transcript-archive/component.cue b/tools/transcript-archive/component.cue new file mode 100644 index 000000000..04449ac5c --- /dev/null +++ b/tools/transcript-archive/component.cue @@ -0,0 +1,11 @@ +id: "transcript-archive" +release: { + base: "0.1.0" + artifacts: { + "transcript-archive": { + kind: "binary" + package: "local:transcript-archive" + binaries: ["transcript-archive"] + } + } +} diff --git a/tools/transcript-archive/go.mod b/tools/transcript-archive/go.mod new file mode 100644 index 000000000..e6626f22b --- /dev/null +++ b/tools/transcript-archive/go.mod @@ -0,0 +1,28 @@ +module github.com/RigelBuild/nebula/tools/transcript-archive + +go 1.27.0 + +require ( + cuelang.org/go v0.17.1 + filippo.io/age v1.3.2 + github.com/oklog/ulid/v2 v2.1.2 + github.com/spf13/cobra v1.10.2 +) + +require ( + filippo.io/hpke v0.4.0 // indirect + github.com/cockroachdb/apd/v3 v3.2.3 // indirect + github.com/emicklei/proto v1.14.3 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/mitchellh/go-wordwrap v1.0.1 // indirect + github.com/pelletier/go-toml/v2 v2.3.1 // indirect + github.com/protocolbuffers/txtpbfmt v0.0.0-20260420112717-c39628bde8b5 // indirect + github.com/spf13/pflag v1.0.10 // indirect + go.yaml.in/yaml/v3 v3.0.4 // indirect + golang.org/x/crypto v0.55.0 // indirect + golang.org/x/net v0.57.0 // indirect + golang.org/x/sys v0.47.0 // indirect + golang.org/x/text v0.41.0 // indirect + google.golang.org/protobuf v1.33.0 // indirect +) diff --git a/tools/transcript-archive/go.sum b/tools/transcript-archive/go.sum new file mode 100644 index 000000000..39d8119d1 --- /dev/null +++ b/tools/transcript-archive/go.sum @@ -0,0 +1,77 @@ +c2sp.org/CCTV/age v0.0.0-20260829155415-4448f2097b2d h1:Blprhc2SbChNZtWcU+BLTM4YdoqYAS9V7cJgOwJKyAs= +c2sp.org/CCTV/age v0.0.0-20260829155415-4448f2097b2d/go.mod h1:SrHC2C7r5GkDk8R+NFVzYy/sdj0Ypg9htaPXQq5Cqeo= +cuelabs.dev/go/oci/ociregistry v0.0.0-20260601085548-328ff8e2c943 h1:XUtzi/yWlmuy8V6kkmVbbmirmUqcFe9Ce3gmEaHXf1Q= +cuelabs.dev/go/oci/ociregistry v0.0.0-20260601085548-328ff8e2c943/go.mod h1:WjmQxb+W6nVNCgj8nXrF24lIz95AHwnSl36tpjDZSU8= +cuelang.org/go v0.17.1 h1:liOkxZDqTHrzq0USJX+6bMYOZ5PSf+wzvQr15AHpDCQ= +cuelang.org/go v0.17.1/go.mod h1:xlly/o1wSLvxOsi5vkQGieU0rLOt7TvUIizOFtnxHRU= +filippo.io/age v1.3.2 h1:r6RSZLFSMm6rzKepZ7ZAYkKCu14f3/Me8c7uKYh7C8c= +filippo.io/age v1.3.2/go.mod h1:TH/Yr2sSRhCKbaH4XPxpUV0Us8Gv6txYUpiZQWz8Evk= +filippo.io/hpke v0.4.0 h1:p575VVQ6ted4pL+it6M00V/f2qTZITO0zgmdKCkd5+A= +filippo.io/hpke v0.4.0/go.mod h1:EmAN849/P3qdeK+PCMkDpDm83vRHM5cDipBJ8xbQLVY= +github.com/cockroachdb/apd/v3 v3.2.3 h1:4Zx+I3R35bFXMnltzmjP79i2cravE4jTRL6ps9Aux80= +github.com/cockroachdb/apd/v3 v3.2.3/go.mod h1:klXJcjp+FffLTHlhIG69tezTDvdP065naDsHzKhYSqc= +github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= +github.com/emicklei/proto v1.14.3 h1:zEhlzNkpP8kN6utonKMzlPfIvy82t5Kb9mufaJxSe1Q= +github.com/emicklei/proto v1.14.3/go.mod h1:rn1FgRS/FANiZdD2djyH7TMA9jdRDcYQ9IEN9yvjX0A= +github.com/go-quicktest/qt v1.102.0 h1:HSQxCeh5YZH3EL3W39ixjtyaEhcWSXQHtHnMBzSs474= +github.com/go-quicktest/qt v1.102.0/go.mod h1:p4lGIVX+8Wa6ZPNDvqcxq36XpUDLh42FLetFU7odllI= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/lib/pq v1.10.7 h1:p7ZhMD+KsSRozJr34udlUrhboJwWAgCg34+/ZZNvZZw= +github.com/lib/pq v1.10.7/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0= +github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0= +github.com/oklog/ulid/v2 v2.1.2 h1:IEclFb9JNvzYA6MW2SCxbLzcHTVsfqm3PrqGQJH5zec= +github.com/oklog/ulid/v2 v2.1.2/go.mod h1:rcEKHmBBKfef9DhnvX7y1HZBYxjXb0cP5ExxNsTT1QQ= +github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= +github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= +github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040= +github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M= +github.com/pborman/getopt v0.0.0-20170112200414-7148bc3a4c30/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o= +github.com/pelletier/go-toml/v2 v2.3.1 h1:MYEvvGnQjeNkRF1qUuGolNtNExTDwct51yp7olPtrEc= +github.com/pelletier/go-toml/v2 v2.3.1/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= +github.com/protocolbuffers/txtpbfmt v0.0.0-20260420112717-c39628bde8b5 h1:Mckui8l+Wqz2Ve7XQvsE8SbHNmDWu8NA7Xce5NFJ/kM= +github.com/protocolbuffers/txtpbfmt v0.0.0-20260420112717-c39628bde8b5/go.mod h1:JSbkp0BviKovYYt9XunS95M3mLPibE9bGg+Y95DsEEY= +github.com/rogpeppe/go-internal v1.16.0 h1:O9DK+vNMDVGLr2BeZqmpLeMjiMNkuXfcqntWbZV6S5g= +github.com/rogpeppe/go-internal v1.16.0/go.mod h1:DrUVZyrJU+txYW5/1kwtXQSMFio52ZOxX7yM1VHvnxs= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= +github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= +github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= +github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M= +golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis= +golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk= +golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40= +golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE= +golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU= +golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= +golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= +golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= +golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= +golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0= +golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w= +golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8= +golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M= +golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI= +golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo= +google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI= +google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/tools/transcript-archive/internal/client/client.go b/tools/transcript-archive/internal/client/client.go new file mode 100644 index 000000000..fd8a95e4b --- /dev/null +++ b/tools/transcript-archive/internal/client/client.go @@ -0,0 +1,280 @@ +package client + +import ( + "context" + "crypto/rand" + "encoding/hex" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "sync" + "time" + + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/inventory" + "github.com/oklog/ulid/v2" +) + +var ErrInitBroken = errors.New("client: repository init is broken") + +var ErrNoScan = errors.New("client: no scan exists") + +// ErrPassDone reports that the current scan has already been passed. +var ErrPassDone = errors.New("client: scan already passed") + +// ErrReadOnly reports a write attempted on a client opened with OpenReadOnly. +var ErrReadOnly = errors.New("client: read-only client cannot write") + +// RepoRef identifies a transcript scope and the restic repository that stores it. +type RepoRef struct { + Scope string + Repository string +} + +// Escrower stores the scope password before repository initialization. +type Escrower interface { + Put(ctx context.Context, scope string, body []byte) (sha256 [32]byte, err error) +} + +// OutcomeKind is the durable result of one pass. +type OutcomeKind uint8 + +const ( + Acked OutcomeKind = iota + Incomplete + Failed + Stored + Abandoned +) + +// Outcome reports the result of a restic pass or recovery check. +type Outcome struct { + Kind OutcomeKind + PassID string + SnapshotID string + ScanStartedAt time.Time + ExitCode int + FilesUnmodified int + Vanished []string +} + +// Option configures chained lifecycle behavior. +type Option func(*Client) + +// WithBaseline marks the predecessor inventory for a chained scope. +func WithBaseline(baseline *inventory.Inventory) Option { + return func(c *Client) { + if baseline == nil { + c.baseline = nil + return + } + baselineCopy := *baseline + baselineCopy.Lines = append([]inventory.Line(nil), baseline.Lines...) + c.baseline = &baselineCopy + } +} + +// WithChained tells scans that matching baseline content is already covered. +func WithChained(chained bool) Option { + return func(c *Client) { c.chained = chained } +} + +// WithClock sets the clock used to timestamp scans and passes. +func WithClock(now func() time.Time) Option { + return func(c *Client) { c.now = now } +} + +// WithScratch sets the directory used for restic temporary files. +func WithScratch(dir string) Option { + return func(c *Client) { c.scratch = dir } +} + +// WithRestic sets the restic binary; the default resolves "restic" on PATH. +func WithRestic(path string) Option { + return func(c *Client) { c.restic = path } +} + +type pendingEntry struct { + line inventory.Line + at time.Time +} + +// Client owns one scope's durable transcript archive state. +type Client struct { + mu sync.Mutex + stateDir string + readOnly bool + scratch string + restic string + repo RepoRef + escrow Escrower + password []byte + baseline *inventory.Inventory + chained bool + now func() time.Time + initialized bool + newestDelta string + scanID string + scanStarted time.Time + lastPass ulid.ULID + committed map[string]bool + scanHook func(string) error + escrowed bool + pending map[string]pendingEntry + scanned map[string]inventory.Line + acked map[string]inventory.Line + passes map[string]journalEvent + outcomes map[string]bool +} + +// newClient builds the in-memory state shared by Open and OpenReadOnly. +func newClient(stateDir string, repo RepoRef, escrow Escrower, options ...Option) *Client { + c := &Client{ + stateDir: stateDir, + repo: repo, + escrow: escrow, + now: time.Now, + restic: "restic", + pending: make(map[string]pendingEntry), + scanned: make(map[string]inventory.Line), + acked: make(map[string]inventory.Line), + passes: make(map[string]journalEvent), + committed: make(map[string]bool), + outcomes: make(map[string]bool), + } + for _, option := range options { + if option != nil { + option(c) + } + } + return c +} + +// OpenReadOnly resumes one scope's state and never creates, chmods or removes anything in stateDir. +// A missing password, journal or scan-state.json reads as empty; write methods return ErrReadOnly. +func OpenReadOnly(stateDir string, repo RepoRef, options ...Option) (*Client, error) { + if strings.TrimSpace(stateDir) == "" || strings.TrimSpace(repo.Scope) == "" || strings.TrimSpace(repo.Repository) == "" { + return nil, errors.New("client: state directory, scope and repository are required") + } + if _, err := os.Stat(stateDir); err != nil { + return nil, fmt.Errorf("client: read state directory: %w", withoutPath(err)) + } + c := newClient(stateDir, repo, nil, options...) + c.readOnly = true + if err := c.replayDeltas(); err != nil { + return nil, err + } + if err := c.openJournal(); err != nil { + return nil, err + } + password, err := os.ReadFile(filepath.Join(stateDir, "password")) //nolint:gosec // Password is in the private state directory. + if err != nil && !errors.Is(err, os.ErrNotExist) { + return nil, fmt.Errorf("client: read password: %w", withoutPath(err)) + } + if err == nil { + if err := checkPassword(password); err != nil { + return nil, err + } + c.password = password + } + return c, nil +} + +// checkPassword requires the 64 lowercase hex characters that Open writes. +func checkPassword(password []byte) error { + if len(password) != 64 || strings.Trim(string(password), "0123456789abcdef") != "" { + return errors.New("client: existing password is not 64 lowercase hex characters") + } + return nil +} + +// Open creates or resumes the state for one scope and writes its password once. +func Open(stateDir string, repo RepoRef, escrow Escrower, options ...Option) (*Client, error) { + if strings.TrimSpace(stateDir) == "" || strings.TrimSpace(repo.Scope) == "" || strings.TrimSpace(repo.Repository) == "" { + return nil, errors.New("client: state directory, scope and repository are required") + } + if escrow == nil { + return nil, errors.New("client: escrow is required") + } + if err := os.MkdirAll(stateDir, 0o700); err != nil { //nolint:gosec // operator supplies the private state directory + return nil, fmt.Errorf("client: create state directory: %w", withoutPath(err)) + } + if err := os.Chmod(stateDir, 0o700); err != nil { //nolint:gosec // directory execute permission is required for traversal + return nil, fmt.Errorf("client: protect state directory: %w", withoutPath(err)) + } + c := newClient(stateDir, repo, escrow, options...) + if strings.TrimSpace(c.scratch) == "" { + return nil, errors.New("client: scratch directory is required") + } + if err := os.MkdirAll(c.scratch, 0o700); err != nil { + return nil, fmt.Errorf("client: create scratch directory: %w", withoutPath(err)) + } + if err := os.Chmod(c.scratch, 0o700); err != nil { //nolint:gosec // Directory traversal requires execute permission. + return nil, fmt.Errorf("client: protect scratch directory: %w", withoutPath(err)) + } + if err := c.replayDeltas(); err != nil { + return nil, err + } + if err := c.openJournal(); err != nil { + return nil, err + } + password, err := c.readOrCreatePassword() + if err != nil { + return nil, err + } + c.password = password + return c, nil +} +func (c *Client) readOrCreatePassword() (result []byte, resultErr error) { + path := filepath.Join(c.stateDir, "password") + password, err := os.ReadFile(path) //nolint:gosec // Password is in the private state directory. + if err == nil { + if err := checkPassword(password); err != nil { + return nil, err + } + return password, nil + } + if !errors.Is(err, os.ErrNotExist) { + return nil, fmt.Errorf("client: read password: %w", withoutPath(err)) + } + random := make([]byte, 32) + if _, err := rand.Read(random); err != nil { + return nil, fmt.Errorf("client: generate password: %w", err) + } + password = []byte(hex.EncodeToString(random)) + + file, err := os.CreateTemp(c.stateDir, ".password-*") + if err != nil { + return nil, fmt.Errorf("client: create password: %w", withoutPath(err)) + } + defer func() { + if err := os.Remove(file.Name()); err != nil && !errors.Is(err, os.ErrNotExist) { //nolint:gosec // G703: file.Name() is the temp file this call just created in the operator-configured stateDir. + resultErr = errors.Join(resultErr, fmt.Errorf("client: remove temporary password: %w", withoutPath(err))) + } + }() + if _, err := file.Write(password); err != nil { + closeErr := file.Close() + return nil, errors.Join(fmt.Errorf("client: write password: %w", withoutPath(err)), withoutPath(closeErr)) + } + if err := file.Sync(); err != nil { + closeErr := file.Close() + return nil, errors.Join(fmt.Errorf("client: sync password: %w", withoutPath(err)), withoutPath(closeErr)) + } + if err := file.Close(); err != nil { + return nil, fmt.Errorf("client: close password: %w", withoutPath(err)) + } + if err := os.Link(file.Name(), path); err != nil { + if errors.Is(err, os.ErrExist) { + return c.readOrCreatePassword() + } + return nil, fmt.Errorf("client: install password: %w", withoutPath(err)) + } + if err := syncDir(c.stateDir); err != nil { + return nil, err + } + if err := c.appendEvent(journalEvent{Event: "password-created", At: time.Now().UTC()}); err != nil { + return nil, err + } + return password, nil +} diff --git a/tools/transcript-archive/internal/client/client_test.go b/tools/transcript-archive/internal/client/client_test.go new file mode 100644 index 000000000..321a4fbaf --- /dev/null +++ b/tools/transcript-archive/internal/client/client_test.go @@ -0,0 +1,348 @@ +package client + +import ( + "context" + "crypto/sha256" + "errors" + "os" + "os/exec" + "path/filepath" + "regexp" + "strings" + "testing" + + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/inventory" +) + +type fakeEscrow struct { + body []byte +} + +func (f *fakeEscrow) Put(_ context.Context, _ string, body []byte) ([32]byte, error) { + f.body = append([]byte(nil), body...) + return sha256.Sum256(body), nil +} + +func openTestClient(t *testing.T, repo string, options ...Option) (*Client, *fakeEscrow, string) { + t.Helper() + root := t.TempDir() + state := filepath.Join(root, "state") + escrow := &fakeEscrow{} + options = append([]Option{WithScratch(filepath.Join(root, "scratch"))}, options...) + client, err := Open(state, RepoRef{Scope: "k3s-test-one", Repository: repo}, escrow, options...) + if err != nil { + t.Fatal(err) + } + return client, escrow, state +} + +func localRestic(t *testing.T) { + t.Helper() + if _, err := exec.LookPath("restic"); err != nil { + t.Fatalf("restic must be on PATH: %v", err) + } + output, err := exec.Command("restic", "version").Output() + if err != nil { + t.Fatalf("read restic version: %v", err) + } + if !strings.Contains(string(output), "0.19.1") { + t.Fatalf("restic version = %q, want pinned 0.19.1", output) + } +} + +func TestOpenCreatesEscrowedPassword(t *testing.T) { + localRestic(t) + repo := filepath.Join(t.TempDir(), "repo") + client, escrow, state := openTestClient(t, repo) + password, err := os.ReadFile(filepath.Join(state, "password")) + if err != nil { + t.Fatal(err) + } + if len(password) != 64 || regexp.MustCompile(`[^0-9a-f]`).Match(password) { + t.Fatalf("password format = %q", password) + } + info, err := os.Stat(filepath.Join(state, "password")) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm() != 0o600 { + t.Fatalf("password mode = %o, want 600", info.Mode().Perm()) + } + if len(escrow.body) != 0 { + t.Fatal("Open called escrow") + } + if _, err := os.Stat(repo); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("Open touched repository: %v", err) + } + if err := client.Recover(t.Context()); err != nil { + t.Fatal(err) + } + journal, err := os.ReadFile(filepath.Join(state, "journal.jsonl")) + if err != nil { + t.Fatal(err) + } + escrowIndex := strings.Index(string(journal), `"event":"escrowed"`) + initIndex := strings.Index(string(journal), `"event":"init"`) + if escrowIndex < 0 || initIndex <= escrowIndex { + t.Fatalf("escrow and init journal order: %s", journal) + } + if string(escrow.body) != string(password) { + t.Fatal("escrow received different password bytes") + } +} + +func TestPassAckChangedBytesAndEmptyDelta(t *testing.T) { + localRestic(t) + repo := filepath.Join(t.TempDir(), "repo") + client, _, _ := openTestClient(t, repo) + file := filepath.Join(t.TempDir(), "session.jsonl") + if err := os.WriteFile(file, []byte("first"), 0o600); err != nil { + t.Fatal(err) + } + line := inventory.Line{Path: file, Type: "file", Size: 5, SHA256: sha256.Sum256([]byte("first"))} + if err := client.Scan(t.Context(), inventory.Inventory{Lines: []inventory.Line{line}}, inventory.Delta{Added: []inventory.Line{line}}); err != nil { + t.Fatal(err) + } + first, err := client.Pass(t.Context(), []string{file}, nil) + if err != nil || first.Kind != Acked || first.SnapshotID == "" { + t.Fatalf("first pass = %#v, %v", first, err) + } + if err := os.WriteFile(file, []byte("second version"), 0o600); err != nil { + t.Fatal(err) + } + changed := inventory.Line{Path: file, Type: "file", Size: 14, SHA256: sha256.Sum256([]byte("second version"))} + if err := client.Scan(t.Context(), inventory.Inventory{Lines: []inventory.Line{changed}}, inventory.Delta{Changed: []inventory.Line{changed}}); err != nil { + t.Fatal(err) + } + second, err := client.Pass(t.Context(), []string{file}, nil) + if err != nil || second.Kind != Acked || second.SnapshotID == "" { + t.Fatalf("second pass = %#v, %v", second, err) + } + if err := client.Scan(t.Context(), inventory.Inventory{Lines: []inventory.Line{changed}}, inventory.Delta{}); err != nil { + t.Fatal(err) + } + oldest, bytes := client.Pending() + if !oldest.IsZero() || bytes != 0 { + t.Fatalf("pending after unchanged ack = %v/%d, want empty", oldest, bytes) + } +} + +func TestPassVanishedBeforePass(t *testing.T) { + localRestic(t) + client, _, state := openTestClient(t, filepath.Join(t.TempDir(), "repo")) + missing := filepath.Join(t.TempDir(), "gone.jsonl") + line := writeVersion(t, missing, "gone", "normal") + scanLines(t, client, line) + if err := os.Remove(missing); err != nil { + t.Fatal(err) + } + resticWrapper(t, `exec REAL_RESTIC "$@" 2>/dev/null`) + outcome, err := client.Pass(t.Context(), []string{missing}, nil) + if err != nil || outcome.Kind != Acked || len(outcome.Vanished) != 1 || outcome.Vanished[0] != missing { + t.Fatalf("pass = %#v, %v", outcome, err) + } + if !journalHas(t, state, "vanished", missing) { + t.Fatal("journal missing vanished path") + } + if oldest, size := client.Pending(); !oldest.IsZero() || size != 0 { + t.Fatalf("pending = %v/%d, want empty", oldest, size) + } +} + +func TestScanRevertClearsPending(t *testing.T) { + path := filepath.Join(t.TempDir(), "session.jsonl") + base := writeVersion(t, path, "base", "normal") + baseline := inventory.Inventory{Lines: []inventory.Line{base}} + client, _, _ := openTestClient(t, filepath.Join(t.TempDir(), "repo"), WithBaseline(&baseline), WithChained(true)) + changed := writeVersion(t, path, "other", "normal") + if err := client.Scan(t.Context(), inventory.Inventory{Lines: []inventory.Line{changed}}, inventory.Delta{Changed: []inventory.Line{changed}}); err != nil { + t.Fatal(err) + } + oldest, bytes := client.Pending() + if oldest.IsZero() || bytes != 5 { + t.Fatalf("pending changed baseline = %v/%d", oldest, bytes) + } + reverted := writeVersion(t, path, "base", "normal") + if err := client.Scan(t.Context(), inventory.Inventory{Lines: []inventory.Line{reverted}}, inventory.Delta{Changed: []inventory.Line{reverted}}); err != nil { + t.Fatal(err) + } + oldest, bytes = client.Pending() + if !oldest.IsZero() || bytes != 0 { + t.Fatalf("pending after baseline revert = %v/%d", oldest, bytes) + } +} + +func TestRecoverFindsStoredSnapshotWithoutAck(t *testing.T) { + localRestic(t) + repo := filepath.Join(t.TempDir(), "repo") + client, _, state := openTestClient(t, repo) + path := filepath.Join(t.TempDir(), "captured.jsonl") + if err := os.WriteFile(path, []byte("captured"), 0o600); err != nil { + t.Fatal(err) + } + line := inventory.Line{Path: path, Type: "file", Size: 8, SHA256: sha256.Sum256([]byte("captured"))} + if err := client.Scan(t.Context(), inventory.Inventory{Lines: []inventory.Line{line}}, inventory.Delta{Added: []inventory.Line{line}}); err != nil { + t.Fatal(err) + } + if _, err := client.Pass(t.Context(), []string{path}, nil); err != nil { + t.Fatal(err) + } + events, err := os.ReadFile(filepath.Join(state, "journal.jsonl")) + if err != nil { + t.Fatal(err) + } + lines := strings.Split(strings.TrimSpace(string(events)), "\n") + kept := make([]string, 0, len(lines)) + for _, line := range lines { + if strings.Contains(line, `"event":"pass-acked"`) { + continue + } + kept = append(kept, line) + } + if err := os.WriteFile(filepath.Join(state, "journal.jsonl"), []byte(strings.Join(kept, "\n")+"\n"), 0o600); err != nil { + t.Fatal(err) + } + recovered, err := Open(state, RepoRef{Scope: "k3s-test-one", Repository: repo}, &fakeEscrow{}, WithScratch(t.TempDir())) + if err != nil { + t.Fatal(err) + } + if err := recovered.Recover(t.Context()); err != nil { + t.Fatal(err) + } + journal, err := os.ReadFile(filepath.Join(state, "journal.jsonl")) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(journal), `"event":"pass-stored"`) { + t.Fatalf("journal lacks stored recovery result: %s", journal) + } + oldest, bytes := recovered.Pending() + if oldest.IsZero() || bytes == 0 { + t.Fatalf("stored recovery cleared pending: %v/%d", oldest, bytes) + } +} + +// TestOpenDropsTornJournalTail: a crash mid-append leaves a line with no newline; Open must drop it, not fail. +func TestOpenDropsTornJournalTail(t *testing.T) { + _, _, state := openTestClient(t, filepath.Join(t.TempDir(), "repo")) + journal := filepath.Join(state, "journal.jsonl") + before, err := os.ReadFile(journal) + if err != nil { + t.Fatal(err) + } + torn := append(append([]byte(nil), before...), []byte(`{"event":"path-acked","passId":"x","pa`)...) + if err := os.WriteFile(journal, torn, 0o600); err != nil { + t.Fatal(err) + } + if _, err := Open(state, RepoRef{Scope: "k3s-test-one", Repository: filepath.Join(t.TempDir(), "repo")}, &fakeEscrow{}, WithScratch(t.TempDir())); err != nil { + t.Fatalf("Open with torn tail: %v", err) + } + after, err := os.ReadFile(journal) + if err != nil || string(after) != string(before) { + t.Fatalf("torn tail not truncated: %q, %v", after, err) + } +} + +// TestOpenReadOnlySkipsTornJournalTail: read-only Open skips a torn final line and leaves the journal as it was. +func TestOpenReadOnlySkipsTornJournalTail(t *testing.T) { + _, _, state := openTestClient(t, filepath.Join(t.TempDir(), "repo")) + journal := filepath.Join(state, "journal.jsonl") + before, err := os.ReadFile(journal) + if err != nil { + t.Fatal(err) + } + torn := append(append([]byte(nil), before...), []byte(`{"event":"path-acked","passId":"x","pa`)...) + if err := os.WriteFile(journal, torn, 0o600); err != nil { + t.Fatal(err) + } + if _, err := OpenReadOnly(state, RepoRef{Scope: "k3s-test-one", Repository: filepath.Join(t.TempDir(), "repo")}); err != nil { + t.Fatalf("OpenReadOnly with torn tail: %v", err) + } + after, err := os.ReadFile(journal) + if err != nil || string(after) != string(torn) { + t.Fatalf("read-only open changed the journal: %q, %v", after, err) + } +} + +func TestInitBrokenForKeysWithoutConfig(t *testing.T) { + localRestic(t) + repo := filepath.Join(t.TempDir(), "repo") + client, _, _ := openTestClient(t, repo) + if _, err := client.runJSON(t.Context(), client.commonArgs("init", true)...); err != nil { + t.Fatal(err) + } + if err := os.Remove(filepath.Join(repo, "config")); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(client.stateDir, "journal.jsonl"), nil, 0o600); err != nil { + t.Fatal(err) + } + client.initialized = false + if err := client.ensureRepository(t.Context()); !errors.Is(err, ErrInitBroken) { + t.Fatalf("init error = %v, want ErrInitBroken", err) + } +} + +func TestPassContextCancellation(t *testing.T) { + localRestic(t) + client, _, _ := openTestClient(t, filepath.Join(t.TempDir(), "repo")) + ctx, cancel := context.WithCancel(t.Context()) + cancel() + if _, err := client.Pass(ctx, []string{"secret-path"}, nil); !errors.Is(err, context.Canceled) { + t.Fatalf("pass error = %v, want canceled", err) + } +} + +func TestPendingExcludesFinalOnlyDatabase(t *testing.T) { + client, _, _ := openTestClient(t, filepath.Join(t.TempDir(), "repo")) + line := inventory.Line{Path: "agent.db", Class: "final-only", Size: 12} + if err := client.Scan(t.Context(), inventory.Inventory{Lines: []inventory.Line{line}}, inventory.Delta{Added: []inventory.Line{line}}); err != nil { + t.Fatal(err) + } + oldest, bytes := client.Pending() + if !oldest.IsZero() || bytes != 0 { + t.Fatalf("final-only database entered pending: %v/%d", oldest, bytes) + } +} + +func TestSourceErrorsHidePaths(t *testing.T) { + path := filepath.Join(t.TempDir(), "secret-sentinel", "child") + if err := os.WriteFile(filepath.Dir(path), []byte("not a directory"), 0o600); err != nil { + t.Fatal(err) + } + _, err := statLine(path) + if err == nil || strings.Contains(err.Error(), "secret-sentinel") { + t.Fatalf("stat error leaks source path: %v", err) + } +} + +func TestResticRelativeArguments(t *testing.T) { + root := filepath.Join(t.TempDir(), "secret-sentinel") + c, err := Open(filepath.Join(root, "state"), RepoRef{Scope: "test", Repository: filepath.Join(t.TempDir(), "repo")}, &fakeEscrow{}, WithScratch(t.TempDir())) + if err != nil { + t.Fatal(err) + } + for _, arg := range c.commonArgs("backup", true) { + if strings.Contains(arg, "secret-sentinel") { + t.Fatalf("argv leaks state root: %s", arg) + } + } +} + +func TestScratchOption(t *testing.T) { + dir := filepath.Join(t.TempDir(), "scratch") + c, _, _ := openTestClient(t, filepath.Join(t.TempDir(), "repo"), WithScratch(dir)) + recorded := filepath.Join(t.TempDir(), "env") + resticWrapper(t, "printf '%s' \"$TMPDIR\" > "+recorded+"; exit 0") + if _, err := c.runJSON(t.Context(), "version"); err != nil { + t.Fatal(err) + } + data, err := os.ReadFile(recorded) + if err != nil || string(data) != dir { + t.Fatalf("restic TMPDIR = %q, %v; want %q", data, err, dir) + } + info, err := os.Stat(dir) + if err != nil || info.Mode().Perm() != 0o700 { + t.Fatalf("scratch mode: %v, %v", info, err) + } +} diff --git a/tools/transcript-archive/internal/client/helpers.go b/tools/transcript-archive/internal/client/helpers.go new file mode 100644 index 000000000..f6cb6f6d9 --- /dev/null +++ b/tools/transcript-archive/internal/client/helpers.go @@ -0,0 +1,112 @@ +package client + +import ( + "context" + "encoding/hex" + "errors" + "fmt" + "os" + "path/filepath" + "slices" + "strings" + "time" + + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/inventory" + "github.com/oklog/ulid/v2" +) + +func (c *Client) escrowPassword(ctx context.Context) error { + if c.escrowed { + return nil + } + if err := ctx.Err(); err != nil { + return err + } + digest, err := c.escrow.Put(ctx, c.repo.Scope, append([]byte(nil), c.password...)) + if err != nil { + return fmt.Errorf("client: escrow password: %w", err) + } + if err := c.appendEvent(journalEvent{Event: eventEscrowed, At: time.Now().UTC(), Digest: hex.EncodeToString(digest[:])}); err != nil { + return err + } + c.escrowed = true + return nil +} + +func (c *Client) privateList(name string, values []string) (string, error) { + path := filepath.Join(c.stateDir, name+"-"+ulid.Make().String()+".txt") + file, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600) //nolint:gosec // List name is generated inside the state directory. + if err != nil { + return "", fmt.Errorf("client: create private list: %w", withoutPath(err)) + } + for _, value := range values { + if value == "" || strings.ContainsAny(value, "\r\n") { + closeErr := file.Close() + removeErr := os.Remove(path) //nolint:gosec // path is built inside the client's own state directory. + return "", errors.Join(errors.New("client: invalid path in private list"), withoutPath(closeErr), withoutPath(removeErr)) + } + if _, err := file.WriteString(value + "\n"); err != nil { + closeErr := file.Close() + removeErr := os.Remove(path) //nolint:gosec // path is built inside the client's own state directory. + return "", errors.Join(fmt.Errorf("client: write private list: %w", withoutPath(err)), withoutPath(closeErr), withoutPath(removeErr)) + } + } + if err := file.Sync(); err != nil { + closeErr := file.Close() + removeErr := os.Remove(path) //nolint:gosec // path is built inside the client's own state directory. + return "", errors.Join(fmt.Errorf("client: sync private list: %w", withoutPath(err)), withoutPath(closeErr), withoutPath(removeErr)) + } + if err := file.Close(); err != nil { + removeErr := os.Remove(path) //nolint:gosec // List name is generated inside the state directory. + return "", errors.Join(fmt.Errorf("client: close private list: %w", withoutPath(err)), withoutPath(removeErr)) + } + return path, nil +} + +func removePrivateFile(path string) { + if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { //nolint:gosec // Removes the generated private list. + return + } +} + +func statLine(path string) (inventory.Line, error) { + info, err := os.Lstat(path) //nolint:gosec // Path is a source selected for the pass. + if err != nil { + return inventory.Line{}, fmt.Errorf("client: stat source file: %w", withoutPath(err)) + } + return inventory.Line{Path: path, Type: "file", Size: info.Size()}, nil +} + +func appendUnique(values []string, value string) []string { + if slices.Contains(values, value) { + return values + } + return append(values, value) +} + +// pendingIn returns the listed paths that are pending; pass-acked clears only these. +func (c *Client) pendingIn(list []string) []string { + pending := make([]string, 0, len(c.pending)) + for _, path := range list { + if _, ok := c.pending[pathKey(path)]; ok { + pending = append(pending, path) + } + } + return pending +} + +// ackPath moves one pending path to acked. Open drops a torn final line; lost path-acked lines leave paths pending for the next pass. +func (c *Client) ackPath(path string) { + key := pathKey(path) + if pending, ok := c.pending[key]; ok { + c.acked[key] = pending.line + delete(c.pending, key) + } +} + +func withoutPath(err error) error { + if pathErr, ok := errors.AsType[*os.PathError](err); ok { + return pathErr.Err + } + return err +} diff --git a/tools/transcript-archive/internal/client/journal.go b/tools/transcript-archive/internal/client/journal.go new file mode 100644 index 000000000..f36a21274 --- /dev/null +++ b/tools/transcript-archive/internal/client/journal.go @@ -0,0 +1,276 @@ +package client + +import ( + "bufio" + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "time" + + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/inventory" +) + +const ( + eventPending = "pending" + eventPendingCleared = "pending-cleared" + eventPassStart = "pass-start" + eventPassAcked = "pass-acked" + eventPassIncomplete = "pass-incomplete" + eventPassFailed = "pass-failed" + eventPassStored = "pass-stored" + eventPassAbandoned = "pass-abandoned" + eventVanished = "vanished" + eventEscrowed = "escrowed" + eventInit = "init" + // eventPathAcked follows pass-acked, one per pending path, so no journal line grows with the pass. + eventPathAcked = "path-acked" +) + +type journalEvent struct { + Event string `json:"event"` + At time.Time `json:"at,omitzero"` + ScanStartedAt time.Time `json:"scanStartedAt,omitzero"` + PassID string `json:"passId,omitempty"` + SnapshotID string `json:"snapshotId,omitempty"` + Path string `json:"path,omitempty"` + Paths []string `json:"paths,omitempty"` + Code int `json:"exitCode,omitempty"` + Digest string `json:"sha256,omitempty"` + Line *inventory.Line `json:"line,omitempty"` +} + +func (c *Client) openJournal() error { + flags := os.O_CREATE | os.O_RDWR + if c.readOnly { + flags = os.O_RDONLY + } + file, err := os.OpenFile(filepath.Join(c.stateDir, "journal.jsonl"), flags, 0o600) //nolint:gosec // G703: stateDir is the operator-configured state directory passed to Open, not request input. + if errors.Is(err, os.ErrNotExist) && c.readOnly { + return nil + } + if err != nil { + return fmt.Errorf("client: open journal: %w", withoutPath(err)) + } + if !c.readOnly { + if err := file.Chmod(0o600); err != nil { + closeErr := file.Close() + return errors.Join(fmt.Errorf("client: protect journal: %w", withoutPath(err)), withoutPath(closeErr)) + } + } + reader := bufio.NewReader(file) + var offset int64 + for { + line, readErr := reader.ReadBytes('\n') + // Every event ends in a newline, so a final line without one is a torn append: drop it (read-only: skip, never truncate). + if errors.Is(readErr, io.EOF) && len(line) > 0 { + if c.readOnly { + break + } + if err := file.Truncate(offset); err != nil { + return errors.Join(fmt.Errorf("client: truncate torn journal tail: %w", withoutPath(err)), withoutPath(file.Close())) + } + if err := file.Sync(); err != nil { + return errors.Join(fmt.Errorf("client: sync journal: %w", withoutPath(err)), withoutPath(file.Close())) + } + break + } + offset += int64(len(line)) + if len(line) > 0 { + var event journalEvent + if err := json.Unmarshal(bytes.TrimSpace(line), &event); err != nil { + closeErr := file.Close() + return errors.Join(fmt.Errorf("client: decode journal event: %w", withoutPath(err)), withoutPath(closeErr)) + } + c.observePassID(event.PassID) + if event.PassID != "" && (event.Event == eventPending || event.Event == eventPendingCleared || event.Event == eventVanished) && !c.committed[event.PassID] { + continue + } + c.applyEvent(event) + } + if errors.Is(readErr, io.EOF) { + break + } + if readErr != nil { + closeErr := file.Close() + return errors.Join(fmt.Errorf("client: read journal: %w", withoutPath(readErr)), withoutPath(closeErr)) + } + } + if _, err := file.Seek(0, io.SeekEnd); err != nil { + closeErr := file.Close() + return errors.Join(fmt.Errorf("client: seek journal: %w", withoutPath(err)), withoutPath(closeErr)) + } + if err := file.Close(); err != nil { + return fmt.Errorf("client: close journal: %w", withoutPath(err)) + } + return nil +} + +func (c *Client) appendEvent(event journalEvent) error { + return c.appendEvents([]journalEvent{event}) +} + +func (c *Client) appendEvents(events []journalEvent) error { + if err := c.writeEvents(events); err != nil { + return err + } + for _, event := range events { + c.applyEvent(event) + } + return nil +} + +func (c *Client) writeEvents(events []journalEvent) error { + if c.readOnly { + return ErrReadOnly + } + if len(events) == 0 { + return nil + } + var data bytes.Buffer + enc := json.NewEncoder(&data) + for _, event := range events { + if err := enc.Encode(event); err != nil { + return fmt.Errorf("client: encode journal event: %w", withoutPath(err)) + } + } + file, err := os.OpenFile(filepath.Join(c.stateDir, "journal.jsonl"), os.O_APPEND|os.O_WRONLY, 0o600) //nolint:gosec // Journal resides in the state directory. + if err != nil { + return fmt.Errorf("client: append journal: %w", withoutPath(err)) + } + if _, err := file.Write(data.Bytes()); err != nil { + closeErr := file.Close() + return errors.Join(fmt.Errorf("client: write journal: %w", withoutPath(err)), withoutPath(closeErr)) + } + if err := file.Sync(); err != nil { + closeErr := file.Close() + return errors.Join(fmt.Errorf("client: sync journal: %w", withoutPath(err)), withoutPath(closeErr)) + } + if err := file.Close(); err != nil { + return fmt.Errorf("client: close journal: %w", withoutPath(err)) + } + return nil +} + +func (c *Client) applyEvent(event journalEvent) { + switch event.Event { + case eventPending: + if event.Line != nil { + c.pending[pathKey(event.Line.Path)] = pendingEntry{line: *event.Line, at: event.At} + } + case eventPendingCleared: + delete(c.pending, pathKey(event.Path)) + case eventPassStart: + c.passes[event.PassID] = event + case eventPassAcked: + c.outcomes[event.PassID] = true + start := c.passes[event.PassID] + start.Event = event.Event + start.SnapshotID = event.SnapshotID + c.passes[event.PassID] = start + for _, path := range start.Paths { + c.ackPath(path) + } + start.Paths = nil + c.passes[event.PassID] = start + case eventPathAcked: + // Only a journaled pass-acked makes its path lines count. + if c.passes[event.PassID].Event == eventPassAcked { + c.ackPath(event.Path) + } + case eventPassIncomplete, eventPassFailed, eventPassStored, eventPassAbandoned: + c.outcomes[event.PassID] = true + start := c.passes[event.PassID] + start.Event = event.Event + start.SnapshotID = event.SnapshotID + c.passes[event.PassID] = start + case eventInit: + c.initialized = true + case eventEscrowed: + c.escrowed = true + case eventVanished: + delete(c.pending, pathKey(event.Path)) + } +} + +// Scan persists the current inventory and journals pending state transitions. +func (c *Client) Scan(ctx context.Context, now inventory.Inventory, delta inventory.Delta) error { + c.mu.Lock() + defer c.mu.Unlock() + if c.readOnly { + return ErrReadOnly + } + if err := ctx.Err(); err != nil { + return err + } + started := c.now().UTC() + events := make([]journalEvent, 0, len(delta.Removed)+len(delta.Added)+len(delta.Changed)) + for _, line := range delta.Removed { + if _, ok := c.pending[pathKey(line.Path)]; ok { + events = append(events, journalEvent{Event: eventVanished, Path: line.Path, At: started}) + } + } + scanned := make(map[string]inventory.Line, len(now.Lines)) + for _, line := range now.Lines { + scanned[pathKey(line.Path)] = line + if event, ok := c.scanTransition(line, started); ok { + events = append(events, event) + } + } + if err := c.persistScan(now, delta, events, scanned, started); err != nil { + return err + } + return nil +} + +func (c *Client) scanTransition(line inventory.Line, started time.Time) (journalEvent, bool) { + if line.Class == "final-only" || strings.HasSuffix(line.Path, ".db") || strings.HasSuffix(line.Path, ".db-wal") || strings.HasSuffix(line.Path, ".db-shm") { + return journalEvent{}, false + } + key := pathKey(line.Path) + pending, exists := c.pending[key] + old, acked := c.acked[key] + covered := c.chained && c.baseline != nil && baselineHas(c.baseline.Lines, line) + if covered || (acked && sameLineVersion(old, line)) { + return journalEvent{Event: eventPendingCleared, Path: line.Path, At: started}, exists + } + if exists && sameLineVersion(pending.line, line) { + return journalEvent{}, false + } + return journalEvent{Event: eventPending, Line: &line, At: started}, true +} + +func baselineHas(lines []inventory.Line, line inventory.Line) bool { + for _, old := range lines { + if old.Path == line.Path && old.Type == line.Type && old.Size == line.Size && old.SHA256 == line.SHA256 { + return true + } + } + return false +} + +func sameLineVersion(left, right inventory.Line) bool { + return left.Path == right.Path && left.Type == right.Type && left.Size == right.Size && left.SHA256 == right.SHA256 +} + +func pathKey(path string) string { return path } + +func syncDir(path string) error { + directory, err := os.Open(path) //nolint:gosec // Opens the state or delta directory for fsync. + if err != nil { + return fmt.Errorf("client: open state directory: %w", withoutPath(err)) + } + if err := directory.Sync(); err != nil { + closeErr := directory.Close() + return errors.Join(fmt.Errorf("client: sync state directory: %w", withoutPath(err)), withoutPath(closeErr)) + } + if err := directory.Close(); err != nil { + return fmt.Errorf("client: close state directory: %w", withoutPath(err)) + } + return nil +} diff --git a/tools/transcript-archive/internal/client/pass.go b/tools/transcript-archive/internal/client/pass.go new file mode 100644 index 000000000..2b35e8f5e --- /dev/null +++ b/tools/transcript-archive/internal/client/pass.go @@ -0,0 +1,434 @@ +package client + +import ( + "bufio" + "bytes" + "context" + "crypto/rand" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "os/exec" //nolint:depguard // restic runs directly, without a shell + "path/filepath" + "strings" + "time" + + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/inventory" + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/resticenv" + "github.com/oklog/ulid/v2" +) + +type resticMessage struct { + MessageType string `json:"message_type"` + ID string `json:"id"` + FilesUnmodified int `json:"files_unmodified"` +} + +type exitError interface { + ExitCode() int +} + +// Pass backs up the supplied paths and the current scan delta. Each scan permits one pass. +func (c *Client) Pass(ctx context.Context, files []string, tags []string) (Outcome, error) { + c.mu.Lock() + defer c.mu.Unlock() + if c.readOnly { + return Outcome{}, ErrReadOnly + } + return c.pass(ctx, files, tags) +} + +// PassFinal backs up the complete lifecycle delta and final-only files. +func (c *Client) PassFinal(ctx context.Context, tags []string) (outcome Outcome, resultErr error) { + c.mu.Lock() + defer c.mu.Unlock() + if c.readOnly { + return Outcome{}, ErrReadOnly + } + if c.scanID == "" { + return Outcome{}, ErrNoScan + } + if _, exists := c.passes[c.scanID]; exists { + return Outcome{}, ErrPassDone + } + file, err := os.Open(filepath.Join(c.stateDir, "scan-"+c.scanID+".jsonl")) + if errors.Is(err, os.ErrNotExist) { + return Outcome{}, ErrNoScan + } + if err != nil { + return Outcome{}, fmt.Errorf("client: open current scan: %w", withoutPath(err)) + } + defer func() { + if closeErr := file.Close(); closeErr != nil { + resultErr = errors.Join(resultErr, fmt.Errorf("client: close current scan: %w", withoutPath(closeErr))) + } + }() + files := []string{} + decoder := json.NewDecoder(file) + for { + var line inventory.Line + if err := decoder.Decode(&line); errors.Is(err, io.EOF) { + break + } else if err != nil { + return Outcome{}, fmt.Errorf("client: decode current scan: %w", err) + } + if !c.chained || c.baseline == nil || !baselineHas(c.baseline.Lines, line) || line.Class == "final-only" { + files = append(files, line.Path) + } + } + return c.pass(ctx, files, tags) +} + +func (c *Client) pass(ctx context.Context, files []string, tags []string) (Outcome, error) { + if err := ctx.Err(); err != nil { + return Outcome{}, err + } + if c.newestDelta == "" { + return Outcome{}, ErrNoScan + } + if _, exists := c.passes[c.scanID]; exists { + return Outcome{}, ErrPassDone + } + if err := c.ensureRepository(ctx); err != nil { + return Outcome{}, err + } + started := c.now().UTC() + list, vanished, err := c.filterPresent(files, started) + if err != nil { + return Outcome{}, err + } + for _, path := range list { + if _, exists := c.scanned[pathKey(path)]; !exists { + line, err := statLine(path) + if err != nil { + return Outcome{}, err + } + if err := c.appendEvent(journalEvent{Event: eventPending, Line: &line, At: started}); err != nil { + return Outcome{}, err + } + } + } + list = appendUnique(list, c.newestDelta) + listPath, err := c.privateList("pass-files", list) + if err != nil { + return Outcome{}, err + } + defer removePrivateFile(listPath) + passID := c.scanID + // Pending paths stay in memory; the ack journals them one per line, so no line grows with the walk set. + start := journalEvent{Event: eventPassStart, PassID: passID, ScanStartedAt: c.scanStarted, At: started} + if err := c.writeEvents([]journalEvent{start}); err != nil { + return Outcome{}, err + } + start.Paths = c.pendingIn(list) + c.applyEvent(start) + return c.runPass(ctx, list, listPath, tags, passID, started, vanished) +} + +func (c *Client) filterPresent(files []string, started time.Time) ([]string, []string, error) { + present := make([]string, 0, len(files)) + seen := make(map[string]struct{}, len(files)) + vanished := make([]string, 0) + for _, path := range files { + info, err := os.Lstat(path) //nolint:gosec // Checks a source selected for the pass. + if errors.Is(err, os.ErrNotExist) { + vanished = append(vanished, path) + if err := c.appendEvent(journalEvent{Event: eventVanished, Path: path, At: started}); err != nil { + return nil, nil, err + } + continue + } + if err != nil { + return nil, nil, fmt.Errorf("client: lstat pending file: %w", withoutPath(err)) + } + if info.IsDir() { + return nil, nil, errors.New("client: pass file list contains a directory") + } + if _, dup := seen[path]; !dup { + seen[path] = struct{}{} + present = append(present, path) + } + } + return present, vanished, nil +} + +func (c *Client) runPass(ctx context.Context, files []string, listPath string, tags []string, passID string, started time.Time, vanished []string) (Outcome, error) { + args := c.commonArgs("backup", true) + args = append(args, "--host", c.repo.Scope, "--tag", "pass-"+passID, "--files-from-verbatim", filepath.Base(listPath)) + if parent := c.latestAcked(); parent != "" { + args = append(args, "--parent", parent) + } + for _, tag := range tags { + args = append(args, "--tag", tag) + } + output, err := c.runJSON(ctx, args...) + if err == nil { + outcome, ackErr := c.ackPass(passID, started, snapshotID(output), vanished) + outcome.FilesUnmodified = filesUnmodified(output) + return outcome, ackErr + } + return c.failPass(err, output, files, passID, started, vanished) +} + +func (c *Client) ackPass(passID string, started time.Time, id string, vanished []string) (Outcome, error) { + if id == "" { + return Outcome{}, errors.New("client: successful backup returned no snapshot id") + } + paths := c.passes[passID].Paths + events := make([]journalEvent, 0, 1+len(paths)) + events = append(events, journalEvent{Event: eventPassAcked, PassID: passID, SnapshotID: id, At: time.Now().UTC()}) + for _, path := range paths { + events = append(events, journalEvent{Event: eventPathAcked, PassID: passID, Path: path}) + } + if err := c.appendEvents(events); err != nil { + return Outcome{}, err + } + return Outcome{Kind: Acked, PassID: passID, SnapshotID: id, ScanStartedAt: started, Vanished: vanished}, nil +} + +func filesUnmodified(output []byte) int { + for line := range bytes.SplitSeq(output, []byte{'\n'}) { + var message resticMessage + if json.Unmarshal(line, &message) == nil && message.MessageType == "summary" { + return message.FilesUnmodified + } + } + return 0 +} + +func (c *Client) failPass(runErr error, output []byte, files []string, passID string, started time.Time, vanished []string) (Outcome, error) { + var exit exitError + if !errors.As(runErr, &exit) { + return Outcome{}, fmt.Errorf("client: run backup: %w", runErr) + } + outcome := Outcome{PassID: passID, ScanStartedAt: started, ExitCode: exit.ExitCode(), Vanished: vanished} + if outcome.ExitCode == 3 { + outcome.Kind = Incomplete + outcome.SnapshotID = snapshotID(output) + if err := c.appendEvent(journalEvent{Event: eventPassIncomplete, PassID: passID, SnapshotID: outcome.SnapshotID, Code: outcome.ExitCode, At: time.Now().UTC()}); err != nil { + return Outcome{}, err + } + return c.vanishAfterPass(outcome, files) + } + outcome.Kind = Failed + if err := c.appendEvent(journalEvent{Event: eventPassFailed, PassID: passID, Code: outcome.ExitCode, At: time.Now().UTC()}); err != nil { + return Outcome{}, err + } + return outcome, nil +} + +func (c *Client) vanishAfterPass(outcome Outcome, files []string) (Outcome, error) { + for _, path := range files { + _, err := os.Lstat(path) //nolint:gosec // Rechecks a listed source after an incomplete pass. + if errors.Is(err, os.ErrNotExist) { + outcome.Vanished = appendUnique(outcome.Vanished, path) + if err := c.appendEvent(journalEvent{Event: eventVanished, Path: path, At: time.Now().UTC()}); err != nil { + return Outcome{}, err + } + } else if err != nil { + return Outcome{}, fmt.Errorf("client: lstat after incomplete backup: %w", withoutPath(err)) + } + } + return outcome, nil +} + +func (c *Client) ensureRepository(ctx context.Context) error { + if c.initialized { + return nil + } + if err := c.escrowPassword(ctx); err != nil { + return err + } + _, err := c.runJSON(ctx, append(c.commonArgs("cat", false), "config")...) + if err == nil { + return c.journalInit([]byte("{}")) + } + var exit exitError + if !errors.As(err, &exit) { + return fmt.Errorf("client: inspect repository: %w", err) + } + if exit.ExitCode() == 12 { + return c.brokenInit() + } + if exit.ExitCode() != 10 { + return fmt.Errorf("client: inspect repository: %w", err) + } + args := c.commonArgs("init", true) + output, initErr := c.runJSON(ctx, args...) + if initErr == nil { + return c.journalInit(output) + } + _, err = c.runJSON(ctx, append(c.commonArgs("cat", false), "config")...) + if err == nil { + return c.journalInit([]byte("{}")) + } + if !errors.As(err, &exit) { + return fmt.Errorf("client: inspect repository: %w", err) + } + if exit.ExitCode() == 12 { + return c.brokenInit() + } + if exit.ExitCode() != 10 { + return fmt.Errorf("client: inspect repository: %w", err) + } + config, keys, err := localRepositoryState(c.repo.Repository) + if err != nil { + return err + } + if config || keys { + return c.brokenInit() + } + output, err = c.runJSON(ctx, args...) + if err != nil { + return fmt.Errorf("client: retry repository init: %w", err) + } + return c.journalInit(output) +} + +func (c *Client) brokenInit() error { + if err := c.appendEvent(journalEvent{Event: "init-broken", At: time.Now().UTC()}); err != nil { + return err + } + return ErrInitBroken +} + +// localRepositoryState probes a local repository's files; remote backends report nothing. +func localRepositoryState(repository string) (bool, bool, error) { + if resticenv.IsBackend(repository) { + return false, false, nil + } + repository = strings.TrimPrefix(repository, "local:") + _, configErr := os.Stat(filepath.Join(repository, "config")) //nolint:gosec // Inspects the configured local repository. + if configErr != nil && !errors.Is(configErr, os.ErrNotExist) { + return false, false, fmt.Errorf("client: inspect repository config state: %w", configErr) + } + entries, keysErr := os.ReadDir(filepath.Join(repository, "keys")) + if keysErr != nil && !errors.Is(keysErr, os.ErrNotExist) { + return false, false, fmt.Errorf("client: inspect repository key state: %w", keysErr) + } + return configErr == nil, len(entries) > 0, nil +} + +func (c *Client) journalInit(output []byte) error { + var message resticMessage + if len(bytes.TrimSpace(output)) > 0 { + if err := json.Unmarshal(bytes.TrimSpace(output), &message); err != nil { + return fmt.Errorf("client: parse init output: %w", err) + } + } + if c.initialized { + return nil + } + if err := c.appendEvent(journalEvent{Event: eventInit, SnapshotID: message.ID, At: time.Now().UTC()}); err != nil { + return err + } + c.initialized = true + return nil +} +func snapshotID(output []byte) string { + var id string + scanner := bufio.NewScanner(bytes.NewReader(output)) + for scanner.Scan() { + var message struct { + MessageType string `json:"message_type"` + ID string `json:"id"` + SnapshotID string `json:"snapshot_id"` + } + if json.Unmarshal(scanner.Bytes(), &message) != nil { + continue + } + if message.SnapshotID != "" { + id = message.SnapshotID + } + if message.MessageType == "snapshot" && message.ID != "" { + id = message.ID + } + } + return id +} + +func (c *Client) commonArgs(command string, write bool) []string { + args := []string{"--repo", c.repo.Repository, "--password-file", "password", "--json", "--no-cache"} + if !write { + args = append(args, "--no-lock") + } + return append(args, command) +} + +func (c *Client) runJSON(ctx context.Context, args ...string) ([]byte, error) { + tmpDir := c.scratch + if err := os.MkdirAll(tmpDir, 0o700); err != nil { //nolint:gosec // Scratch is selected by the operator. + return nil, fmt.Errorf("client: create restic scratch: %w", withoutPath(err)) + } + command := exec.CommandContext(ctx, c.restic, args...) //nolint:gosec // command resolves the operator-selected restic binary + command.Dir = c.stateDir + command.Env = resticenv.Filter(tmpDir) + var output bytes.Buffer + command.Stdout = &output + command.Stderr = io.Discard + if err := command.Run(); err != nil { + return output.Bytes(), err + } + return output.Bytes(), nil +} + +func (c *Client) nextPassID(started time.Time) (string, error) { + ms := ulid.Timestamp(started) + id := c.lastPass + if id == (ulid.ULID{}) || ms > id.Time() { + fresh, err := ulid.New(ms, rand.Reader) + if err != nil { + return "", fmt.Errorf("client: generate pass id: %w", err) + } + id = fresh + } else { + entropy := id.Entropy() + if err := incrementEntropy(entropy); err != nil { + return "", fmt.Errorf("client: generate pass id: %w", err) + } + if err := id.SetEntropy(entropy); err != nil { + return "", fmt.Errorf("client: generate pass id: %w", err) + } + } + c.lastPass = id + return strings.ToLower(id.String()), nil +} + +// observePassID raises lastPass to id when id is newer. Call it for every +// pass ID read from disk or the journal, including uncommitted ones, so a +// crashed scan's ID is never minted again. A string that is not a ULID +// cannot equal a minted ID, so it is ignored. +func (c *Client) observePassID(id string) { + parsed, err := ulid.ParseStrict(id) + if err != nil { + return + } + if parsed.Compare(c.lastPass) > 0 { + c.lastPass = parsed + } +} + +// incrementEntropy adds one to the big-endian entropy bytes of a pass ID. +func incrementEntropy(entropy []byte) error { + for i := len(entropy) - 1; i >= 0; i-- { + entropy[i]++ + if entropy[i] != 0 { + return nil + } + } + return ulid.ErrMonotonicOverflow +} + +func (c *Client) latestAcked() string { + var newest time.Time + id := "" + for _, event := range c.passes { + if event.Event == "pass-acked" && event.ScanStartedAt.After(newest) { + newest = event.ScanStartedAt + id = event.SnapshotID + } + } + return id +} diff --git a/tools/transcript-archive/internal/client/pass_acceptance_test.go b/tools/transcript-archive/internal/client/pass_acceptance_test.go new file mode 100644 index 000000000..3bef347d9 --- /dev/null +++ b/tools/transcript-archive/internal/client/pass_acceptance_test.go @@ -0,0 +1,305 @@ +package client + +import ( + "bytes" + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "slices" + "testing" + "time" + + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/config" + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/coverage" + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/inventory" +) + +func writeVersion(t *testing.T, path, value, class string) inventory.Line { + t.Helper() + if err := os.WriteFile(path, []byte(value), 0o600); err != nil { + t.Fatal(err) + } + return inventory.Line{Path: path, Type: "file", Size: int64(len(value)), SHA256: sha256.Sum256([]byte(value)), Class: class} +} + +func scanLines(t *testing.T, c *Client, lines ...inventory.Line) { + t.Helper() + if err := c.Scan(t.Context(), inventory.Inventory{Lines: lines}, inventory.Delta{Changed: lines}); err != nil { + t.Fatal(err) + } +} + +func ackFiles(t *testing.T, c *Client, paths ...string) Outcome { + t.Helper() + result, err := c.Pass(t.Context(), paths, nil) + if err != nil || result.Kind != Acked { + t.Fatalf("pass = %#v, %v", result, err) + } + return result +} + +func TestPendingThirtyMinutes(t *testing.T) { + localRestic(t) + now := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + c, _, _ := openTestClient(t, filepath.Join(t.TempDir(), "repo"), WithClock(func() time.Time { return now })) + dir := t.TempDir() + file, db := filepath.Join(dir, "session.jsonl"), filepath.Join(dir, "index.db") + for minute := 1; minute <= 30; minute++ { + now = now.Add(time.Minute) + line := writeVersion(t, file, fmt.Sprintf("version-%02d", minute), "normal") + database := writeVersion(t, db, fmt.Sprintf("db-%02d", minute), "final-only") + if minute%5 == 0 { + scanLines(t, c, line, database) + oldest, size := c.Pending() + if oldest.IsZero() || now.Sub(oldest) > 10*time.Minute || size != line.Size { + t.Fatalf("minute %d: pending %v/%d", minute, oldest, size) + } + ackFiles(t, c, file) + } + oldest, size := c.Pending() + if !oldest.IsZero() && now.Sub(oldest) > 10*time.Minute { + t.Fatalf("minute %d: oldest %v", minute, oldest) + } + if size != 0 { + t.Fatalf("minute %d: pending bytes %d", minute, size) + } + } +} + +func TestChangedBetweenScanAndPass(t *testing.T) { + localRestic(t) + c, _, _ := openTestClient(t, filepath.Join(t.TempDir(), "repo")) + path := filepath.Join(t.TempDir(), "session.jsonl") + first := writeVersion(t, path, "first", "normal") + scanLines(t, c, first) + second := writeVersion(t, path, "second version", "normal") + ackFiles(t, c, path) + scanLines(t, c, second) + oldest, size := c.Pending() + if oldest.IsZero() || size != second.Size { + t.Fatalf("changed pending %v/%d", oldest, size) + } + ackFiles(t, c, path) + oldest, size = c.Pending() + if !oldest.IsZero() || size != 0 { + t.Fatalf("pending after ack %v/%d", oldest, size) + } +} + +func TestCoverageAppendBetweenScanAndPass(t *testing.T) { + localRestic(t) + repo := filepath.Join(t.TempDir(), "repo") + c, _, state := openTestClient(t, repo) + path := filepath.Join(t.TempDir(), "session.jsonl") + first := writeVersion(t, path, "first", "normal") + scanLines(t, c, first) + passID := c.scanID + writeVersion(t, path, "first appended", "normal") + ack := ackFiles(t, c, path) + if err := os.Remove(path); err != nil { + t.Fatal(err) + } + files := snapshotFiles(t, repo, state, ack.SnapshotID) + if !files[path] { + t.Fatal("snapshot does not hold appended path") + } + delta, err := os.Open(c.newestDelta) + if err != nil { + t.Fatal(err) + } + defer delta.Close() + history := []coverage.SnapshotListing{{SnapshotID: ack.SnapshotID, PassID: passID, Outcome: "pass-acked", PathsOnly: true, Files: map[string][32]byte{path: {}}}} + report := coverage.Check(inventory.Inventory{}, inventory.Inventory{}, []coverage.Delta{{PassID: passID, R: delta}}, false, coverage.SnapshotListing{}, nil, history, nil) + if !report.Pass || len(report.History) != 1 || report.History[0].SHA256 != first.SHA256 { + t.Fatalf("coverage = %#v", report) + } +} + +func TestFinalPassContainsWholeDelta(t *testing.T) { + localRestic(t) + repo := filepath.Join(t.TempDir(), "repo") + c, _, state := openTestClient(t, repo) + dir := t.TempDir() + lines := make([]inventory.Line, 0, 4) + var parent Outcome + for i := range 3 { + path := filepath.Join(dir, fmt.Sprintf("session-%d.jsonl", i)) + lines = append(lines, writeVersion(t, path, fmt.Sprintf("data-%d", i), "normal")) + scanLines(t, c, lines...) + parent = ackFiles(t, c, path) + } + db := writeVersion(t, filepath.Join(dir, "index.db"), "database", "final-only") + lines = append(lines, db) + scanLines(t, c, lines...) + parentFiles := snapshotFiles(t, repo, state, parent.SnapshotID) + wantUnmodified := 0 + for _, line := range lines { + if parentFiles[line.Path] { + wantUnmodified++ + } + } + if wantUnmodified == 0 { + t.Fatal("parent snapshot contains no unchanged delta files") + } + result, err := c.PassFinal(t.Context(), []string{"final"}) + if err != nil || result.Kind != Acked { + t.Fatalf("final pass = %#v, %v", result, err) + } + if result.FilesUnmodified != wantUnmodified { + t.Fatalf("final files_unmodified = %d, want %d", result.FilesUnmodified, wantUnmodified) + } + finalFiles := snapshotFiles(t, repo, state, result.SnapshotID) + for _, line := range lines { + if !finalFiles[line.Path] { + t.Errorf("snapshot missing %s", line.Path) + } + } +} + +func snapshotFiles(t *testing.T, repo, state, snapshot string) map[string]bool { + t.Helper() + args := []string{"-r", repo, "--password-file", filepath.Join(state, "password"), "ls", "--json", "--no-lock", snapshot} + output, err := exec.Command("restic", args...).Output() + if err != nil { + t.Fatal(err) + } + files := map[string]bool{} + decoder := json.NewDecoder(bytes.NewReader(output)) + for decoder.More() { + var entry struct { + Type string `json:"type"` + Path string `json:"path"` + } + if err := decoder.Decode(&entry); err != nil { + t.Fatal(err) + } + if entry.Type == "file" { + files[entry.Path] = true + } + } + return files +} + +func TestWalkScanFinalCoverage(t *testing.T) { + localRestic(t) + root := t.TempDir() + path := filepath.Join(root, "data", "transcript") + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + writeVersion(t, path, "transcript", "normal") + cfg := config.Walk{Root: root, Sources: []config.Source{{Name: "data", Path: "data"}}} + final, delta, err := inventory.Walk(cfg, nil) + if err != nil { + t.Fatal(err) + } + repo := filepath.Join(t.TempDir(), "repo") + state := filepath.Join(root, ".example", "archive", "test") + c, err := Open(state, RepoRef{Scope: "k3s-test-one", Repository: repo}, &fakeEscrow{}, WithScratch(t.TempDir())) + if err != nil { + t.Fatal(err) + } + if err := c.Scan(t.Context(), final, delta); err != nil { + t.Fatal(err) + } + first, err := c.Pass(t.Context(), []string{path}, nil) + if err != nil || first.Kind != Acked || len(first.Vanished) != 0 { + t.Fatalf("pass = %#v, %v", first, err) + } + if err := c.Scan(t.Context(), final, inventory.Delta{}); err != nil { + t.Fatal(err) + } + last, err := c.PassFinal(t.Context(), nil) + if err != nil || last.Kind != Acked || len(last.Vanished) != 0 { + t.Fatalf("final pass = %#v, %v", last, err) + } + files := snapshotDigests(t, repo, state, last.SnapshotID) + deltaFile, err := os.Open(c.newestDelta) + if err != nil { + t.Fatal(err) + } + defer deltaFile.Close() + listing := coverage.SnapshotListing{Files: files, StateFiles: map[string]struct{}{c.newestDelta: {}}} + report := coverage.Check(final, inventory.Inventory{}, []coverage.Delta{{PassID: c.scanID, R: deltaFile}}, false, listing, nil, nil, nil) + if !report.Pass || report.Vanished != 0 { + t.Fatalf("coverage = %#v", report) + } +} + +func TestWalkScanDeletedVersionUnexplained(t *testing.T) { + root := t.TempDir() + path := filepath.Join(root, "data", "transcript") + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + writeVersion(t, path, "transcript", "normal") + cfg := config.Walk{Root: root, Sources: []config.Source{{Name: "data", Path: "data"}}} + scan, delta, err := inventory.Walk(cfg, nil) + if err != nil { + t.Fatal(err) + } + c, _, _ := openTestClient(t, filepath.Join(t.TempDir(), "repo")) + if err := c.Scan(t.Context(), scan, delta); err != nil { + t.Fatal(err) + } + if err := os.Remove(path); err != nil { + t.Fatal(err) + } + final, _, err := inventory.Walk(cfg, &scan) + if err != nil { + t.Fatal(err) + } + deltaFile, err := os.Open(c.newestDelta) + if err != nil { + t.Fatal(err) + } + defer deltaFile.Close() + report := coverage.Check(final, inventory.Inventory{}, []coverage.Delta{{PassID: c.scanID, R: deltaFile}}, false, coverage.SnapshotListing{}, nil, nil, nil) + if report.Pass || !slices.Contains(report.Unexplained, path) { + t.Fatalf("coverage = %#v", report) + } +} + +func snapshotDigests(t *testing.T, repo, state, snapshot string) map[string][32]byte { + t.Helper() + files := snapshotFiles(t, repo, state, snapshot) + digests := make(map[string][32]byte, len(files)) + for path := range files { + args := []string{"-r", repo, "--password-file", filepath.Join(state, "password"), "dump", snapshot, path} + data, err := exec.Command("restic", args...).Output() + if err != nil { + t.Fatal(err) + } + digests[path] = sha256.Sum256(data) + } + return digests +} + +func TestInterruptedScanOrphanExcludedFromCoverage(t *testing.T) { + repo := filepath.Join(t.TempDir(), "repo") + c, _, state := openTestClient(t, repo) + line := writeVersion(t, filepath.Join(t.TempDir(), "lost"), "data", "normal") + stop := errors.New("interrupt") + c.scanHook = func(point string) error { + if point == "delta" { + return stop + } + return nil + } + if err := c.Scan(t.Context(), inventory.Inventory{Lines: []inventory.Line{line}}, inventory.Delta{Added: []inventory.Line{line}}); err != stop { + t.Fatalf("scan: %v", err) + } + entries, err := os.ReadDir(filepath.Join(state, "deltas")) + if err != nil || len(entries) != 1 { + t.Fatalf("orphan before open: %v %v", entries, err) + } + reopenTestClient(t, state, repo) + entries, err = os.ReadDir(filepath.Join(state, "deltas")) + if err != nil || len(entries) != 0 { + t.Fatalf("orphan after open: %v %v", entries, err) + } +} diff --git a/tools/transcript-archive/internal/client/pass_argv_test.go b/tools/transcript-archive/internal/client/pass_argv_test.go new file mode 100644 index 000000000..e5ce79a54 --- /dev/null +++ b/tools/transcript-archive/internal/client/pass_argv_test.go @@ -0,0 +1,58 @@ +package client + +import ( + "bytes" + "fmt" + "os" + "path/filepath" + "slices" + "strings" + "testing" +) + +// TestPassChildArgvAndEnvHideSourceAndPassword checks that pass gives restic +// only the list file name, never the source path or the password bytes. +func TestPassChildArgvAndEnvHideSourceAndPassword(t *testing.T) { + const sentinel = "unique-source-sentinel-9006" + localRestic(t) + repo := filepath.Join(t.TempDir(), "repo") + c, _, state := openTestClient(t, repo) + source := filepath.Join(t.TempDir(), sentinel) + if err := os.Mkdir(source, 0o700); err != nil { + t.Fatal(err) + } + file := filepath.Join(source, "session") + line := writeVersion(t, file, "data", "normal") + scanLines(t, c, line) + calls := filepath.Join(t.TempDir(), "calls") + resticWrapper(t, fmt.Sprintf(`{ printf 'cmd '; tr '\000' ' ' < /proc/$$/cmdline; printf '\n'; cat /proc/$$/environ; printf '\n'; } >> %q +exec REAL_RESTIC "$@"`, calls)) + ackFiles(t, c, file) + password, err := os.ReadFile(filepath.Join(state, "password")) + if err != nil { + t.Fatal(err) + } + if len(password) == 0 { + t.Fatal("password file is empty") + } + records, err := os.ReadFile(calls) + if err != nil { + t.Fatal(err) + } + backups := 0 + for record := range bytes.SplitSeq(records, []byte{'\n'}) { + if rest, ok := strings.CutPrefix(string(record), "cmd "); ok && slices.Contains(strings.Fields(rest), "backup") { + backups++ + } + } + t.Logf("healthy-subject: backup invocations=%d", backups) + if backups == 0 { + t.Fatal("no backup invocation was logged") + } + if bytes.Contains(records, []byte(sentinel)) { + t.Fatal("source sentinel appeared in restic argv or environment") + } + if bytes.Contains(records, password) { + t.Fatal("password bytes appeared in restic argv or environment") + } +} diff --git a/tools/transcript-archive/internal/client/pass_crash_test.go b/tools/transcript-archive/internal/client/pass_crash_test.go new file mode 100644 index 000000000..eda135f35 --- /dev/null +++ b/tools/transcript-archive/internal/client/pass_crash_test.go @@ -0,0 +1,212 @@ +package client + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +func resticWrapper(t *testing.T, body string) { + t.Helper() + real, err := exec.LookPath("restic") + if err != nil { + t.Fatal(err) + } + dir := t.TempDir() + script := "#!/bin/sh\n" + strings.ReplaceAll(body, "REAL_RESTIC", real) + "\n" + if err := os.WriteFile(filepath.Join(dir, "restic"), []byte(script), 0o700); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) +} + +func journalHas(t *testing.T, state, event, path string) bool { + t.Helper() + data, err := os.ReadFile(filepath.Join(state, "journal.jsonl")) + if err != nil { + t.Fatal(err) + } + for line := range strings.SplitSeq(strings.TrimSpace(string(data)), "\n") { + var e journalEvent + if err := json.Unmarshal([]byte(line), &e); err != nil { + t.Fatal(err) + } + if e.Event == event && (path == "" || e.Path == path) { + return true + } + } + return false +} + +func reopenTestClient(t *testing.T, state, repo string) *Client { + t.Helper() + c, err := Open(state, RepoRef{Scope: "k3s-test-one", Repository: repo}, &fakeEscrow{}, WithScratch(t.TempDir())) + if err != nil { + t.Fatal(err) + } + return c +} + +func TestCrashPassHelper(t *testing.T) { + if os.Getenv("CLIENT_CRASH_HELPER") != "1" { + return + } + c := reopenTestClient(t, os.Getenv("CLIENT_STATE"), os.Getenv("CLIENT_REPO")) + _, err := c.Pass(t.Context(), []string{os.Getenv("CLIENT_FILE")}, nil) + t.Fatalf("pass unexpectedly returned: %v", err) +} + +func crashPass(t *testing.T, state, repo, file string) { + t.Helper() + cmd := exec.Command(os.Args[0], "-test.run=^TestCrashPassHelper$") + cmd.Env = append(os.Environ(), "CLIENT_CRASH_HELPER=1", "CLIENT_STATE="+state, "CLIENT_REPO="+repo, "CLIENT_FILE="+file) + err := cmd.Run() + var exit *exec.ExitError + if !errors.As(err, &exit) || exit.ExitCode() != -1 { + t.Fatalf("child exit = %v, want signal", err) + } +} + +func TestRecoverCrashPoints(t *testing.T) { + for _, tc := range []struct{ name, script, event string }{ + {name: "stored", script: `REAL_RESTIC "$@" || exit 1; kill -KILL "$PPID"`, event: "pass-stored"}, + {name: "not uploaded", script: `kill -KILL "$PPID"`, event: "pass-abandoned"}, + } { + t.Run(tc.name, func(t *testing.T) { + localRestic(t) + repo := filepath.Join(t.TempDir(), "repo") + c, _, state := openTestClient(t, repo) + file := filepath.Join(t.TempDir(), "session") + line := writeVersion(t, file, "data", "normal") + scanLines(t, c, line) + if err := c.ensureRepository(t.Context()); err != nil { + t.Fatal(err) + } + resticWrapper(t, "case \" $* \" in *' backup '*) "+tc.script+" ;; *) exec REAL_RESTIC \"$@\" ;; esac") + crashPass(t, state, repo, file) + c = reopenTestClient(t, state, repo) + if err := c.Recover(t.Context()); err != nil { + t.Fatal(err) + } + if !journalHas(t, state, tc.event, "") { + t.Fatalf("missing %s", tc.event) + } + if oldest, size := c.Pending(); oldest.IsZero() || size != 4 { + t.Fatalf("pending = %v/%d", oldest, size) + } + if tc.event == "pass-abandoned" { + // Restore the real binary for the next pass. + t.Setenv("PATH", strings.TrimPrefix(os.Getenv("PATH"), strings.Split(os.Getenv("PATH"), string(os.PathListSeparator))[0]+string(os.PathListSeparator))) + scanLines(t, c, line) + ackFiles(t, c, file) + } + }) + } +} + +func TestInitWrongPassword(t *testing.T) { + localRestic(t) + repo := filepath.Join(t.TempDir(), "repo") + first, _, _ := openTestClient(t, repo) + if err := first.ensureRepository(t.Context()); err != nil { + t.Fatal(err) + } + second, _, state := openTestClient(t, repo) + if err := second.ensureRepository(t.Context()); !errors.Is(err, ErrInitBroken) { + t.Fatalf("init = %v", err) + } + if !journalHas(t, state, "init-broken", "") { + t.Fatal("missing init-broken") + } +} + +func TestInitRetriesEmptyRepository(t *testing.T) { + localRestic(t) + repo := filepath.Join(t.TempDir(), "repo") + c, _, _ := openTestClient(t, repo) + if err := os.Mkdir(repo, 0o700); err != nil { + t.Fatal(err) + } + marker := filepath.Join(t.TempDir(), "failed") + resticWrapper(t, fmt.Sprintf(`case " $* " in *' init '*) if [ ! -e %q ]; then : > %q; exit 1; fi ;; esac +exec REAL_RESTIC "$@"`, marker, marker)) + if err := c.ensureRepository(t.Context()); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(repo, "config")); err != nil { + t.Fatal(err) + } +} +func TestVanishedDuringPass(t *testing.T) { + localRestic(t) + repo := filepath.Join(t.TempDir(), "repo") + c, _, state := openTestClient(t, repo) + dir := t.TempDir() + gone := filepath.Join(dir, "gone") + unreadable := filepath.Join(dir, "unreadable") + first := writeVersion(t, gone, "gone", "normal") + second := writeVersion(t, unreadable, "unreadable", "normal") + scanLines(t, c, first, second) + if err := c.ensureRepository(t.Context()); err != nil { + t.Fatal(err) + } + resticWrapper(t, fmt.Sprintf(`case " $* " in *' backup '*) rm -- %q; chmod 000 -- %q ;; esac +exec REAL_RESTIC "$@"`, gone, unreadable)) + outcome, err := c.Pass(t.Context(), []string{gone, unreadable}, nil) + if err != nil || outcome.Kind != Incomplete || outcome.ExitCode != 3 || outcome.SnapshotID == "" { + t.Fatalf("pass = %#v, %v", outcome, err) + } + if !journalHas(t, state, "vanished", gone) || journalHas(t, state, "vanished", unreadable) { + t.Fatal("incorrect vanished journal entries") + } + if _, ok := c.pending[pathKey(unreadable)]; !ok { + t.Fatal("unreadable file not pending") + } + if _, ok := c.pending[pathKey(gone)]; ok { + t.Fatal("vanished file still pending") + } +} + +func TestIncompleteSurvivesCrashUntilAck(t *testing.T) { + localRestic(t) + repo := filepath.Join(t.TempDir(), "repo") + c, _, state := openTestClient(t, repo) + file := filepath.Join(t.TempDir(), "session") + line := writeVersion(t, file, "data", "normal") + scanLines(t, c, line) + if err := c.ensureRepository(t.Context()); err != nil { + t.Fatal(err) + } + if err := os.Chmod(file, 0); err != nil { + t.Fatal(err) + } + outcome, err := c.Pass(t.Context(), []string{file}, nil) + if err != nil || outcome.Kind != Incomplete || outcome.ExitCode != 3 || outcome.SnapshotID == "" { + t.Fatalf("pass = %#v, %v", outcome, err) + } + scanLines(t, c, line) + resticWrapper(t, `case " $* " in *' backup '*) kill -KILL "$PPID" ;; *) exec REAL_RESTIC "$@" ;; esac`) + crashPass(t, state, repo, file) + c = reopenTestClient(t, state, repo) + if err := c.Recover(t.Context()); err != nil { + t.Fatal(err) + } + if oldest, size := c.Pending(); oldest.IsZero() || size != 4 { + t.Fatalf("pending = %v/%d", oldest, size) + } + if err := os.Chmod(file, 0o600); err != nil { + t.Fatal(err) + } + _, path, _ := strings.Cut(os.Getenv("PATH"), string(os.PathListSeparator)) + t.Setenv("PATH", path) + scanLines(t, c, line) + ackFiles(t, c, file) + if oldest, size := c.Pending(); !oldest.IsZero() || size != 0 { + t.Fatalf("pending = %v/%d", oldest, size) + } +} diff --git a/tools/transcript-archive/internal/client/readonly_test.go b/tools/transcript-archive/internal/client/readonly_test.go new file mode 100644 index 000000000..6489b631c --- /dev/null +++ b/tools/transcript-archive/internal/client/readonly_test.go @@ -0,0 +1,141 @@ +package client + +import ( + "crypto/sha256" + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/inventory" +) + +// stateTree records each entry's path, mode, size, mtime and, for regular files, SHA-256. +// A chmod that keeps the current mode changes only ctime, which it does not record. +func stateTree(t *testing.T, dir string) string { + t.Helper() + var b strings.Builder + err := filepath.WalkDir(dir, func(path string, entry fs.DirEntry, err error) error { + if err != nil { + return err + } + info, err := entry.Info() + if err != nil { + return err + } + rel, err := filepath.Rel(dir, path) + if err != nil { + return err + } + fmt.Fprintf(&b, "%s %v %d %d", rel, info.Mode(), info.Size(), info.ModTime().UnixNano()) + if info.Mode().IsRegular() { + data, err := os.ReadFile(path) + if err != nil { + return err + } + fmt.Fprintf(&b, " %x", sha256.Sum256(data)) + } + b.WriteString("\n") + return nil + }) + if err != nil { + t.Fatal(err) + } + return b.String() +} + +// seedReadOnlyState writes a real lifecycle state and plants the leftovers a read-write Open would clean up. +func seedReadOnlyState(t *testing.T) (state, repo string, newestDelta string) { + t.Helper() + repo = filepath.Join(t.TempDir(), "repo") + c, _, state := openTestClient(t, repo) + line := inventory.Line{Path: "first", Type: "file", Size: 1} + if err := c.Scan(t.Context(), inventory.Inventory{Lines: []inventory.Line{line}}, inventory.Delta{Added: []inventory.Line{line}}); err != nil { + t.Fatal(err) + } + for _, name := range []string{".current-orphan", ".password-orphan", "scan-01ARZ3NDEKTSV4RRFFQ69G5FAV.jsonl"} { + if err := os.WriteFile(filepath.Join(state, name), []byte("leftover\n"), 0o600); err != nil { + t.Fatal(err) + } + } + return state, repo, c.newestDelta +} + +func TestOpenReadOnlyLeavesStateDirUnchanged(t *testing.T) { + state, repo, newestDelta := seedReadOnlyState(t) + // Open sets these to 0o700 and 0o600; seed other modes so a regression changes the tree. + if err := os.Chmod(state, 0o750); err != nil { + t.Fatal(err) + } + if err := os.Chmod(filepath.Join(state, "journal.jsonl"), 0o640); err != nil { + t.Fatal(err) + } + before := stateTree(t, state) + ro, err := OpenReadOnly(state, RepoRef{Scope: "k3s-test-one", Repository: repo}) + if err != nil { + t.Fatal(err) + } + if after := stateTree(t, state); after != before { + t.Fatalf("read-only open changed the state directory\nbefore:\n%s\nafter:\n%s", before, after) + } + if ro.newestDelta != newestDelta { + t.Fatalf("read-only newestDelta = %q, want %q", ro.newestDelta, newestDelta) + } + if _, err := os.Stat(filepath.Join(state, "scan-01ARZ3NDEKTSV4RRFFQ69G5FAV.jsonl")); err != nil { + t.Fatalf("orphan scan removed by read-only open: %v", err) + } +} + +func TestOpenReadOnlyEmptyStateDirWritesNothing(t *testing.T) { + state := t.TempDir() + before := stateTree(t, state) + ro, err := OpenReadOnly(state, RepoRef{Scope: "k3s-test-one", Repository: filepath.Join(t.TempDir(), "repo")}) + if err != nil { + t.Fatal(err) + } + if after := stateTree(t, state); after != before { + t.Fatalf("read-only open of empty state wrote files\nbefore:\n%s\nafter:\n%s", before, after) + } + if oldest, bytes := ro.Pending(); !oldest.IsZero() || bytes != 0 { + t.Fatalf("pending = %v %d, want none", oldest, bytes) + } +} + +func TestOpenReadOnlyMissingStateDirIsNotCreated(t *testing.T) { + state := filepath.Join(t.TempDir(), "missing") + _, err := OpenReadOnly(state, RepoRef{Scope: "k3s-test-one", Repository: filepath.Join(t.TempDir(), "repo")}) + if !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("OpenReadOnly error = %v, want fs.ErrNotExist", err) + } + if _, err := os.Stat(state); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("missing state directory was created: %v", err) + } +} + +func TestReadOnlyClientRejectsWrites(t *testing.T) { + state, repo, _ := seedReadOnlyState(t) + before := stateTree(t, state) + ro, err := OpenReadOnly(state, RepoRef{Scope: "k3s-test-one", Repository: repo}) + if err != nil { + t.Fatal(err) + } + line := inventory.Line{Path: "second", Type: "file", Size: 2} + if err := ro.Scan(t.Context(), inventory.Inventory{Lines: []inventory.Line{line}}, inventory.Delta{Added: []inventory.Line{line}}); !errors.Is(err, ErrReadOnly) { + t.Fatalf("Scan error = %v, want ErrReadOnly", err) + } + if _, err := ro.Pass(t.Context(), nil, nil); !errors.Is(err, ErrReadOnly) { + t.Fatalf("Pass error = %v, want ErrReadOnly", err) + } + if _, err := ro.PassFinal(t.Context(), nil); !errors.Is(err, ErrReadOnly) { + t.Fatalf("PassFinal error = %v, want ErrReadOnly", err) + } + if err := ro.Recover(t.Context()); !errors.Is(err, ErrReadOnly) { + t.Fatalf("Recover error = %v, want ErrReadOnly", err) + } + if after := stateTree(t, state); after != before { + t.Fatalf("rejected write changed the state directory\nbefore:\n%s\nafter:\n%s", before, after) + } +} diff --git a/tools/transcript-archive/internal/client/recovery.go b/tools/transcript-archive/internal/client/recovery.go new file mode 100644 index 000000000..5d8a23e97 --- /dev/null +++ b/tools/transcript-archive/internal/client/recovery.go @@ -0,0 +1,120 @@ +package client + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "slices" + "sort" + "time" +) + +// JournalSnapshot identifies a snapshot and its durable pass outcome. +type JournalSnapshot struct { + SnapshotID string + Outcome OutcomeKind +} + +// Snapshots returns all journaled snapshots usable as history. +func (c *Client) Snapshots() []JournalSnapshot { + c.mu.Lock() + defer c.mu.Unlock() + snapshots := make([]JournalSnapshot, 0, len(c.passes)) + for _, pass := range c.passes { + if pass.SnapshotID == "" { + continue + } + var outcome OutcomeKind + switch pass.Event { + case eventPassAcked: + outcome = Acked + case eventPassIncomplete: + outcome = Incomplete + case eventPassStored: + outcome = Stored + default: + continue + } + snapshots = append(snapshots, JournalSnapshot{SnapshotID: pass.SnapshotID, Outcome: outcome}) + } + sort.Slice(snapshots, func(i, j int) bool { return snapshots[i].SnapshotID < snapshots[j].SnapshotID }) + return snapshots +} + +// Recover resolves passes that started without a recorded outcome. +func (c *Client) Recover(ctx context.Context) error { + c.mu.Lock() + defer c.mu.Unlock() + if c.readOnly { + return ErrReadOnly + } + if err := ctx.Err(); err != nil { + return err + } + if err := c.ensureRepository(ctx); err != nil { + return err + } + passIDs := make([]string, 0, len(c.passes)) + for passID, event := range c.passes { + if event.Event == eventPassStart && !c.outcomes[passID] { + passIDs = append(passIDs, passID) + } + } + sort.Strings(passIDs) + for _, passID := range passIDs { + if err := ctx.Err(); err != nil { + return err + } + args := c.commonArgs("snapshots", false) + args = append(args, "--tag", "pass-"+passID) + output, err := c.runJSON(ctx, args...) + if err != nil { + return fmt.Errorf("client: recover pass: %w", err) + } + snapshotID, err := taggedSnapshot(output, passID) + if err != nil { + return err + } + kind, event := Stored, eventPassStored + if snapshotID == "" { + kind, event = Abandoned, eventPassAbandoned + } + if err := c.appendEvent(journalEvent{Event: event, PassID: passID, SnapshotID: snapshotID, At: time.Now().UTC()}); err != nil { + return err + } + if kind == Stored { + continue + } + } + return nil +} + +func taggedSnapshot(output []byte, passID string) (string, error) { + var snapshots []struct { + ID string `json:"id"` + Tags []string `json:"tags"` + } + if err := json.Unmarshal(bytes.TrimSpace(output), &snapshots); err != nil { + return "", fmt.Errorf("client: parse snapshot listing: %w", err) + } + for _, snapshot := range snapshots { + if slices.Contains(snapshot.Tags, "pass-"+passID) { + return snapshot.ID, nil + } + } + return "", nil +} + +// Pending reports the oldest pending-since time and the pending byte total. +func (c *Client) Pending() (oldest time.Time, bytes int64) { + c.mu.Lock() + defer c.mu.Unlock() + for _, pending := range c.pending { + if oldest.IsZero() || pending.at.Before(oldest) { + oldest = pending.at + } + bytes += pending.line.Size + } + return oldest, bytes +} diff --git a/tools/transcript-archive/internal/client/remote_test.go b/tools/transcript-archive/internal/client/remote_test.go new file mode 100644 index 000000000..f8265c2f3 --- /dev/null +++ b/tools/transcript-archive/internal/client/remote_test.go @@ -0,0 +1,84 @@ +package client + +import ( + "bufio" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/inventory" +) + +// stubRestic answers `cat config` as an existing repo and `backup` with a snapshot id. +func stubRestic(t *testing.T) string { + t.Helper() + path := filepath.Join(t.TempDir(), "restic") + body := "#!/bin/sh\nfor a in \"$@\"; do\n if [ \"$a\" = backup ]; then echo '{\"message_type\":\"summary\",\"snapshot_id\":\"stubsnap\"}'; exit 0; fi\ndone\nexit 0\n" + if err := os.WriteFile(path, []byte(body), 0o700); err != nil { + t.Fatal(err) + } + return path +} + +func TestPassAcceptsBackendRepository(t *testing.T) { + for _, repo := range []string{"s3:https://acct.example.invalid/bucket/host", "rest:http://127.0.0.1:1/x"} { + c, _, _ := openTestClient(t, repo, WithRestic(stubRestic(t))) + path := filepath.Join(t.TempDir(), "session.jsonl") + scanLines(t, c, writeVersion(t, path, "one", "normal")) + if outcome, err := c.Pass(t.Context(), []string{path}, nil); err != nil || outcome.Kind != Acked { + t.Fatalf("%s: pass = %#v, %v", repo, outcome, err) + } + } +} + +func TestPassStartLineBounded(t *testing.T) { + c, _, state := openTestClient(t, "s3:https://acct.example.invalid/bucket/host", WithRestic(stubRestic(t))) + dir := t.TempDir() + const total = 50000 + files := make([]string, total) + lines := make([]inventory.Line, total) + for i := range files { + files[i] = filepath.Join(dir, fmt.Sprintf("f%05d", i)) + if err := os.WriteFile(files[i], nil, 0o600); err != nil { + t.Fatal(err) + } + lines[i] = inventory.Line{Path: files[i], Type: "file", Class: "final-only"} + } + pending := writeVersion(t, filepath.Join(dir, "pending.jsonl"), "data", "normal") + lines = append(lines, pending) + scanLines(t, c, lines...) + if outcome, err := c.Pass(t.Context(), append(files, pending.Path), nil); err != nil || outcome.Kind != Acked { + t.Fatalf("pass = %#v, %v", outcome, err) + } + if oldest, size := c.Pending(); !oldest.IsZero() || size != 0 { + t.Fatalf("pending after ack %v/%d", oldest, size) + } + journal, err := os.Open(filepath.Join(state, "journal.jsonl")) + if err != nil { + t.Fatal(err) + } + defer journal.Close() + scanner := bufio.NewScanner(journal) + scanner.Buffer(make([]byte, 64*1024), 64*1024*1024) + found := false + for scanner.Scan() { + if strings.Contains(scanner.Text(), `"event":"pass-start"`) { + found = true + if len(scanner.Bytes()) > 16*1024 { + t.Fatalf("pass-start line is %d bytes for %d files", len(scanner.Bytes()), total+1) + } + } + } + if !found { + t.Fatal("no pass-start event") + } + reopened, err := Open(state, RepoRef{Scope: "k3s-test-one", Repository: c.repo.Repository}, &fakeEscrow{}, WithScratch(t.TempDir()), WithRestic(c.restic)) + if err != nil { + t.Fatal(err) + } + if oldest, _ := reopened.Pending(); !oldest.IsZero() { + t.Fatal("pending path not acked after journal replay") + } +} diff --git a/tools/transcript-archive/internal/client/review_init_test.go b/tools/transcript-archive/internal/client/review_init_test.go new file mode 100644 index 000000000..0be96ae3e --- /dev/null +++ b/tools/transcript-archive/internal/client/review_init_test.go @@ -0,0 +1,62 @@ +package client + +import ( + "errors" + "os" + "path/filepath" + "testing" +) + +func TestReviewInitKeysOnly(t *testing.T) { + repo := filepath.Join(t.TempDir(), "repo") + first, _, _ := openTestClient(t, repo) + if err := first.ensureRepository(t.Context()); err != nil { + t.Fatal(err) + } + if err := os.Remove(filepath.Join(repo, "config")); err != nil { + t.Fatal(err) + } + second, _, state := openTestClient(t, repo) + if err := second.ensureRepository(t.Context()); !errors.Is(err, ErrInitBroken) { + t.Fatalf("init: %v", err) + } + if !journalHas(t, state, "init-broken", "") { + t.Fatal("missing init-broken") + } +} + +func TestReviewInitConfigError(t *testing.T) { + c, _, state := openTestClient(t, filepath.Join(t.TempDir(), "repo")) + resticWrapper(t, `case " $* " in *' cat config '*) exit 1 ;; esac; exec REAL_RESTIC "$@"`) + if err := c.ensureRepository(t.Context()); err == nil || errors.Is(err, ErrInitBroken) { + t.Fatalf("init: %v", err) + } + if journalHas(t, state, "init-broken", "") { + t.Fatal("unexpected init-broken") + } +} + +func TestReviewRecoverPreservesAck(t *testing.T) { + repo := filepath.Join(t.TempDir(), "repo") + c, _, state := openTestClient(t, repo) + file := filepath.Join(t.TempDir(), "file") + line := writeVersion(t, file, "data", "normal") + scanLines(t, c, line) + ack := ackFiles(t, c, file) + scanLines(t, c, line) + resticWrapper(t, `case " $* " in *' backup '*) kill -KILL "$PPID" ;; *) exec REAL_RESTIC "$@" ;; esac`) + crashPass(t, state, repo, file) + c = reopenTestClient(t, state, repo) + if err := c.Recover(t.Context()); err != nil { + t.Fatal(err) + } + if !journalHas(t, state, "pass-abandoned", "") { + t.Fatal("missing recovery outcome") + } + if got := c.latestAcked(); got != ack.SnapshotID { + t.Fatalf("latest ack = %q, want %q", got, ack.SnapshotID) + } + if _, err := c.Pass(t.Context(), nil, nil); !errors.Is(err, ErrPassDone) { + t.Fatalf("second pass: %v", err) + } +} diff --git a/tools/transcript-archive/internal/client/review_regression_test.go b/tools/transcript-archive/internal/client/review_regression_test.go new file mode 100644 index 000000000..beda5df14 --- /dev/null +++ b/tools/transcript-archive/internal/client/review_regression_test.go @@ -0,0 +1,111 @@ +package client + +import ( + "errors" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/inventory" +) + +func TestReviewScanFailureKeepsCommittedState(t *testing.T) { + c, _, _ := openTestClient(t, filepath.Join(t.TempDir(), "repo")) + file := filepath.Join(t.TempDir(), "file") + line := writeVersion(t, file, "first", "normal") + scanLines(t, c, line) + oldID, oldStarted := c.scanID, c.scanStarted + c.scanHook = func(point string) error { + if point == "journal" { + return errors.New("injected") + } + return nil + } + if err := c.Scan(t.Context(), inventory.Inventory{}, inventory.Delta{Removed: []inventory.Line{line}}); err == nil { + t.Fatal("scan succeeded") + } + if c.scanID != oldID || c.scanStarted != oldStarted || len(c.scanned) != 1 || len(c.pending) != 1 { + t.Fatal("failed scan changed committed state") + } + c.scanHook = nil + if _, err := c.Pass(t.Context(), []string{file}, nil); err != nil { + t.Fatal(err) + } +} + +func TestReviewOnePassPerScan(t *testing.T) { + c, _, _ := openTestClient(t, filepath.Join(t.TempDir(), "repo")) + scanLines(t, c) + if _, err := c.Pass(t.Context(), nil, nil); err != nil { + t.Fatal(err) + } + if _, err := c.Pass(t.Context(), nil, nil); !errors.Is(err, ErrPassDone) { + t.Fatalf("second pass: %v", err) + } + if _, err := c.PassFinal(t.Context(), nil); !errors.Is(err, ErrPassDone) { + t.Fatalf("final pass: %v", err) + } +} + +func TestReviewScratchRequired(t *testing.T) { + _, err := Open(filepath.Join(t.TempDir(), "state"), RepoRef{Scope: "scope", Repository: "repo"}, &fakeEscrow{}) + if err == nil { + t.Fatal("missing scratch accepted") + } +} + +func TestReviewPrivateErrorsHideStatePath(t *testing.T) { + secret := filepath.Join(t.TempDir(), "sentinel-private-state") + if err := os.Mkdir(secret, 0700); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(filepath.Join(secret, "password"), 0700); err != nil { + t.Fatal(err) + } + c := &Client{stateDir: secret, scratch: filepath.Join(secret, "password", "child")} + _, err := c.readOrCreatePassword() + if err == nil || strings.Contains(err.Error(), secret) { + t.Fatalf("password error leaks state path: %v", err) + } + c.stateDir = filepath.Join(secret, "missing") + _, err = c.privateList("test", nil) + if err == nil || strings.Contains(err.Error(), secret) { + t.Fatalf("list error leaks state path: %v", err) + } + c.scratch = filepath.Join(secret, "password", "child", "nested") + if err := os.WriteFile(filepath.Join(secret, "password", "child"), []byte("x"), 0600); err != nil { + t.Fatal(err) + } + _, err = c.runJSON(t.Context()) + if err == nil || strings.Contains(err.Error(), secret) { + t.Fatalf("scratch error leaks state path: %v", err) + } +} + +func TestReviewCleanOldScanAndTemps(t *testing.T) { + repo := filepath.Join(t.TempDir(), "repo") + c, _, state := openTestClient(t, repo) + scanLines(t, c) + old := filepath.Join(state, "scan-"+c.scanID+".jsonl") + c.scanHook = func(point string) error { + if point == "commit" { + return errors.New("crash") + } + return nil + } + if err := c.Scan(t.Context(), inventory.Inventory{}, inventory.Delta{}); err == nil { + t.Fatal("expected crash") + } + for _, name := range []string{".scan-left", ".current-left", ".password-left", "deltas/.scan-left"} { + if err := os.WriteFile(filepath.Join(state, name), []byte("x"), 0600); err != nil { + t.Fatal(err) + } + } + reopenTestClient(t, state, repo) + for _, name := range []string{old, filepath.Join(state, ".scan-left"), filepath.Join(state, ".current-left"), filepath.Join(state, ".password-left"), filepath.Join(state, "deltas/.scan-left")} { + if _, err := os.Stat(name); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("orphan remains: %s: %v", name, err) + } + } +} diff --git a/tools/transcript-archive/internal/client/scan_files.go b/tools/transcript-archive/internal/client/scan_files.go new file mode 100644 index 000000000..b2125a0ae --- /dev/null +++ b/tools/transcript-archive/internal/client/scan_files.go @@ -0,0 +1,250 @@ +package client + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "time" + + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/inventory" + "github.com/oklog/ulid/v2" +) + +type scanState struct { + ID string `json:"passId"` + Prev string `json:"prev,omitempty"` + Started time.Time `json:"scanStartedAt"` +} + +func (c *Client) replayDeltas() (resultErr error) { + data, err := os.ReadFile(filepath.Join(c.stateDir, "scan-state.json")) //nolint:gosec // G703: stateDir is the operator-configured state directory passed to Open, not request input. + if errors.Is(err, os.ErrNotExist) { + return c.removeOrphanScans() + } + if err != nil { + return fmt.Errorf("client: read scan state: %w", withoutPath(err)) + } + var head scanState + if err := json.Unmarshal(data, &head); err != nil { + return fmt.Errorf("client: decode scan state: %w", withoutPath(err)) + } + for id := head.ID; id != ""; { + data, err := os.ReadFile(filepath.Join(c.stateDir, "scan-state-"+id+".json")) //nolint:gosec // Scan history IDs are generated by this client. + if err != nil { + return fmt.Errorf("client: read scan history: %w", withoutPath(err)) + } + var state scanState + if err := json.Unmarshal(data, &state); err != nil { + return fmt.Errorf("client: decode scan history: %w", withoutPath(err)) + } + if state.ID != id || c.committed[id] { + return errors.New("client: invalid scan history") + } + c.committed[id] = true + id = state.Prev + } + last, err := ulid.ParseStrict(head.ID) + if err != nil { + return fmt.Errorf("client: decode scan id: %w", withoutPath(err)) + } + c.scanID, c.scanStarted, c.lastPass = head.ID, head.Started, last + c.newestDelta, err = filepath.Abs(filepath.Join(c.stateDir, "deltas", "delta-"+head.ID+".jsonl")) + if err != nil { + return fmt.Errorf("client: resolve delta path: %w", withoutPath(err)) + } + file, err := os.Open(filepath.Join(c.stateDir, "scan-"+head.ID+".jsonl")) //nolint:gosec // G703: head.ID is the scan id from scan-state.json, checked by ulid.ParseStrict above (a ULID is 26 Crockford base32 characters, so it cannot hold a separator or ".."). Keep this Open below that check. + if err != nil { + return fmt.Errorf("client: open current scan: %w", withoutPath(err)) + } + defer func() { resultErr = errors.Join(resultErr, withoutPath(file.Close())) }() + decoder := json.NewDecoder(file) + for decoder.More() { + var line inventory.Line + if err := decoder.Decode(&line); err != nil { + return fmt.Errorf("client: decode current scan: %w", withoutPath(err)) + } + c.scanned[line.Path] = line + } + if err := c.publishCurrentScan(head.ID); err != nil { + return err + } + return c.removeOrphanScans() +} + +func (c *Client) removeOrphanScans() error { + if c.readOnly { + return nil + } + for _, dir := range []string{c.stateDir, filepath.Join(c.stateDir, "deltas")} { + entries, err := os.ReadDir(dir) + if errors.Is(err, os.ErrNotExist) { + continue + } + if err != nil { + return fmt.Errorf("client: read scan files: %w", withoutPath(err)) + } + for _, entry := range entries { + name := entry.Name() + id := orphanScanID(name) + c.observePassID(id) + temp := strings.HasPrefix(name, ".scan-") || strings.HasPrefix(name, ".current-") || strings.HasPrefix(name, ".password-") + oldScan := strings.HasPrefix(name, "scan-") && strings.HasSuffix(name, ".jsonl") && name != "scan-current.jsonl" && id != c.scanID + if temp || oldScan || (id != "" && !c.committed[id]) { + if err := os.Remove(filepath.Join(dir, name)); err != nil { //nolint:gosec // G703: dir is stateDir or stateDir/deltas, and name comes from os.ReadDir of that dir, so only entries already inside the state directory are removed. + return fmt.Errorf("client: remove orphan scan: %w", withoutPath(err)) + } + } + } + } + return nil +} + +func orphanScanID(name string) string { + if name == "scan-current.jsonl" { + return "" + } + for _, pattern := range [][2]string{{"delta-", ".jsonl"}, {"scan-state-", ".json"}, {"scan-", ".jsonl"}} { + if strings.HasPrefix(name, pattern[0]) && strings.HasSuffix(name, pattern[1]) { + return strings.TrimSuffix(strings.TrimPrefix(name, pattern[0]), pattern[1]) + } + } + return "" +} + +func (c *Client) persistScan(now inventory.Inventory, delta inventory.Delta, events []journalEvent, scanned map[string]inventory.Line, started time.Time) error { + dir := filepath.Join(c.stateDir, "deltas") + if err := os.MkdirAll(dir, 0o700); err != nil { + return fmt.Errorf("client: create delta directory: %w", withoutPath(err)) + } + id, err := c.nextPassID(started) + if err != nil { + return err + } + path, err := filepath.Abs(filepath.Join(dir, "delta-"+id+".jsonl")) + if err != nil { + return fmt.Errorf("client: resolve delta path: %w", withoutPath(err)) + } + if err := writeJSONL(path, func(enc *json.Encoder) error { return inventory.WriteDelta(enc, delta) }); err != nil { + return err + } + if c.scanHook != nil { + if err := c.scanHook("delta"); err != nil { + return err + } + } + for i := range events { + events[i].PassID = id + } + if err := c.writeEvents(events); err != nil { + return err + } + if c.scanHook != nil { + if err := c.scanHook("journal"); err != nil { + return err + } + } + if err := c.commitScan(now, id, started); err != nil { + return err + } + return c.applyCommittedScan(id, path, started, scanned, events) +} + +func (c *Client) applyCommittedScan(id, path string, started time.Time, scanned map[string]inventory.Line, events []journalEvent) error { + old := c.scanID + c.scanID, c.newestDelta, c.scanStarted, c.scanned = id, path, started, scanned + c.committed[id] = true + for _, event := range events { + c.applyEvent(event) + } + if c.scanHook != nil { + if err := c.scanHook("commit"); err != nil { + return err + } + } + if err := c.publishCurrentScan(id); err != nil { + return err + } + if old != "" { + if err := os.Remove(filepath.Join(c.stateDir, "scan-"+old+".jsonl")); err != nil { + return fmt.Errorf("client: remove old scan: %w", withoutPath(err)) + } + } + return nil +} + +func (c *Client) commitScan(now inventory.Inventory, id string, started time.Time) error { + state := scanState{ID: id, Prev: c.scanID, Started: started} + if err := writeJSONL(filepath.Join(c.stateDir, "scan-"+id+".jsonl"), func(enc *json.Encoder) error { + for _, line := range now.Lines { + if err := enc.Encode(line); err != nil { + return err + } + } + return nil + }); err != nil { + return err + } + if err := writeJSONL(filepath.Join(c.stateDir, "scan-state-"+id+".json"), func(enc *json.Encoder) error { return enc.Encode(state) }); err != nil { + return err + } + return writeJSONL(filepath.Join(c.stateDir, "scan-state.json"), func(enc *json.Encoder) error { return enc.Encode(state) }) +} + +func (c *Client) publishCurrentScan(id string) (resultErr error) { + if c.readOnly { + return nil + } + file, err := os.CreateTemp(c.stateDir, ".current-*") + if err != nil { + return fmt.Errorf("client: create current scan link: %w", withoutPath(err)) + } + temp := file.Name() + if err := file.Close(); err != nil { + return fmt.Errorf("client: close current scan link: %w", withoutPath(err)) + } + if err := os.Remove(temp); err != nil { //nolint:gosec // G703: temp is a name os.CreateTemp just made in the operator-configured stateDir. + return fmt.Errorf("client: prepare current scan link: %w", withoutPath(err)) + } + if err := os.Link(filepath.Join(c.stateDir, "scan-"+id+".jsonl"), temp); err != nil { + return fmt.Errorf("client: link current scan: %w", withoutPath(err)) + } + defer func() { + if err := os.Remove(temp); err != nil && !errors.Is(err, os.ErrNotExist) { //nolint:gosec // G703: temp is a name os.CreateTemp just made in the operator-configured stateDir. + resultErr = errors.Join(resultErr, fmt.Errorf("client: remove current scan link: %w", withoutPath(err))) + } + }() + if err := os.Rename(temp, filepath.Join(c.stateDir, "scan-current.jsonl")); err != nil { //nolint:gosec // G703: temp is the os.CreateTemp name in stateDir; the target is the fixed name under the operator-configured stateDir. + return fmt.Errorf("client: publish current scan: %w", withoutPath(err)) + } + return syncDir(c.stateDir) +} + +func writeJSONL(path string, write func(*json.Encoder) error) (resultErr error) { + dir := filepath.Dir(path) + file, err := os.CreateTemp(dir, ".scan-*") + if err != nil { + return fmt.Errorf("client: create scan file: %w", withoutPath(err)) + } + temp := file.Name() + defer func() { + if removeErr := os.Remove(temp); removeErr != nil && !errors.Is(removeErr, os.ErrNotExist) { + resultErr = errors.Join(resultErr, fmt.Errorf("client: remove temporary scan file: %w", withoutPath(removeErr))) + } + }() + if err := write(json.NewEncoder(file)); err != nil { + return errors.Join(fmt.Errorf("client: write scan file: %w", withoutPath(err)), withoutPath(file.Close())) + } + if err := file.Sync(); err != nil { + return errors.Join(fmt.Errorf("client: sync scan file: %w", withoutPath(err)), withoutPath(file.Close())) + } + if err := file.Close(); err != nil { + return fmt.Errorf("client: close scan file: %w", withoutPath(err)) + } + if err := os.Rename(temp, path); err != nil { + return fmt.Errorf("client: rename scan file: %w", withoutPath(err)) + } + return syncDir(dir) +} diff --git a/tools/transcript-archive/internal/client/scan_files_test.go b/tools/transcript-archive/internal/client/scan_files_test.go new file mode 100644 index 000000000..9504001ad --- /dev/null +++ b/tools/transcript-archive/internal/client/scan_files_test.go @@ -0,0 +1,385 @@ +package client + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/inventory" + "github.com/oklog/ulid/v2" +) + +func TestScanPersistsAndReplaysNewestDelta(t *testing.T) { + repo := filepath.Join(t.TempDir(), "repo") + c, _, state := openTestClient(t, repo) + line := inventory.Line{Path: "first", Type: "file", Size: 1} + if err := c.Scan(t.Context(), inventory.Inventory{Lines: []inventory.Line{line}}, inventory.Delta{Added: []inventory.Line{line}}); err != nil { + t.Fatal(err) + } + first := c.newestDelta + if err := c.Scan(t.Context(), inventory.Inventory{Lines: []inventory.Line{line}}, inventory.Delta{}); err != nil { + t.Fatal(err) + } + for _, path := range []string{filepath.Join(state, "scan-current.jsonl"), first, c.newestDelta} { + info, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm() != 0o600 { + t.Fatalf("%s mode = %o, want 600", path, info.Mode().Perm()) + } + } + if filepath.Base(first) >= filepath.Base(c.newestDelta) { + t.Fatalf("delta sequence did not increase: %s then %s", first, c.newestDelta) + } + reopened, err := Open(state, RepoRef{Scope: "k3s-test-one", Repository: repo}, &fakeEscrow{}, WithScratch(t.TempDir())) + if err != nil { + t.Fatal(err) + } + if reopened.newestDelta != c.newestDelta { + t.Fatalf("replayed delta = %q, want %q", reopened.newestDelta, c.newestDelta) + } +} + +func TestScanDeltaIDsFollowClockAndStayOrdered(t *testing.T) { + start := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + now := start + clock := WithClock(func() time.Time { return now }) + repo := filepath.Join(t.TempDir(), "repo") + c, _, state := openTestClient(t, repo, clock) + line := inventory.Line{Path: "first", Type: "file", Size: 1} + var deltas []string + scan := func(client *Client) { + t.Helper() + if err := client.Scan(t.Context(), inventory.Inventory{Lines: []inventory.Line{line}}, inventory.Delta{}); err != nil { + t.Fatal(err) + } + deltas = append(deltas, client.newestDelta) + } + passTime := func(delta string) uint64 { + t.Helper() + id, err := ulid.Parse(strings.ToUpper(strings.TrimSuffix(strings.TrimPrefix(filepath.Base(delta), "delta-"), ".jsonl"))) + if err != nil { + t.Fatal(err) + } + return id.Time() + } + for range 20 { + scan(c) + } + for _, delta := range deltas { + if got, want := passTime(delta), ulid.Timestamp(start); got != want { + t.Fatalf("pass time of %s = %d, want injected clock %d", delta, got, want) + } + } + reopened, err := Open(state, RepoRef{Scope: "k3s-test-one", Repository: repo}, &fakeEscrow{}, WithScratch(t.TempDir()), clock) + if err != nil { + t.Fatal(err) + } + scan(reopened) + now = start.Add(-time.Minute) + scan(reopened) + again, err := Open(state, RepoRef{Scope: "k3s-test-one", Repository: repo}, &fakeEscrow{}, WithScratch(t.TempDir()), clock) + if err != nil { + t.Fatal(err) + } + scan(again) + for i := 1; i < len(deltas); i++ { + if filepath.Base(deltas[i-1]) >= filepath.Base(deltas[i]) { + t.Fatalf("delta %d = %s does not follow %s", i, deltas[i], deltas[i-1]) + } + } +} + +func TestScanAfterJournalCrashDoesNotReusePassID(t *testing.T) { + start := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + clock := WithClock(func() time.Time { return start }) + repo := filepath.Join(t.TempDir(), "repo") + c, _, state := openTestClient(t, repo, clock) + if err := c.Scan(t.Context(), inventory.Inventory{}, inventory.Delta{}); err != nil { + t.Fatal(err) + } + stop := errors.New("crash at journal") + c.scanHook = func(point string) error { + if point == "journal" { + return stop + } + return nil + } + a := inventory.Line{Path: "a", Type: "file", Size: 1} + b := inventory.Line{Path: "b", Type: "file", Size: 7} + if err := c.Scan(t.Context(), inventory.Inventory{Lines: []inventory.Line{a, b}}, inventory.Delta{Added: []inventory.Line{a, b}}); !errors.Is(err, stop) { + t.Fatalf("crashed scan: %v", err) + } + reopen := func() *Client { + t.Helper() + client, err := Open(state, RepoRef{Scope: "k3s-test-one", Repository: repo}, &fakeEscrow{}, WithScratch(t.TempDir()), clock) + if err != nil { + t.Fatal(err) + } + return client + } + if deltas := deltaFiles(t, state); len(deltas) != 2 || !slices.Contains(deltas, c.newestDelta) { + t.Fatalf("after crash deltas = %v, want the committed delta and one orphan", deltas) + } + c = reopen() + if deltas := deltaFiles(t, state); len(deltas) != 1 || !slices.Contains(deltas, c.newestDelta) { + t.Fatalf("after first reopen deltas = %v, want only the committed delta", deltas) + } + c = reopen() + if _, bytes := c.Pending(); bytes != 0 { + t.Fatalf("uncommitted pending after crash: %d", bytes) + } + realLine := inventory.Line{Path: "a", Type: "file", Size: 3} + if err := c.Scan(t.Context(), inventory.Inventory{Lines: []inventory.Line{realLine}}, inventory.Delta{Changed: []inventory.Line{realLine}}); err != nil { + t.Fatal(err) + } + c = reopen() + if _, bytes := c.Pending(); bytes != realLine.Size { + t.Fatalf("pending bytes = %d, want %d: crashed scan events were replayed", bytes, realLine.Size) + } +} + +// deltaFiles lists every delta file under the state directory, committed or orphaned. +func deltaFiles(t *testing.T, state string) []string { + t.Helper() + matches, err := filepath.Glob(filepath.Join(state, "deltas", "delta-*.jsonl")) + if err != nil { + t.Fatal(err) + } + return matches +} + +func TestPassRequiresScan(t *testing.T) { + c, _, _ := openTestClient(t, filepath.Join(t.TempDir(), "repo")) + if _, err := c.Pass(t.Context(), nil, nil); !errors.Is(err, ErrNoScan) { + t.Fatalf("pass error = %v, want ErrNoScan", err) + } +} + +func TestPassEmptyListBacksUpDelta(t *testing.T) { + localRestic(t) + c, _, _ := openTestClient(t, filepath.Join(t.TempDir(), "repo")) + if err := c.Scan(t.Context(), inventory.Inventory{}, inventory.Delta{}); err != nil { + t.Fatal(err) + } + outcome, err := c.Pass(t.Context(), nil, nil) + if err != nil || outcome.Kind != Acked || outcome.SnapshotID == "" { + t.Fatalf("pass = %#v, %v", outcome, err) + } + output, err := c.runJSON(t.Context(), append(c.commonArgs("ls", false), outcome.SnapshotID)...) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(output), filepath.Base(c.newestDelta)) { + t.Fatalf("snapshot does not contain delta: %s", output) + } +} + +func TestScanPassIdentitySurvivesRestart(t *testing.T) { + localRestic(t) + repo := filepath.Join(t.TempDir(), "repo") + c, _, state := openTestClient(t, repo) + for range 2 { + if err := c.Scan(t.Context(), inventory.Inventory{}, inventory.Delta{}); err != nil { + t.Fatal(err) + } + } + id := strings.TrimSuffix(strings.TrimPrefix(filepath.Base(c.newestDelta), "delta-"), ".jsonl") + c, err := Open(state, RepoRef{Scope: "k3s-test-one", Repository: repo}, &fakeEscrow{}, WithScratch(t.TempDir())) + if err != nil { + t.Fatal(err) + } + outcome, err := c.Pass(t.Context(), nil, nil) + if err != nil || outcome.PassID != id { + t.Fatalf("pass = %#v, %v; want id %s", outcome, err, id) + } + entries, err := os.ReadDir(filepath.Join(state, "deltas")) + if err != nil || len(entries) != 2 { + t.Fatalf("deltas = %v, %v", entries, err) + } +} + +func TestOpenRemovesOrphansWithoutHead(t *testing.T) { + repo := filepath.Join(t.TempDir(), "repo") + _, _, state := openTestClient(t, repo) + if err := os.MkdirAll(filepath.Join(state, "deltas"), 0o700); err != nil { + t.Fatal(err) + } + for _, name := range []string{"scan-orphan.jsonl", "scan-state-orphan.json", "deltas/delta-orphan.jsonl"} { + if err := os.WriteFile(filepath.Join(state, name), []byte("orphan"), 0o600); err != nil { + t.Fatal(err) + } + } + if _, err := Open(state, RepoRef{Scope: "k3s-test-one", Repository: repo}, &fakeEscrow{}, WithScratch(t.TempDir())); err != nil { + t.Fatal(err) + } + for _, name := range []string{"scan-orphan.jsonl", "scan-state-orphan.json", "deltas/delta-orphan.jsonl"} { + if _, err := os.Stat(filepath.Join(state, name)); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("orphan %s remains: %v", name, err) + } + } +} + +func TestOpenRebuildsCurrentScan(t *testing.T) { + repo := filepath.Join(t.TempDir(), "repo") + c, _, state := openTestClient(t, repo) + if err := c.Scan(t.Context(), inventory.Inventory{}, inventory.Delta{}); err != nil { + t.Fatal(err) + } + if err := os.Remove(filepath.Join(state, "scan-current.jsonl")); err != nil { + t.Fatal(err) + } + if _, err := Open(state, RepoRef{Scope: "k3s-test-one", Repository: repo}, &fakeEscrow{}, WithScratch(t.TempDir())); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(state, "scan-current.jsonl")); err != nil { + t.Fatal(err) + } +} + +func TestScanCommitInterruption(t *testing.T) { + for _, point := range []string{"delta", "journal", "commit"} { + t.Run(point, func(t *testing.T) { + checkScanCommitInterruption(t, point) + }) + } +} + +func checkScanCommitInterruption(t *testing.T, point string) { + t.Helper() + repo := filepath.Join(t.TempDir(), "repo") + c, _, state := openTestClient(t, repo) + path := filepath.Join(t.TempDir(), "source") + line := writeVersion(t, path, "data", "normal") + stop := errors.New("interrupted") + c.scanHook = func(at string) error { + if at == point { + return stop + } + return nil + } + if err := c.Scan(t.Context(), inventory.Inventory{Lines: []inventory.Line{line}}, inventory.Delta{Added: []inventory.Line{line}}); !errors.Is(err, stop) { + t.Fatalf("scan: %v", err) + } + c = reopenTestClient(t, state, repo) + if point != "commit" { + if _, bytes := c.Pending(); bytes != 0 { + t.Fatalf("uncommitted pending: %d", bytes) + } + if err := c.Scan(t.Context(), inventory.Inventory{Lines: []inventory.Line{line}}, inventory.Delta{Added: []inventory.Line{line}}); err != nil { + t.Fatal(err) + } + } + if oldest, bytes := c.Pending(); oldest.IsZero() || bytes != line.Size { + t.Fatalf("pending: %v/%d", oldest, bytes) + } + id := c.scanID + outcome := ackFiles(t, c, path) + if outcome.PassID != id { + t.Fatalf("pass id %s, want %s", outcome.PassID, id) + } +} + +func TestScanDeltaSummaryCounts(t *testing.T) { + c, _, _ := openTestClient(t, filepath.Join(t.TempDir(), "repo")) + line := inventory.Line{Path: "a", Type: "file"} + delta := inventory.Delta{Added: []inventory.Line{line}, Changed: []inventory.Line{line, line}, Removed: []inventory.Line{line, line, line}} + if err := c.Scan(t.Context(), inventory.Inventory{}, delta); err != nil { + t.Fatal(err) + } + data, err := os.ReadFile(c.newestDelta) + if err != nil { + t.Fatal(err) + } + rows := strings.Split(strings.TrimSpace(string(data)), "\n") + var summary inventory.DeltaRow + if err := json.Unmarshal([]byte(rows[len(rows)-1]), &summary); err != nil { + t.Fatal(err) + } + if summary.Event != "summary" || summary.Added != 1 || summary.Changed != 2 || summary.Removed != 3 { + t.Fatalf("summary: %#v", summary) + } +} + +func TestScanRemovedPendingIsVanished(t *testing.T) { + c, _, state := openTestClient(t, filepath.Join(t.TempDir(), "repo")) + line := writeVersion(t, filepath.Join(t.TempDir(), "removed"), "data", "normal") + scanLines(t, c, line) + if err := os.Remove(line.Path); err != nil { + t.Fatal(err) + } + if err := c.Scan(t.Context(), inventory.Inventory{}, inventory.Delta{Removed: []inventory.Line{line}}); err != nil { + t.Fatal(err) + } + if !journalHas(t, state, "vanished", line.Path) || journalHas(t, state, "pending-cleared", line.Path) { + t.Fatal("removed pending path was not journaled vanished") + } + if oldest, size := c.Pending(); !oldest.IsZero() || size != 0 { + t.Fatalf("pending: %v/%d", oldest, size) + } +} + +func TestScanPassScale(t *testing.T) { + if testing.Short() { + t.Skip("scale test") + } + c, _, state := openTestClient(t, filepath.Join(t.TempDir(), "repo")) + root := t.TempDir() + lines := make([]inventory.Line, 10000) + for i := range lines { + path := filepath.Join(root, fmt.Sprintf("file-%05d", i)) + lines[i] = writeVersion(t, path, "initial", "normal") + } + for i := range 1000 { + changed := make([]inventory.Line, 3) + paths := make([]string, 3) + for j := range changed { + index := (i*3 + j) % len(lines) + lines[index] = writeVersion(t, lines[index].Path, fmt.Sprintf("version-%d", i), "normal") + changed[j], paths[j] = lines[index], lines[index].Path + } + if err := c.Scan(t.Context(), inventory.Inventory{Lines: lines}, inventory.Delta{Changed: changed}); err != nil { + t.Fatal(err) + } + if err := c.appendEvent(journalEvent{Event: eventPassStart, PassID: c.scanID, Paths: paths}); err != nil { + t.Fatal(err) + } + if err := c.appendEvent(journalEvent{Event: eventPassAcked, PassID: c.scanID}); err != nil { + t.Fatal(err) + } + } + assertScaleFiles(t, state) +} + +func assertScaleFiles(t *testing.T, state string) { + t.Helper() + entries, err := os.ReadDir(filepath.Join(state, "deltas")) + if err != nil || len(entries) != 1000 { + t.Fatalf("deltas: %d %v", len(entries), err) + } + total := 0 + for _, entry := range entries { + data, err := os.ReadFile(filepath.Join(state, "deltas", entry.Name())) + if err != nil { + t.Fatal(err) + } + total += strings.Count(string(data), "\n") + } + if total >= 2*1000*3 { + t.Fatalf("delta lines: %d", total) + } + journal, err := os.Stat(filepath.Join(state, "journal.jsonl")) + if err != nil || journal.Size() > 6_000_000 { + t.Fatalf("journal: %v %v", journal, err) + } + if _, err := os.Stat(filepath.Join(state, "scan-current.jsonl")); err != nil { + t.Fatal(err) + } +} diff --git a/tools/transcript-archive/internal/config/config.go b/tools/transcript-archive/internal/config/config.go new file mode 100644 index 000000000..3976cb22a --- /dev/null +++ b/tools/transcript-archive/internal/config/config.go @@ -0,0 +1,74 @@ +package config + +import ( + _ "embed" + "fmt" + "os" + + "cuelang.org/go/cue" + "cuelang.org/go/cue/cuecontext" +) + +// schemaSource is the CUE schema every archive config is validated against. It ships inside the binary. +// +//go:embed schema.cue +var schemaSource []byte + +// Config holds host walk sets loaded from CUE. +type Config struct { + hosts map[string]Walk +} + +// Load reads and validates host walk configuration against the embedded schema. +func Load(path string) (Config, error) { + data, err := os.ReadFile(path) //nolint:gosec // Path is the operator-supplied config file. + if err != nil { + return Config{}, fmt.Errorf("read archive config: %w", err) + } + ctx := cuecontext.New() + schema := ctx.CompileBytes(schemaSource) + if err := schema.Err(); err != nil { + return Config{}, fmt.Errorf("compile archive schema: %w", err) + } + schemaHosts := schema.LookupPath(cue.ParsePath("hosts")) + dataValue := ctx.CompileBytes(data) + if err := dataValue.Err(); err != nil { + return Config{}, fmt.Errorf("compile archive config: %w", err) + } + value := schemaHosts.Unify(dataValue.LookupPath(cue.ParsePath("hosts"))) + if err := value.Validate(cue.Concrete(true)); err != nil { + return Config{}, fmt.Errorf("validate archive config: %w", err) + } + var decoded struct { + Hosts map[string]struct { + State string `json:"state"` + Sources []Source `json:"sources"` + Watch []string `json:"watch"` + Exclude []Exclusion `json:"exclude"` + FinalOnly []string `json:"finalOnly"` + } `json:"hosts"` + } + if err := value.Decode(&decoded.Hosts); err != nil { + return Config{}, fmt.Errorf("decode archive config: %w", err) + } + hosts := make(map[string]Walk, len(decoded.Hosts)) + for name, host := range decoded.Hosts { + hosts[name] = Walk{ + State: host.State, + Sources: host.Sources, + Watch: host.Watch, + Exclude: host.Exclude, + FinalOnly: host.FinalOnly, + } + } + return Config{hosts: hosts}, nil +} + +// Walk returns the configured source roots and watch set for a host. +func (c Config) Walk(host string) (Walk, error) { + walk, ok := c.hosts[host] + if !ok { + return Walk{}, fmt.Errorf("unknown archive host %q", host) + } + return walk, nil +} diff --git a/tools/transcript-archive/internal/config/config_test.go b/tools/transcript-archive/internal/config/config_test.go new file mode 100644 index 000000000..f015550a1 --- /dev/null +++ b/tools/transcript-archive/internal/config/config_test.go @@ -0,0 +1,106 @@ +package config + +import ( + "os" + "path/filepath" + "testing" +) + +// fixtureConfig is the synthetic archive config under testdata/. +const fixtureConfig = "../../testdata/archive.cue" + +func TestLoadAndWalk(t *testing.T) { + t.Parallel() + loaded, err := Load(fixtureConfig) + if err != nil { + t.Fatal(err) + } + if _, err := loaded.Walk("example-host"); err != nil { + t.Fatalf("example-host is missing: %v", err) + } + configPath := writeConfigFile(t, `package archive +hosts: fixture: { + state: "unmeasured" + sources: [{name: "sessions", path: "sessions"}] + watch: [".omp"] + exclude: [] + finalOnly: [] +} +`) + loaded, err = Load(configPath) + if err != nil { + t.Fatal(err) + } + walk, err := loaded.Walk("fixture") + if err != nil { + t.Fatal(err) + } + if len(walk.Sources) != 1 || walk.Sources[0].Name != "sessions" || len(walk.Watch) != 1 { + t.Fatalf("Walk fixture = %#v", walk) + } + if _, err := loaded.Walk("missing"); err == nil { + t.Fatal("unknown host accepted") + } +} + +func TestLoadRejectsSchemaViolation(t *testing.T) { + t.Parallel() + configPath := writeConfigFile(t, `package archive +hosts: fixture: { + state: "unmeasured" + sources: [{name: "sessions"}] + watch: [] + exclude: [] + finalOnly: [] +} +`) + if _, err := Load(configPath); err == nil { + t.Fatal("host missing required source path accepted") + } +} + +func TestLoadRejectsHostWithoutState(t *testing.T) { + t.Parallel() + configPath := writeConfigFile(t, `package archive +hosts: fixture: { + sources: [{name: "sessions", path: "sessions"}] + watch: [] + exclude: [] + finalOnly: [] +} +`) + if _, err := Load(configPath); err == nil { + t.Fatal("host without state accepted") + } +} + +func TestFixtureHostsCarryState(t *testing.T) { + t.Parallel() + loaded, err := Load(fixtureConfig) + if err != nil { + t.Fatal(err) + } + for host, want := range map[string]string{ + "example-host": "unmeasured", + "example-empty": "empty", + } { + walk, err := loaded.Walk(host) + if err != nil { + t.Fatalf("host %s: %v", host, err) + } + if walk.State != want { + t.Errorf("host %s state = %q, want %q", host, walk.State, want) + } + } +} + +// writeConfigFile writes content as an archive config in a temp directory. +// Load validates against the schema embedded in the package, so no sibling schema is written. +func writeConfigFile(t *testing.T, content string) string { + t.Helper() + path := filepath.Join(t.TempDir(), "archive.cue") + if err := os.WriteFile(path, []byte(content), 0o600); err != nil { + t.Fatal(err) + } + return path +} diff --git a/tools/transcript-archive/internal/config/schema.cue b/tools/transcript-archive/internal/config/schema.cue new file mode 100644 index 000000000..abc5a9d6a --- /dev/null +++ b/tools/transcript-archive/internal/config/schema.cue @@ -0,0 +1,20 @@ +package archive + +#Source: { + name: string + path: string +} + +#Exclusion: { + path: string +} + +#Host: { + state: "measured" | "unmeasured" | "empty" + sources: [...#Source] + watch: [...string] + exclude: [...#Exclusion] + finalOnly: [...string] +} + +hosts: [string]: #Host diff --git a/tools/transcript-archive/internal/config/walk.go b/tools/transcript-archive/internal/config/walk.go new file mode 100644 index 000000000..fb23cd4e4 --- /dev/null +++ b/tools/transcript-archive/internal/config/walk.go @@ -0,0 +1,22 @@ +package config + +// Walk describes the filesystem roots used for one inventory pass. +type Walk struct { + State string `json:"state"` + Root string `json:"root"` + Sources []Source `json:"sources"` + Watch []string `json:"watch"` + Exclude []Exclusion `json:"exclude"` + FinalOnly []string `json:"finalOnly"` +} + +// Source names a source root relative to Root. +type Source struct { + Name string `json:"name"` + Path string `json:"path"` +} + +// Exclusion is a root-relative path or glob excluded from the walk. +type Exclusion struct { + Path string `json:"path"` +} diff --git a/tools/transcript-archive/internal/coverage/coverage.go b/tools/transcript-archive/internal/coverage/coverage.go new file mode 100644 index 000000000..d69ec965d --- /dev/null +++ b/tools/transcript-archive/internal/coverage/coverage.go @@ -0,0 +1,361 @@ +package coverage + +import ( + "bufio" + "encoding/json" + "io" + "path/filepath" + "slices" + "sort" + "strings" + + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/inventory" +) + +// FileDigest holds the complete file hash and digests for recorded prefixes. +type FileDigest struct { + SHA256 [32]byte `json:"sha256"` + Prefixes map[int64][32]byte `json:"prefixes"` +} + +// HistoryEntry identifies a prior snapshot that holds an earlier file version. +type HistoryEntry struct { + SnapshotID string `json:"snapshotId"` + Path string `json:"path"` + Size int64 `json:"size"` + SHA256 [32]byte `json:"sha256"` +} + +// SnapshotListing lists the paths and SHA-256 values present in one snapshot. +type SnapshotListing struct { + SnapshotID string `json:"snapshotId"` + PassID string `json:"passId,omitempty"` + Outcome string `json:"outcome"` + PathsOnly bool `json:"pathsOnly,omitempty"` + Files map[string][32]byte `json:"files"` + // StateFiles are the archive's own state files (deltas, journal) that the snapshot may hold. + StateFiles map[string]struct{} `json:"-"` +} + +// Report contains the results of forward, backward and loss checks. +type Report struct { + Missing []string `json:"missing"` + Extra []string `json:"extra"` + Unexplained []string `json:"unexplained"` + Truncated []string `json:"truncated"` + Rewritten []string `json:"rewritten"` + HashMismatch []string `json:"hashMismatch"` + History []HistoryEntry `json:"history"` + Vanished int `json:"vanished"` + Pass bool `json:"pass"` +} + +type versionKey struct { + path string + digest [32]byte +} + +type versions struct { + current map[string]inventory.Line + needed map[versionKey]inventory.Line + held map[versionKey]int + final map[string]inventory.Line + baseline map[string]inventory.Line + snap SnapshotListing + digests map[string]FileDigest + chained bool +} + +// Delta identifies the pass associated with a streamed scan delta. +type Delta struct { + PassID string + R io.Reader +} + +// Check compares inventories, streamed scan deltas and snapshot contents. +func Check(final, baseline inventory.Inventory, deltas []Delta, chained bool, snap SnapshotListing, digests map[string]FileDigest, history []SnapshotListing, vanished []string) Report { + report := Report{ + Missing: []string{}, Extra: []string{}, Unexplained: []string{}, + Truncated: []string{}, Rewritten: []string{}, HashMismatch: []string{}, + History: []HistoryEntry{}, + } + vanishedSet := make(map[string]struct{}, len(vanished)) + for _, path := range vanished { + vanishedSet[path] = struct{}{} + } + report.Vanished = len(vanishedSet) + + snap.Files = cleanSnapshotPaths(snap.Files) + history = slices.Clone(history) + for i := range history { + history[i].Files = cleanSnapshotPaths(history[i].Files) + } + finalFiles := fileMap(final) + baselineFiles := fileMap(baseline) + checkSnapshot(&report, finalFiles, baselineFiles, chained, snap, digests) + + state := versions{current: fileMap(baseline), needed: make(map[versionKey]inventory.Line), held: make(map[versionKey]int), final: finalFiles, baseline: baselineFiles, snap: snap, digests: digests, chained: chained} + for _, line := range baseline.Lines { + state.remember(line) + } + for _, delta := range deltas { + if delta.PassID == "" || delta.R == nil { + appendUnique(&report.Unexplained, "invalid-delta") + continue + } + if err := replayDelta(delta.R, &state); err != nil { + appendUnique(&report.Unexplained, "invalid-delta") + continue + } + state.recordPass(delta.PassID, history) + } + state.checkNeeded(&report, history, vanishedSet) + for _, item := range final.Errors { + appendUnique(&report.Unexplained, item.Path) + } + for _, item := range baseline.Errors { + appendUnique(&report.Unexplained, item.Path) + } + sortReport(&report) + report.Pass = reportIsEmpty(report) + return report +} + +func (state *versions) checkNeeded(report *Report, history []SnapshotListing, vanished map[string]struct{}) { + deletedHeld := make(map[string]versionKey) + for key, index := range state.held { + if _, present := state.final[key.path]; present { + continue + } + old, exists := deletedHeld[key.path] + if !exists || index < state.held[old] { + deletedHeld[key.path] = key + } + } + for key, line := range state.needed { + if credited, ok := deletedHeld[key.path]; ok { + if key == credited { + appendHistory(report, HistoryEntry{SnapshotID: history[state.held[key]].SnapshotID, Path: key.path, Size: line.Size, SHA256: key.digest}) + } + continue + } + if err := checkVersion(line, report, state.final, state.baseline, state.chained, state.snap, state.digests, history, vanished, state.held, key); err != nil { + appendUnique(&report.Unexplained, "invalid-delta") + } + } +} + +func checkSnapshot(report *Report, finalFiles, baselineFiles map[string]inventory.Line, chained bool, snap SnapshotListing, digests map[string]FileDigest) { + for path, file := range finalFiles { + if file.Class != "normal" || pathInState(snap, path) { + continue + } + old, existed := baselineFiles[path] + if chained && existed && sameLine(old, file) { + continue + } + archived, ok := snap.Files[path] + if !ok { + appendUnique(&report.Missing, path) + } else if archived != file.SHA256 { + appendUnique(&report.HashMismatch, path) + } + if digest, ok := digests[path]; ok && archived != digest.SHA256 { + appendUnique(&report.HashMismatch, path) + } + } + for path := range snap.Files { + if _, ok := finalFiles[path]; !ok && !pathInState(snap, path) && !isMaterializedPath(path) && !isDeletedBaseline(path, baselineFiles) { + appendUnique(&report.Extra, path) + } + } +} + +func replayDelta(reader io.Reader, state *versions) error { + scanner := bufio.NewScanner(reader) + scanner.Buffer(make([]byte, 64*1024), 4*1024*1024) + for scanner.Scan() { + var row inventory.DeltaRow + if err := json.Unmarshal(scanner.Bytes(), &row); err != nil { + return err + } + switch row.Event { + case "summary": + if row.Line != nil { + return io.ErrUnexpectedEOF + } + case "added", "changed", "removed": + if row.Line == nil || row.Line.Path == "" { + return io.ErrUnexpectedEOF + } + if row.Event == "removed" { + delete(state.current, row.Line.Path) + continue + } + state.current[row.Line.Path] = *row.Line + state.remember(*row.Line) + default: + return io.ErrUnexpectedEOF + } + } + return scanner.Err() +} + +func (state *versions) remember(line inventory.Line) { + if line.Class != "normal" { + return + } + if archived, ok := state.snap.Files[line.Path]; ok && archived == line.SHA256 { + return + } + if final, ok := state.final[line.Path]; ok && (final.SHA256 == line.SHA256 || extends(final, line, state.digests[line.Path])) { + return + } + if base, ok := state.baseline[line.Path]; state.chained && ok && sameLine(line, base) { + return + } + state.needed[versionKey{line.Path, line.SHA256}] = line +} + +func (state *versions) recordPass(pass string, history []SnapshotListing) { + for index, listing := range history { + if listing.PassID != pass || !listing.PathsOnly || (listing.Outcome != "pass-acked" && listing.Outcome != "pass-incomplete" && listing.Outcome != "pass-stored") { + continue + } + for path := range listing.Files { + line, ok := state.current[path] + if !ok { + continue + } + key := versionKey{path, line.SHA256} + if _, needed := state.needed[key]; !needed { + continue + } + if old, exists := state.held[key]; !exists || index < old { + state.held[key] = index + } + } + } +} + +func checkVersion(line inventory.Line, report *Report, final map[string]inventory.Line, baseline map[string]inventory.Line, chained bool, snap SnapshotListing, digests map[string]FileDigest, history []SnapshotListing, vanished map[string]struct{}, held map[versionKey]int, key versionKey) error { + if line.Path == "" || line.Class == "final-only" { + return nil + } + if line.Path == "invalid-delta" { + return io.ErrUnexpectedEOF + } + if archived, ok := snap.Files[line.Path]; ok && archived == line.SHA256 { + return nil + } + current, exists := final[line.Path] + if exists && (current.SHA256 == line.SHA256 || extends(current, line, digests[line.Path])) { + return nil + } + if old, ok := baseline[line.Path]; chained && ok && sameLine(line, old) { + return nil + } + if index, ok := held[key]; ok { + appendHistory(report, HistoryEntry{SnapshotID: history[index].SnapshotID, Path: line.Path, Size: line.Size, SHA256: line.SHA256}) + return nil + } + if _, gone := vanished[line.Path]; gone { + return nil + } + if !exists { + appendUnique(&report.Unexplained, line.Path) + return nil + } + if current.Size < line.Size { + appendUnique(&report.Truncated, line.Path) + return nil + } + appendUnique(&report.Rewritten, line.Path) + return nil +} + +func extends(current, earlier inventory.Line, digest FileDigest) bool { + if current.Size < earlier.Size { + return false + } + if current.SHA256 == earlier.SHA256 { + return true + } + prefix, ok := digest.Prefixes[earlier.Size] + return ok && prefix == earlier.SHA256 +} + +func appendHistory(report *Report, entry HistoryEntry) { + for index := range report.History { + if report.History[index].Path == entry.Path && report.History[index].SHA256 == entry.SHA256 { + report.History[index] = entry + return + } + } + report.History = append(report.History, entry) +} + +func fileMap(inv inventory.Inventory) map[string]inventory.Line { + files := make(map[string]inventory.Line, len(inv.Lines)) + for _, line := range inv.Lines { + if line.Type != "directory" && line.Type != "other" { + files[line.Path] = line + } + } + return files +} + +func sameLine(left, right inventory.Line) bool { + return left.Path == right.Path && left.Type == right.Type && left.Size == right.Size && left.SHA256 == right.SHA256 +} + +func appendUnique(paths *[]string, path string) { + if slices.Contains(*paths, path) { + return + } + *paths = append(*paths, path) +} + +func sortReport(report *Report) { + sort.Strings(report.Missing) + sort.Strings(report.Extra) + sort.Strings(report.Unexplained) + sort.Strings(report.Truncated) + sort.Strings(report.Rewritten) + sort.Strings(report.HashMismatch) + sort.Slice(report.History, func(i, j int) bool { + if report.History[i].Path != report.History[j].Path { + return report.History[i].Path < report.History[j].Path + } + return report.History[i].SnapshotID < report.History[j].SnapshotID + }) +} + +func reportIsEmpty(report Report) bool { + return len(report.Missing) == 0 && len(report.Extra) == 0 && len(report.Unexplained) == 0 && + len(report.Truncated) == 0 && len(report.Rewritten) == 0 && len(report.HashMismatch) == 0 +} + +func cleanSnapshotPaths(files map[string][32]byte) map[string][32]byte { + cleaned := make(map[string][32]byte, len(files)) + for path, digest := range files { + cleaned[filepath.ToSlash(filepath.Clean(path))] = digest + } + return cleaned +} + +// pathInState reports whether path is one of the state files coverage was given; only those are exempt. +func pathInState(snap SnapshotListing, path string) bool { + _, ok := snap.StateFiles[filepath.ToSlash(filepath.Clean(path))] + return ok +} + +func isMaterializedPath(path string) bool { + base := path[strings.LastIndexByte(path, '/')+1:] + return base == "config.yml" || base == "models.yml" || base == "gc.lock" || strings.HasSuffix(base, ".pid") || strings.Contains(base, ".pid.") +} + +func isDeletedBaseline(path string, baseline map[string]inventory.Line) bool { + _, exists := baseline[path] + return exists +} diff --git a/tools/transcript-archive/internal/coverage/coverage_test.go b/tools/transcript-archive/internal/coverage/coverage_test.go new file mode 100644 index 000000000..25db29f15 --- /dev/null +++ b/tools/transcript-archive/internal/coverage/coverage_test.go @@ -0,0 +1,442 @@ +package coverage + +import ( + "crypto/sha256" + "encoding/json" + "fmt" + "io" + "maps" + "runtime" + "slices" + "strconv" + "strings" + "testing" + + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/inventory" +) + +func TestCheckHistoryCandidates(t *testing.T) { + old := invLine("/file", 3, sha256.Sum256([]byte("old"))) + changed := invLine("/file", 3, sha256.Sum256([]byte("new"))) + history := []SnapshotListing{{SnapshotID: "newest", PassID: "one", Outcome: "pass-stored", PathsOnly: true, Files: map[string][32]byte{"/file": {}}}, {SnapshotID: "older", PassID: "one", Outcome: "pass-acked", PathsOnly: true, Files: map[string][32]byte{"/file": {}}}} + report := Check(inventory.Inventory{Lines: []inventory.Line{changed}}, inventory.Inventory{}, []Delta{{PassID: "one", R: strings.NewReader(lineJSON(t, old))}}, false, SnapshotListing{Files: map[string][32]byte{"/file": changed.SHA256}}, nil, history, nil) + if !report.Pass || len(report.History) != 1 || report.History[0].SnapshotID != "newest" || report.History[0].SHA256 != old.SHA256 || report.History[0].Size != old.Size { + t.Fatalf("history candidates: %#v", report) + } +} + +func TestCheckDeltaIdentity(t *testing.T) { + line := invLine("/file", 3, sha256.Sum256([]byte("old"))) + history := []SnapshotListing{{SnapshotID: "s1", PassID: "one", Outcome: "pass-acked", PathsOnly: true, Files: map[string][32]byte{line.Path: {}}}} + report := Check(inventory.Inventory{}, inventory.Inventory{}, []Delta{{PassID: "one", R: strings.NewReader(lineJSON(t, line))}}, false, SnapshotListing{}, nil, history, nil) + if !report.Pass || len(report.History) != 1 { + t.Fatalf("explicit pass identity: %#v", report) + } + report = Check(inventory.Inventory{}, inventory.Inventory{}, []Delta{{R: strings.NewReader(lineJSON(t, line))}}, false, SnapshotListing{}, nil, nil, nil) + if !slices.Contains(report.Unexplained, "invalid-delta") { + t.Fatalf("missing pass identity accepted: %#v", report) + } +} + +func TestCheckDeletedAfterFailedPass(t *testing.T) { + first := invLine("/file", 3, sha256.Sum256([]byte("one"))) + second := invLine("/file", 3, sha256.Sum256([]byte("two"))) + history := []SnapshotListing{{SnapshotID: "s2", PassID: "two", Outcome: "pass-acked", PathsOnly: true, Files: map[string][32]byte{"/file": {}}}} + removed, err := json.Marshal(inventory.DeltaRow{Event: "removed", Line: &second}) + if err != nil { + t.Fatal(err) + } + deltas := []Delta{{PassID: "one", R: strings.NewReader(lineJSON(t, first))}, {PassID: "two", R: strings.NewReader(lineJSON(t, second))}, {PassID: "three", R: strings.NewReader(string(removed))}} + report := Check(inventory.Inventory{}, inventory.Inventory{}, deltas, false, SnapshotListing{}, nil, history, nil) + if !report.Pass || len(report.History) != 1 || report.History[0].SnapshotID != "s2" || report.History[0].SHA256 != second.SHA256 { + t.Fatalf("deleted path history: %#v", report) + } +} + +func TestCheckPresentStillRequiresEveryVersion(t *testing.T) { + first := invLine("/file", 3, sha256.Sum256([]byte("one"))) + second := invLine("/file", 3, sha256.Sum256([]byte("two"))) + final := invLine("/file", 5, sha256.Sum256([]byte("three"))) + history := []SnapshotListing{{SnapshotID: "s2", PassID: "two", Outcome: "pass-acked", PathsOnly: true, Files: map[string][32]byte{first.Path: {}}}} + deltas := []Delta{{PassID: "one", R: strings.NewReader(lineJSON(t, first))}, {PassID: "two", R: strings.NewReader(lineJSON(t, second))}} + report := Check(inventory.Inventory{Lines: []inventory.Line{final}}, inventory.Inventory{}, deltas, false, SnapshotListing{Files: map[string][32]byte{final.Path: final.SHA256}}, nil, history, nil) + if report.Pass || !slices.Contains(report.Rewritten, first.Path) { + t.Fatalf("uncredited present version accepted: %#v", report) + } +} + +func TestCheckHistoryExactReplay(t *testing.T) { + first := invLine("/file", 3, sha256.Sum256([]byte("one"))) + second := invLine("/file", 3, sha256.Sum256([]byte("two"))) + history := []SnapshotListing{ + {SnapshotID: "s2", PassID: "two", Outcome: "pass-acked", PathsOnly: true, Files: map[string][32]byte{"/file": {}}}, + {SnapshotID: "s1", PassID: "one", Outcome: "pass-acked", PathsOnly: true, Files: map[string][32]byte{"/file": {}}}, + } + deltas := []Delta{{PassID: "one", R: strings.NewReader(lineJSON(t, first))}, {PassID: "two", R: strings.NewReader(lineJSON(t, second))}} + report := Check(inventory.Inventory{}, inventory.Inventory{}, deltas, false, SnapshotListing{}, nil, history, nil) + if !report.Pass || len(report.History) != 1 || report.History[0].SHA256 != second.SHA256 || report.History[0].SnapshotID != "s2" { + t.Fatalf("history: %#v", report) + } +} + +func TestCheckDoesNotMutateHistory(t *testing.T) { + history := []SnapshotListing{{Files: map[string][32]byte{"/a/../file": {1}}}} + Check(inventory.Inventory{}, inventory.Inventory{}, nil, false, SnapshotListing{}, nil, history, nil) + if _, ok := history[0].Files["/a/../file"]; !ok { + t.Fatalf("history mutated: %#v", history) + } +} + +func TestCheckAbsoluteSnapshotPathsAndBookkeeping(t *testing.T) { + line := invLine("/seat/data/file", 4, sha256.Sum256([]byte("data"))) + state := "/state/deltas/1.jsonl" + files := map[string][32]byte{ + "/seat/data/../data/file": line.SHA256, + state: {}, + } + report := Check(inventory.Inventory{Lines: []inventory.Line{line}}, inventory.Inventory{}, nil, false, SnapshotListing{Files: files, StateFiles: map[string]struct{}{state: {}}}, nil, nil, nil) + if !report.Pass { + t.Fatalf("coverage = %#v", report) + } +} + +// A transcript under a nested .example/archive is ordinary data: missing from the snapshot fails coverage. +func TestCheckNestedArchiveIsNotExempt(t *testing.T) { + line := invLine("/workspace/u/.example/agents/seat/.example/archive/id/session.jsonl", 4, sha256.Sum256([]byte("data"))) + report := Check(inventory.Inventory{Lines: []inventory.Line{line}}, inventory.Inventory{}, nil, false, SnapshotListing{Files: map[string][32]byte{}}, nil, nil, nil) + if report.Pass || !slices.Contains(report.Missing, line.Path) { + t.Fatalf("nested archive transcript exempted: %#v", report) + } +} + +func TestCheckClientDeltaLostVersion(t *testing.T) { + line := invLine("lost", 4, sha256.Sum256([]byte("lost"))) + row, err := json.Marshal(struct { + Event string `json:"event"` + Line inventory.Line `json:"line"` + }{Event: "added", Line: line}) + if err != nil { + t.Fatal(err) + } + report := Check(inventory.Inventory{}, inventory.Inventory{}, []Delta{{PassID: "test", R: strings.NewReader(string(row))}}, false, SnapshotListing{}, nil, nil, nil) + if !slices.Contains(report.Unexplained, line.Path) { + t.Fatalf("lost delta version was not reported: %#v", report) + } +} + +func TestCheckRejectsUnknownDeltaRow(t *testing.T) { + report := Check(inventory.Inventory{}, inventory.Inventory{}, []Delta{{PassID: "test", R: strings.NewReader(`{"event":"unknown"}`)}}, false, SnapshotListing{}, nil, nil, nil) + if !slices.Contains(report.Unexplained, "invalid-delta") { + t.Fatalf("unknown delta row was accepted: %#v", report) + } +} + +func TestCheckDeletedBaselineLoss(t *testing.T) { + base := invLine("lost", 4, sha256.Sum256([]byte("base"))) + report := Check(inventory.Inventory{}, inventory.Inventory{Lines: []inventory.Line{base}}, nil, false, SnapshotListing{}, nil, nil, nil) + if !slices.Contains(report.Unexplained, base.Path) { + t.Fatalf("deleted baseline was not reported: %#v", report) + } +} + +func TestCheckChangedBaselineLoss(t *testing.T) { + base := invLine("file", 8, sha256.Sum256([]byte("original"))) + for _, tc := range []struct { + name string + size int64 + }{{"truncated", 2}, {"rewritten", 8}} { + t.Run(tc.name, func(t *testing.T) { + final := invLine("file", tc.size, sha256.Sum256([]byte(tc.name))) + report := Check(inventory.Inventory{Lines: []inventory.Line{final}}, inventory.Inventory{Lines: []inventory.Line{base}}, nil, false, SnapshotListing{Files: map[string][32]byte{"file": final.SHA256}}, nil, nil, nil) + if tc.name == "truncated" && !slices.Contains(report.Truncated, "file") || tc.name == "rewritten" && !slices.Contains(report.Rewritten, "file") { + t.Fatalf("loss not classified: %#v", report) + } + }) + } +} + +func TestCheckEqualHashVersion(t *testing.T) { + line := invLine("file", 4, sha256.Sum256([]byte("same"))) + report := Check(inventory.Inventory{Lines: []inventory.Line{line}}, inventory.Inventory{}, []Delta{{PassID: "test", R: strings.NewReader(lineJSON(t, line))}}, false, SnapshotListing{Files: map[string][32]byte{line.Path: line.SHA256}}, nil, nil, nil) + if !report.Pass { + t.Fatalf("equal final hash was rejected: %#v", report) + } +} + +func TestCheckGrowingFile(t *testing.T) { + t.Parallel() + first := sha256.Sum256([]byte("first")) + secondBytes := []byte("first and longer") + second := sha256.Sum256(secondBytes) + prefix := sha256.Sum256([]byte("first")) + baseline := invLine("sessions/a.jsonl", 5, first) + final := invLine("sessions/a.jsonl", int64(len(secondBytes)), second) + report := Check( + inventory.Inventory{Lines: []inventory.Line{final}}, + inventory.Inventory{Lines: []inventory.Line{baseline}}, + []Delta{{PassID: "test", R: strings.NewReader(lineJSON(t, final))}}, + false, + SnapshotListing{Files: map[string][32]byte{final.Path: second}}, + map[string]FileDigest{final.Path: {SHA256: second, Prefixes: map[int64][32]byte{5: prefix}}}, + nil, + nil, + ) + if !report.Pass { + t.Fatalf("growing append-only file should pass: %#v", report) + } +} + +func TestCheckFailureClassification(t *testing.T) { + t.Parallel() + old := sha256.Sum256([]byte("original")) + oldLine := invLine("sessions/a.jsonl", 8, old) + cases := []struct { + name string + final []inventory.Line + delta []inventory.Line + digests map[string]FileDigest + snapshot SnapshotListing + vanished []string + wantBucket string + }{ + { + name: "truncated", + final: []inventory.Line{invLine(oldLine.Path, 4, sha256.Sum256([]byte("less")))}, + delta: []inventory.Line{oldLine}, + wantBucket: "truncated", + }, + { + name: "rewritten", + final: []inventory.Line{invLine(oldLine.Path, 8, sha256.Sum256([]byte("rewritten")))}, + delta: []inventory.Line{oldLine}, + wantBucket: "rewritten", + }, + { + name: "unexplained missing scan version", + final: []inventory.Line{}, + delta: []inventory.Line{oldLine}, + wantBucket: "unexplained", + }, + { + name: "vanished", + final: []inventory.Line{}, + delta: []inventory.Line{oldLine}, + vanished: []string{oldLine.Path}, + wantBucket: "pass", + }, + { + name: "snapshot digest mismatch", + final: []inventory.Line{oldLine}, + delta: []inventory.Line{oldLine}, + snapshot: SnapshotListing{Files: map[string][32]byte{oldLine.Path: sha256.Sum256([]byte("wrong"))}}, + wantBucket: "hashMismatch", + }, + } + for _, test := range cases { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + var deltaReader io.Reader + if len(test.delta) > 0 { + deltaReader = strings.NewReader(lineJSON(t, test.delta[0])) + } + report := Check(inventory.Inventory{Lines: test.final}, inventory.Inventory{Lines: []inventory.Line{oldLine}}, []Delta{{PassID: "test", R: deltaReader}}, false, test.snapshot, test.digests, nil, test.vanished) + assertFailureBucket(t, report, test.wantBucket, oldLine.Path) + }) + } +} + +func assertFailureBucket(t *testing.T, report Report, bucket, path string) { + t.Helper() + if bucket == "pass" { + if !report.Pass || report.Vanished != 1 { + t.Fatalf("vanished report = %#v", report) + } + return + } + if report.Pass { + t.Fatalf("expected %s failure: %#v", bucket, report) + } + if !bucketHas(report, bucket, path) { + t.Fatalf("%s missing from report: %#v", bucket, report) + } +} + +func TestCheckBackwardAndHeldHistory(t *testing.T) { + t.Parallel() + deleted := invLine("sessions/deleted.jsonl", 4, sha256.Sum256([]byte("gone"))) + finalLine := invLine("sessions/final.jsonl", 5, sha256.Sum256([]byte("final"))) + report := Check( + inventory.Inventory{Lines: []inventory.Line{finalLine}}, + inventory.Inventory{Lines: []inventory.Line{deleted}}, + []Delta{{PassID: "test", R: strings.NewReader(lineJSON(t, deleted))}}, + false, + SnapshotListing{Files: map[string][32]byte{finalLine.Path: finalLine.SHA256}}, + map[string]FileDigest{finalLine.Path: {SHA256: finalLine.SHA256}}, + []SnapshotListing{{SnapshotID: "stored-id", PassID: "test", Outcome: "pass-stored", PathsOnly: true, Files: map[string][32]byte{deleted.Path: {}}}}, + nil, + ) + if !report.Pass || len(report.History) != 1 || report.History[0].SnapshotID != "stored-id" { + t.Fatalf("stored snapshot history = %#v", report) + } + + extra := invLine("stale", 1, sha256.Sum256([]byte("x"))) + report = Check( + inventory.Inventory{Lines: []inventory.Line{finalLine}}, inventory.Inventory{}, nil, false, + SnapshotListing{Files: map[string][32]byte{extra.Path: extra.SHA256}}, + map[string]FileDigest{extra.Path: {SHA256: extra.SHA256}}, nil, nil, + ) + if report.Pass || len(report.Extra) != 1 || len(report.Missing) != 1 { + t.Fatalf("backward/forward report = %#v", report) + } +} + +func TestCheckSeatDelta(t *testing.T) { + t.Parallel() + baselineLines := make([]inventory.Line, 100) + finalLines := make([]inventory.Line, 100, 103) + files := make(map[string][32]byte, 5) + for index := range baselineLines { + path := fmt.Sprintf("file-%03d", index) + digest := sha256.Sum256([]byte(fmt.Sprintf("baseline-%d", index))) + baselineLines[index] = invLine(path, 10, digest) + finalLines[index] = baselineLines[index] + } + for index := range 3 { + line := invLine(fmt.Sprintf("added-%d", index), 10, sha256.Sum256([]byte(fmt.Sprintf("added-%d", index)))) + finalLines = append(finalLines, line) + files[line.Path] = line.SHA256 + } + for index := range 2 { + path := fmt.Sprintf("file-%03d", index) + line := invLine(path, 11, sha256.Sum256([]byte(fmt.Sprintf("changed-%d", index)))) + finalLines[index] = line + files[line.Path] = line.SHA256 + } + deltaLines := append([]inventory.Line(nil), finalLines[100:]...) + deltaLines = append(deltaLines, finalLines[:2]...) + reader := strings.NewReader(strings.Join(marshalLines(t, deltaLines), "\n")) + report := Check(inventory.Inventory{Lines: finalLines}, inventory.Inventory{Lines: baselineLines}, []Delta{{PassID: "test", R: reader}}, true, SnapshotListing{Files: files}, digestMap(finalLines), nil, nil) + if !report.Pass || len(files) != 5 { + t.Fatalf("seat delta checked %d files: %#v", len(files), report) + } + missingFiles := maps.Clone(files) + delete(missingFiles, finalLines[0].Path) + report = Check(inventory.Inventory{Lines: finalLines}, inventory.Inventory{Lines: baselineLines}, nil, true, SnapshotListing{Files: missingFiles}, digestMap(finalLines), nil, nil) + if !slices.Contains(report.Missing, finalLines[0].Path) { + t.Fatalf("missing rewritten file not reported: %#v", report) + } + + finalWithout := append([]inventory.Line(nil), finalLines[:99]...) + finalWithout = append(finalWithout, finalLines[99:]...) + finalWithout = append(finalWithout[:99], finalWithout[100:]...) + report = Check(inventory.Inventory{Lines: finalWithout}, inventory.Inventory{Lines: baselineLines}, nil, true, SnapshotListing{Files: files}, digestMap(finalWithout), nil, nil) + if !report.Pass { + t.Fatalf("unchanged baseline deletion should pass: %#v", report) + } +} + +func TestCheckChainedRevert(t *testing.T) { + t.Parallel() + base := invLine("file", 4, sha256.Sum256([]byte("base"))) + changed := invLine("file", 7, sha256.Sum256([]byte("changed"))) + report := Check( + inventory.Inventory{Lines: []inventory.Line{base}}, + inventory.Inventory{Lines: []inventory.Line{base}}, + []Delta{{PassID: "test", R: strings.NewReader(lineJSON(t, changed))}}, + true, + SnapshotListing{Files: map[string][32]byte{}}, + map[string]FileDigest{}, nil, nil, + ) + if !slices.Contains(report.Truncated, changed.Path) { + t.Fatalf("lost changed version was not reported: %#v", report) + } +} + +func TestCheckScanDeltaMemoryBound(t *testing.T) { + t.Parallel() + const fileCount = 10000 + const passCount = 1000 + baselineLines := make([]inventory.Line, fileCount) + finalLines := make([]inventory.Line, fileCount) + for index := range baselineLines { + line := invLine(fmt.Sprintf("file-%05d", index), 10, sha256.Sum256([]byte(fmt.Sprintf("v0-%d", index)))) + baselineLines[index] = line + finalLines[index] = line + } + readers := make([]Delta, passCount) + for pass := range passCount { + lines := make([]inventory.Line, 3) + for changed := range lines { + index := (pass*3 + changed) % fileCount + line := invLine(baselineLines[index].Path, 11, sha256.Sum256([]byte(fmt.Sprintf("pass-%d-file-%d", pass, index)))) + lines[changed] = line + finalLines[index] = line + } + readers[pass] = Delta{PassID: strconv.Itoa(pass), R: strings.NewReader(strings.Join(marshalLines(t, lines), "\n"))} + } + files := make(map[string][32]byte, fileCount) + for _, line := range finalLines { + files[line.Path] = line.SHA256 + } + runtime.GC() + var before runtime.MemStats + runtime.ReadMemStats(&before) + report := Check(inventory.Inventory{Lines: finalLines}, inventory.Inventory{Lines: baselineLines}, readers, true, SnapshotListing{Files: files}, digestMap(finalLines), nil, nil) + var after runtime.MemStats + runtime.ReadMemStats(&after) + if !report.Pass { + t.Fatalf("scan replay failed: %#v", report) + } + if after.TotalAlloc-before.TotalAlloc > 256*1024*1024 { + t.Fatalf("scan replay allocated %d bytes, exceeds one-walk-set budget", after.TotalAlloc-before.TotalAlloc) + } +} + +func invLine(path string, size int64, digest [32]byte) inventory.Line { + return inventory.Line{Root: "root", Path: path, Type: "file", Record: "tree/root", Class: "normal", Size: size, SHA256: digest} +} + +func lineJSON(t *testing.T, line inventory.Line) string { + t.Helper() + encoded, err := json.Marshal(inventory.DeltaRow{Event: "changed", Line: &line}) + if err != nil { + t.Fatal(err) + } + return string(encoded) +} + +func marshalLines(t *testing.T, lines []inventory.Line) []string { + t.Helper() + encoded := make([]string, len(lines)) + for index, line := range lines { + encoded[index] = lineJSON(t, line) + } + return encoded +} + +func digestMap(lines []inventory.Line) map[string]FileDigest { + digests := make(map[string]FileDigest, len(lines)) + for _, line := range lines { + digests[line.Path] = FileDigest{SHA256: line.SHA256} + } + return digests +} + +func bucketHas(report Report, bucket, path string) bool { + var paths []string + switch bucket { + case "missing": + paths = report.Missing + case "extra": + paths = report.Extra + case "unexplained": + paths = report.Unexplained + case "truncated": + paths = report.Truncated + case "rewritten": + paths = report.Rewritten + case "hashMismatch": + paths = report.HashMismatch + } + return slices.Contains(paths, path) +} diff --git a/tools/transcript-archive/internal/fence/fence.go b/tools/transcript-archive/internal/fence/fence.go new file mode 100644 index 000000000..706f5698c --- /dev/null +++ b/tools/transcript-archive/internal/fence/fence.go @@ -0,0 +1,160 @@ +package fence + +import ( + "context" + "errors" + "fmt" + "os" + "os/exec" //nolint:depguard // Fence verifies the installed OMP version before taking its locks. + "path/filepath" + "slices" + "strings" + "time" +) + +const ( + // OMPVersion is the `omp --version` string the fence accepts. It must match the + // pinned oh-my-pi fork release that both flake locks pin. + OMPVersion = "omp/18.22.2-rigel.1" + lockPollInterval = 200 * time.Millisecond +) + +// Options configures the gc lock fence. +type Options struct { + AgentDirs []string + Wait time.Duration +} + +// ExitError carries a process exit code for the CLI integration. +type ExitError struct { + Code int + Message string +} + +func (e *ExitError) Error() string { return e.Message } + +// ExitCode returns the process exit code associated with the failure. +func (e *ExitError) ExitCode() int { return e.Code } + +// Run verifies OMP, locks every requested agent directory, and holds them until ctx ends. +// It returns nil when ctx ends while every lock is held, and an error when ctx +// ends first. Its locks are released before it returns. +func Run(ctx context.Context, options Options) (runErr error) { + if options.Wait < 0 { + return errors.New("wait duration must not be negative") + } + if err := checkOMPVersion(ctx); err != nil { + return err + } + + agentDirs := cleanAgentDirs(options.AgentDirs) + if len(agentDirs) == 0 { + var err error + agentDirs, err = discoverAgentDirs() + if err != nil { + return err + } + } + agentDirs, err := uniqueAgentDirs(agentDirs) + if err != nil { + return err + } + + deadline := time.Now().Add(options.Wait) + locks := make([]*heldLock, 0, len(agentDirs)) + defer func() { + for _, lock := range slices.Backward(locks) { + runErr = errors.Join(runErr, lock.release()) + } + }() + + for _, agentDir := range agentDirs { + lock, err := acquire(ctx, agentDir, deadline) + if err != nil { + return err + } + locks = append(locks, lock) + } + + <-ctx.Done() + return nil +} + +func checkOMPVersion(ctx context.Context) error { + output, err := exec.CommandContext(ctx, "omp", "--version").Output() + if ctxErr := ctx.Err(); ctxErr != nil { + return fmt.Errorf("check omp version: %w", ctxErr) + } + if err != nil { + return &ExitError{Code: 3, Message: fmt.Sprintf("run omp --version: %v", err)} + } + if strings.TrimSpace(string(output)) != OMPVersion { + return &ExitError{Code: 3, Message: "unsupported omp version"} + } + return nil +} + +func cleanAgentDirs(agentDirs []string) []string { + cleaned := make([]string, 0, len(agentDirs)) + seen := make(map[string]struct{}, len(agentDirs)) + for _, agentDir := range agentDirs { + if agentDir == "" { + continue + } + path := filepath.Clean(agentDir) + if _, ok := seen[path]; ok { + continue + } + seen[path] = struct{}{} + cleaned = append(cleaned, path) + } + return cleaned +} + +func discoverAgentDirs() ([]string, error) { + home, err := os.UserHomeDir() + if err != nil { + return nil, fmt.Errorf("find home directory: %w", err) + } + agentDirs := []string{filepath.Join(home, ".omp", "agent")} + profilesDir := filepath.Join(home, ".omp", "profiles") + profiles, err := os.ReadDir(profilesDir) + if err != nil && !errors.Is(err, os.ErrNotExist) { + return nil, fmt.Errorf("read OMP profiles: %w", err) + } + for _, profile := range profiles { + profilePath := filepath.Join(profilesDir, profile.Name()) + profileInfo, err := os.Stat(profilePath) + if err != nil { + return nil, fmt.Errorf("stat OMP profile: %w", err) + } + if profileInfo.IsDir() { + agentDirs = append(agentDirs, filepath.Join(profilePath, "agent")) + } + } + return cleanAgentDirs(agentDirs), nil +} + +// uniqueAgentDirs keeps the first entry of each directory that several entries +// name, such as a symlink and its target. Each directory is created first so +// os.SameFile has a stat result to compare. Locking one directory twice would +// make the fence wait on its own lock. +func uniqueAgentDirs(agentDirs []string) ([]string, error) { + unique := make([]string, 0, len(agentDirs)) + seen := make([]os.FileInfo, 0, len(agentDirs)) + for _, agentDir := range agentDirs { + if err := os.MkdirAll(agentDir, 0o750); err != nil { + return nil, fmt.Errorf("create agent directory: %w", err) + } + info, err := os.Stat(agentDir) + if err != nil { + return nil, fmt.Errorf("stat agent directory: %w", err) + } + if slices.ContainsFunc(seen, func(previous os.FileInfo) bool { return os.SameFile(previous, info) }) { + continue + } + seen = append(seen, info) + unique = append(unique, agentDir) + } + return unique, nil +} diff --git a/tools/transcript-archive/internal/fence/fence_test.go b/tools/transcript-archive/internal/fence/fence_test.go new file mode 100644 index 000000000..f7cd9b15e --- /dev/null +++ b/tools/transcript-archive/internal/fence/fence_test.go @@ -0,0 +1,378 @@ +package fence + +import ( + "context" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "testing" + "time" +) + +func TestRunFencesOMPBlobGcAndBreaksDeadLock(t *testing.T) { + ompPath := requireOMP(t) + t.Setenv("PATH", filepath.Dir(ompPath)+string(os.PathListSeparator)+os.Getenv("PATH")) + + agentDir := t.TempDir() + blobPath := filepath.Join(agentDir, "blobs", strings.Repeat("a", 64)) + writeTestFile(t, blobPath, []byte("unchanged blob")) + oldTime := time.Now().Add(-10 * time.Minute) + if err := os.Chtimes(blobPath, oldTime, oldTime); err != nil { + t.Fatal("age blob fixture") + } + lockPath := filepath.Join(agentDir, "gc.lock") + if err := os.WriteFile(lockPath, []byte("2147483647\n2026-01-01T00:00:00.000Z\n"), 0o600); err != nil { + t.Fatal("write dead lock fixture") + } + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + runDone := make(chan error, 1) + go func() { + runDone <- Run(ctx, Options{AgentDirs: []string{agentDir}}) + }() + waitForLockPID(t, lockPath) + + lockText, err := os.ReadFile(lockPath) + if err != nil || !strings.HasPrefix(string(lockText), strconv.Itoa(os.Getpid())+"\n") { + cancel() + t.Fatal("fence did not replace the dead-PID lock with its own OMP-format lock") + } + command := exec.CommandContext(t.Context(), "omp", "gc", "--agent-dir", agentDir, "--blobs", "--apply") + output, commandErr := command.CombinedOutput() + if commandErr == nil || !strings.Contains(string(output), "GC already running") { + cancel() + t.Fatal("omp gc did not fail because the fence held its gc lock") + } + blob, err := os.ReadFile(blobPath) + if err != nil || string(blob) != "unchanged blob" { + cancel() + t.Fatal("omp gc changed the fixture blob while the fence was active") + } + + cancel() + if err := <-runDone; err != nil { + t.Fatalf("release fence: %v", err) + } + if _, err := os.Stat(lockPath); !errors.Is(err, os.ErrNotExist) { + t.Fatal("fence left its gc lock behind") + } + + // Control: with the fence released, the same apply must delete the aged blob. + // If it does not, the blob-unchanged check above could not have failed. + control := exec.CommandContext(t.Context(), "omp", "gc", "--agent-dir", agentDir, "--blobs", "--apply") + if output, err := control.CombinedOutput(); err != nil { + t.Fatalf("control omp gc --apply after release: %v\n%s", err, output) + } + if _, err := os.Stat(blobPath); !errors.Is(err, os.ErrNotExist) { + t.Fatal("control omp gc --apply did not delete the aged blob after the fence was released") + } +} + +func TestRunReturnsExitCodeFourForLiveLock(t *testing.T) { + installFakeOMP(t) + agentDir := t.TempDir() + lockPath := filepath.Join(agentDir, "gc.lock") + contents := fmt.Sprintf("%d\n%s\n", os.Getpid(), time.Now().UTC().Format("2006-01-02T15:04:05.000Z")) + if err := os.WriteFile(lockPath, []byte(contents), 0o600); err != nil { + t.Fatal("write live lock fixture") + } + err := Run(t.Context(), Options{AgentDirs: []string{agentDir}, Wait: 25 * time.Millisecond}) + var exitErr *ExitError + if !errors.As(err, &exitErr) || exitErr.ExitCode() != 4 { + t.Fatal("fence did not return exit code 4 for the live lock") + } + if _, err := os.Stat(lockPath); err != nil { + t.Fatal("fence removed a live gc lock") + } +} + +func TestRunReturnsImmediatelyForZeroWait(t *testing.T) { + installFakeOMP(t) + agentDir := t.TempDir() + lockPath := filepath.Join(agentDir, "gc.lock") + if err := os.WriteFile(lockPath, []byte(fmt.Sprintf("%d\n%s\n", os.Getpid(), time.Now().UTC().Format(time.RFC3339Nano))), 0o600); err != nil { + t.Fatal("write live lock fixture") + } + err := Run(t.Context(), Options{AgentDirs: []string{agentDir}, Wait: 0}) + var exitErr *ExitError + if !errors.As(err, &exitErr) || exitErr.ExitCode() != 4 { + t.Fatal("fence did not return exit code 4 for zero wait") + } + // requireKeptLock times acquire alone; timing Run here would also count the fake omp fork. +} + +func TestRunFencesDefaultAndProfileAgentDirs(t *testing.T) { + installFakeOMP(t) + home := t.TempDir() + t.Setenv("HOME", home) + agentDirs := []string{ + filepath.Join(home, ".omp", "agent"), + filepath.Join(home, ".omp", "profiles", "first", "agent"), + filepath.Join(home, ".omp", "profiles", "second", "agent"), + filepath.Join(home, ".omp", "profiles", "linked-profile", "agent"), + } + for _, agentDir := range agentDirs[:3] { + if err := os.MkdirAll(agentDir, 0o700); err != nil { + t.Fatal("create agent directory fixture") + } + } + profilesDir := filepath.Join(home, ".omp", "profiles") + if err := os.MkdirAll(filepath.Join(home, "first-profile-target"), 0o700); err != nil { + t.Fatal("create symlink profile target") + } + if err := os.Symlink(filepath.Join(home, "first-profile-target"), filepath.Join(profilesDir, "linked-profile")); err != nil { + t.Fatal("create symlink profile") + } + if err := os.WriteFile(filepath.Join(profilesDir, "not-a-profile"), []byte("x"), 0o600); err != nil { + t.Fatal("create non-directory profile fixture") + } + + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + runDone := make(chan error, 1) + go func() { + runDone <- Run(ctx, Options{}) + }() + lockPaths := make([]string, 0, len(agentDirs)) + for _, agentDir := range agentDirs { + lockPaths = append(lockPaths, filepath.Join(agentDir, "gc.lock")) + } + waitForLocks(t, lockPaths...) + cancel() + if err := <-runDone; err != nil { + t.Fatalf("release profile fences: %v", err) + } + for _, lockPath := range lockPaths { + if _, err := os.Stat(lockPath); !errors.Is(err, os.ErrNotExist) { + t.Fatal("fence left a profile gc lock behind") + } + } +} + +func TestRunFencesSymlinkedAgentDirOnce(t *testing.T) { + installFakeOMP(t) + root := t.TempDir() + agentDir := filepath.Join(root, "agent") + linkDir := filepath.Join(root, "linked-agent") + if err := os.MkdirAll(agentDir, 0o700); err != nil { + t.Fatal("create agent directory fixture") + } + if err := os.Symlink(agentDir, linkDir); err != nil { + t.Fatal("create symlink to agent directory") + } + + // Wait is zero. Locking the same directory twice would make the second + // acquire see the first hold's live PID and exit 4 at once. + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + runDone := make(chan error, 1) + go func() { + runDone <- Run(ctx, Options{AgentDirs: []string{agentDir, linkDir}}) + }() + waitForLocks(t, filepath.Join(agentDir, "gc.lock")) + cancel() + if err := <-runDone; err != nil { + t.Fatalf("release fence over symlinked agent dir: %v", err) + } + if _, err := os.Stat(filepath.Join(agentDir, "gc.lock")); !errors.Is(err, os.ErrNotExist) { + t.Fatal("fence left its gc lock behind") + } +} + +func TestRunReturnsNilWhenHoldPhaseIsCancelled(t *testing.T) { + installFakeOMP(t) + agentDir := t.TempDir() + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + runDone := make(chan error, 1) + go func() { + runDone <- Run(ctx, Options{AgentDirs: []string{agentDir}}) + }() + waitForLocks(t, filepath.Join(agentDir, "gc.lock")) + cancel() + if err := <-runDone; err != nil { + t.Fatalf("cancel during hold returned %v, want nil (exit 0)", err) + } + if _, err := os.Stat(filepath.Join(agentDir, "gc.lock")); !errors.Is(err, os.ErrNotExist) { + t.Fatal("cancel during hold left the gc lock behind") + } +} + +func TestRunReturnsErrorWhenCancelledDuringAcquire(t *testing.T) { + installFakeOMP(t) + heldDir := t.TempDir() + liveDir := t.TempDir() + livePath := filepath.Join(liveDir, "gc.lock") + writeTestFile(t, livePath, []byte(fmt.Sprintf("%d\n%s\n", os.Getpid(), time.Now().UTC().Format(time.RFC3339Nano)))) + // Run takes heldDir first, so its gc.lock exists before Run reaches liveDir. + // liveDir's lock is live, so Run waits in acquire until ctx is cancelled. + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + runDone := make(chan error, 1) + go func() { + runDone <- Run(ctx, Options{AgentDirs: []string{heldDir, liveDir}, Wait: time.Hour}) + }() + waitForLocks(t, filepath.Join(heldDir, "gc.lock")) + cancel() + if err := <-runDone; !errors.Is(err, context.Canceled) { + t.Fatalf("cancel during acquire returned %v, want a wrapped context.Canceled (non-zero exit)", err) + } + if _, err := os.Stat(filepath.Join(heldDir, "gc.lock")); !errors.Is(err, os.ErrNotExist) { + t.Fatal("cancel during acquire left the already-taken gc lock behind") + } + if _, err := os.Stat(livePath); err != nil { + t.Fatal("cancel during acquire removed a live gc lock") + } +} + +func TestRunReturnsExitCodeThreeForUnsupportedOMPVersion(t *testing.T) { + installFakeOMPVersion(t, "omp/1.0.0") + err := Run(t.Context(), Options{AgentDirs: []string{t.TempDir()}}) + var exitErr *ExitError + if !errors.As(err, &exitErr) || exitErr.ExitCode() != 3 { + t.Fatal("fence did not return exit code 3 for an unsupported OMP version") + } +} + +func TestRunReturnsExitCodeThreeWhenOMPUnavailable(t *testing.T) { + t.Setenv("PATH", t.TempDir()) + err := Run(t.Context(), Options{AgentDirs: []string{t.TempDir()}}) + var exitErr *ExitError + if !errors.As(err, &exitErr) || exitErr.ExitCode() != 3 { + t.Fatal("fence did not return exit code 3 when OMP was unavailable") + } +} + +func TestCheckOMPVersionReturnsContextErrorWhenCancelled(t *testing.T) { + installFakeOMP(t) + ctx, cancel := context.WithCancel(t.Context()) + cancel() + err := checkOMPVersion(ctx) + if !errors.Is(err, context.Canceled) { + t.Fatalf("checkOMPVersion with cancelled ctx = %v, want context.Canceled", err) + } +} + +func installFakeOMP(t *testing.T) { + t.Helper() + installFakeOMPVersion(t, OMPVersion) +} + +func installFakeOMPVersion(t *testing.T, version string) { + t.Helper() + binDir := t.TempDir() + fakeOMP := filepath.Join(binDir, "omp") + script := fmt.Sprintf("#!/bin/sh\nprintf '%%s\\n' '%s'\n", version) + writeTestFile(t, fakeOMP, []byte(script)) + if err := os.Chmod(fakeOMP, 0o700); err != nil { + t.Fatal("make fake OMP executable") + } + t.Setenv("PATH", binDir) +} + +func requireOMP(t *testing.T) string { + t.Helper() + ompPath := os.Getenv("TRANSCRIPT_ARCHIVE_TEST_OMP") + if ompPath == "" { + if os.Getenv("TRANSCRIPT_ARCHIVE_REQUIRE_OMP") != "" { + t.Fatal("OMP integration binary is required but unavailable") + } + t.Skip("OMP integration binary is unavailable") + } + if !filepath.IsAbs(ompPath) { + resolvedPath, err := exec.LookPath(ompPath) + if err != nil { + t.Fatalf("find OMP integration binary: %v", err) + } + ompPath = resolvedPath + } + output, err := exec.Command(ompPath, "--version").Output() + if err != nil { + t.Fatalf("run OMP integration version: %v", err) + } + if strings.TrimSpace(string(output)) != OMPVersion { + t.Fatalf("OMP version = %q, want %q", strings.TrimSpace(string(output)), OMPVersion) + } + t.Setenv("PATH", filepath.Dir(ompPath)+string(os.PathListSeparator)+os.Getenv("PATH")) + return ompPath +} + +func TestShouldBreakLockParsesOMPNumericPrefix(t *testing.T) { + path := filepath.Join(t.TempDir(), "gc.lock") + if err := os.WriteFile(path, nil, 0o600); err != nil { + t.Fatal("create lock stat fixture") + } + info, err := os.Stat(path) + if err != nil { + t.Fatal("stat lock fixture") + } + livePID := strconv.Itoa(os.Getpid()) + for _, lockText := range []string{livePID + "\r\n2026-01-01T00:00:00.000Z\r\n", livePID + "abc\n2026-01-01T00:00:00.000Z\n"} { + snapshot := lockSnapshot{info: info, text: lockText} + if shouldBreakLock(snapshot) { + t.Fatalf("shouldBreakLock(%q) broke a lock with a live PID prefix", lockText) + } + } + deadLock := lockSnapshot{info: info, text: "2147483647abc\n2026-01-01T00:00:00.000Z\n"} + if !shouldBreakLock(deadLock) { + t.Fatal("shouldBreakLock kept a lock with a dead PID prefix") + } +} + +func writeTestFile(t *testing.T, path string, contents []byte) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal("create fixture directory") + } + if err := os.WriteFile(path, contents, 0o600); err != nil { + t.Fatal("write fixture file") + } +} + +func waitForLockPID(t *testing.T, path string) { + t.Helper() + timer := time.NewTimer(5 * time.Second) + defer timer.Stop() + ticker := time.NewTicker(10 * time.Millisecond) + defer ticker.Stop() + for { + contents, err := os.ReadFile(path) + if err == nil && strings.HasPrefix(string(contents), strconv.Itoa(os.Getpid())+"\n") { + return + } + select { + case <-timer.C: + t.Fatal("fence did not write its PID to the gc lock") + case <-ticker.C: + } + } +} + +func waitForLocks(t *testing.T, paths ...string) { + t.Helper() + timer := time.NewTimer(5 * time.Second) + defer timer.Stop() + ticker := time.NewTicker(10 * time.Millisecond) + defer ticker.Stop() + for { + allExist := true + for _, path := range paths { + if _, err := os.Stat(path); err != nil { + allExist = false + break + } + } + if allExist { + return + } + select { + case <-timer.C: + t.Fatal("fence did not acquire all gc locks") + case <-ticker.C: + } + } +} diff --git a/tools/transcript-archive/internal/fence/lock.go b/tools/transcript-archive/internal/fence/lock.go new file mode 100644 index 000000000..b7e01d554 --- /dev/null +++ b/tools/transcript-archive/internal/fence/lock.go @@ -0,0 +1,297 @@ +package fence + +import ( + "context" + "errors" + "fmt" + "io" + "math" + "os" + "path/filepath" + "strconv" + "strings" + "syscall" + "time" +) + +const ( + breakerSuffix = ".break" + writeGrace = 5 * time.Minute +) + +var ( + errLiveLock = errors.New("live gc lock") + errTakeoverInProgress = errors.New("gc lock takeover in progress") +) + +type heldLock struct { + path string + file *os.File +} + +type lockSnapshot struct { + info os.FileInfo + text string +} + +// Lock takes dir's gc.lock (breaking a dead holder) and returns its release; it waits until deadline. +func Lock(ctx context.Context, dir string, deadline time.Time) (func() error, error) { + lock, err := acquire(ctx, dir, deadline) + if err != nil { + return nil, err + } + return lock.release, nil +} + +func acquire(ctx context.Context, agentDir string, deadline time.Time) (*heldLock, error) { + if err := os.MkdirAll(agentDir, 0o750); err != nil { + return nil, fmt.Errorf("create agent directory: %w", err) + } + lockPath := filepath.Join(agentDir, "gc.lock") + for { + if err := ctx.Err(); err != nil { + return nil, notAcquired(agentDir, err) + } + file, err := openExclusive(lockPath) + if err != nil { + return nil, err + } + if file != nil { + if err := writeLock(file); err != nil { + return nil, errors.Join(fmt.Errorf("write gc lock: %w", err), releaseFile(lockPath, file)) + } + return &heldLock{path: lockPath, file: file}, nil + } + + file, err = breakDeadLock(lockPath) + if err == nil && file != nil { + if err := writeLock(file); err != nil { + return nil, errors.Join(fmt.Errorf("write gc lock: %w", err), releaseFile(lockPath, file)) + } + return &heldLock{path: lockPath, file: file}, nil + } + if err != nil && file != nil { + return nil, errors.Join(err, releaseFile(lockPath, file)) + } + if err != nil && !errors.Is(err, errLiveLock) && !errors.Is(err, errTakeoverInProgress) { + return nil, err + } + + if !time.Now().Before(deadline) { + return nil, &ExitError{Code: 4, Message: "a live process still holds " + lockPath} + } + timer := time.NewTimer(lockPollInterval) + select { + case <-ctx.Done(): + timer.Stop() + return nil, notAcquired(agentDir, ctx.Err()) + case <-timer.C: + } + } +} + +// notAcquired reports that ctx ended before agentDir's gc lock was taken. Run +// returns it, so the CLI exits non-zero. A cancel after every lock is held is a +// normal stop and returns nil instead. +func notAcquired(agentDir string, err error) error { + return fmt.Errorf("gc lock in %s not acquired: %w", agentDir, err) +} + +func openExclusive(path string) (*os.File, error) { + file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0o600) //nolint:gosec // The path is gc.lock under the operator-selected agent directory. + if err == nil { + return file, nil + } + if errors.Is(err, os.ErrExist) { + return nil, nil //nolint:nilnil // A lock already exists; the caller checks whether its PID is live. + } + return nil, fmt.Errorf("open gc lock: %w", err) +} + +func writeLock(file *os.File) error { + stamp := time.Now().UTC().Format("2006-01-02T15:04:05.000Z") + contents := fmt.Sprintf("%d\n%s\n", os.Getpid(), stamp) + written, err := io.WriteString(file, contents) + if err != nil { + return err + } + if written != len(contents) { + return io.ErrShortWrite + } + return nil +} + +func breakDeadLock(lockPath string) (result *os.File, runErr error) { + breakerPath := lockPath + breakerSuffix + breaker, err := openBreaker(breakerPath) + if err != nil { + return nil, err + } + if err := writeLock(breaker); err != nil { + return nil, errors.Join(fmt.Errorf("write gc breaker: %w", err), releaseFile(breakerPath, breaker)) + } + defer func() { + if releaseErr := releaseFile(breakerPath, breaker); releaseErr != nil { + runErr = errors.Join(runErr, releaseErr) + } + }() + + file, err := openExclusive(lockPath) + if err != nil { + return nil, err + } + if file != nil { + return file, nil + } + snapshot, err := readLockSnapshot(lockPath) + if err != nil { + return nil, err + } + if snapshot == nil || !shouldBreakLock(*snapshot) || !snapshotStillCurrent(lockPath, *snapshot) { + return nil, errLiveLock + } + if err := os.Remove(lockPath); err != nil && !errors.Is(err, os.ErrNotExist) { + return nil, fmt.Errorf("remove stale gc lock: %w", err) + } + takeover, err := openExclusive(lockPath) + if err != nil { + return nil, err + } + if takeover == nil { + return nil, errLiveLock + } + return takeover, nil +} + +// openBreaker takes the gc.lock.break mutex that serializes takeovers. A stale +// breaker from a crashed takeover is removed and the open is tried once more, +// so a dead gc.lock is not held up for another poll interval. A breaker still +// held after that belongs to a live takeover. +func openBreaker(breakerPath string) (*os.File, error) { + breaker, err := openExclusive(breakerPath) + if err != nil { + return nil, err + } + if breaker != nil { + return breaker, nil + } + snapshot, err := readLockSnapshot(breakerPath) + if err != nil { + return nil, err + } + if snapshot == nil || !shouldBreakLock(*snapshot) || !snapshotStillCurrent(breakerPath, *snapshot) { + return nil, errTakeoverInProgress + } + if err := os.Remove(breakerPath); err != nil && !errors.Is(err, os.ErrNotExist) { + return nil, fmt.Errorf("remove stale gc breaker: %w", err) + } + breaker, err = openExclusive(breakerPath) + if err != nil { + return nil, err + } + if breaker == nil { + return nil, errTakeoverInProgress + } + return breaker, nil +} + +func readLockSnapshot(path string) (*lockSnapshot, error) { + before, err := os.Stat(path) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + return nil, nil //nolint:nilnil // A missing file can be removed by a concurrent lock owner. + } + return nil, fmt.Errorf("stat gc lock: %w", err) + } + contents, err := os.ReadFile(path) //nolint:gosec // The path is the gc.lock entry under the operator-selected agent directory. + if err != nil { + if errors.Is(err, os.ErrNotExist) { + return nil, nil //nolint:nilnil // A missing file can be removed by a concurrent lock owner. + } + return nil, fmt.Errorf("read gc lock: %w", err) + } + after, err := os.Stat(path) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + return nil, nil //nolint:nilnil // A missing file can be removed by a concurrent lock owner. + } + return nil, fmt.Errorf("restat gc lock: %w", err) + } + if !sameLockFile(before, after) { + return nil, nil //nolint:nilnil // The lock changed during the snapshot; retry before deciding to break it. + } + return &lockSnapshot{info: after, text: string(contents)}, nil +} + +func sameLockFile(left, right os.FileInfo) bool { + if !os.SameFile(left, right) || left.Size() != right.Size() || !left.ModTime().Equal(right.ModTime()) { + return false + } + return changeTime(left) == changeTime(right) +} + +func snapshotStillCurrent(path string, snapshot lockSnapshot) bool { + info, err := os.Stat(path) + return err == nil && info != nil && sameLockFile(snapshot.info, info) +} + +func shouldBreakLock(snapshot lockSnapshot) bool { + lines := strings.SplitN(snapshot.text, "\n", 3) + if pid, ok := lockPID(lines[0]); ok { + return !processExists(pid) + } + createdAt := snapshot.info.ModTime() + if len(lines) >= 2 { + if parsedAt, err := time.Parse(time.RFC3339Nano, strings.TrimSpace(lines[1])); err == nil { + createdAt = parsedAt + } + } + return time.Since(createdAt) > writeGrace +} + +// lockPID reads the numeric prefix of a lock's PID line. A PID above +// math.MaxInt32 is returned as is, so processExists treats the lock as live and +// never breaks it. Digits past the range of int64 clamp to MaxInt64 and are +// returned the same way. +func lockPID(line string) (int64, bool) { + text := strings.TrimLeft(line, " \t") + digits := strings.TrimLeft(text, "+-") + end := 0 + for end < len(digits) && digits[end] >= '0' && digits[end] <= '9' { + end++ + } + if end == 0 { + return 0, false + } + pid, err := strconv.ParseInt(text[:len(text)-len(digits)+end], 10, 64) + if (err != nil && !errors.Is(err, strconv.ErrRange)) || pid <= 0 { + return 0, false + } + return pid, true +} + +// processExists reports whether pid names a live process. A PID above +// math.MaxInt32 counts as live without a probe, so syscall.Kill never sees it. +func processExists(pid int64) bool { + if pid > math.MaxInt32 { + return true + } + err := syscall.Kill(int(pid), 0) + return err == nil || (!errors.Is(err, syscall.ESRCH) && !errors.Is(err, syscall.EINVAL)) +} + +func releaseFile(path string, file *os.File) error { + closeErr := file.Close() + removeErr := os.Remove(path) + if errors.Is(removeErr, os.ErrNotExist) { + removeErr = nil + } + return errors.Join(closeErr, removeErr) +} + +func (lock *heldLock) release() error { + if lock == nil || lock.file == nil { + return nil + } + return releaseFile(lock.path, lock.file) +} diff --git a/tools/transcript-archive/internal/fence/lock_darwin.go b/tools/transcript-archive/internal/fence/lock_darwin.go new file mode 100644 index 000000000..51281ea4c --- /dev/null +++ b/tools/transcript-archive/internal/fence/lock_darwin.go @@ -0,0 +1,17 @@ +package fence + +import ( + "os" + "syscall" +) + +// changeTime returns the inode change time in nanoseconds. OMP compares ctime +// as well as size and mtime, so a lock rewritten with its mtime restored still +// counts as changed. os.Stat always reports *syscall.Stat_t on this platform. +func changeTime(info os.FileInfo) int64 { + stat, ok := info.Sys().(*syscall.Stat_t) + if !ok { + return 0 + } + return stat.Ctimespec.Nano() +} diff --git a/tools/transcript-archive/internal/fence/lock_linux.go b/tools/transcript-archive/internal/fence/lock_linux.go new file mode 100644 index 000000000..c2d01154c --- /dev/null +++ b/tools/transcript-archive/internal/fence/lock_linux.go @@ -0,0 +1,17 @@ +package fence + +import ( + "os" + "syscall" +) + +// changeTime returns the inode change time in nanoseconds. OMP compares ctime +// as well as size and mtime, so a lock rewritten with its mtime restored still +// counts as changed. os.Stat always reports *syscall.Stat_t on this platform. +func changeTime(info os.FileInfo) int64 { + stat, ok := info.Sys().(*syscall.Stat_t) + if !ok { + return 0 + } + return stat.Ctim.Nano() +} diff --git a/tools/transcript-archive/internal/fence/lock_other.go b/tools/transcript-archive/internal/fence/lock_other.go new file mode 100644 index 000000000..267829075 --- /dev/null +++ b/tools/transcript-archive/internal/fence/lock_other.go @@ -0,0 +1,9 @@ +//go:build !linux && !darwin + +package fence + +import "os" + +// changeTime reports 0 where this package does not read the change time, so +// sameLockFile compares size and mtime alone, as it did before ctime was checked. +func changeTime(_ os.FileInfo) int64 { return 0 } diff --git a/tools/transcript-archive/internal/fence/lock_test.go b/tools/transcript-archive/internal/fence/lock_test.go new file mode 100644 index 000000000..13599d4cb --- /dev/null +++ b/tools/transcript-archive/internal/fence/lock_test.go @@ -0,0 +1,191 @@ +package fence + +import ( + "errors" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + "time" +) + +const deadPID = "2147483647" + +// ageFile sets path's mtime to age in the past, so writeGrace checks see an old file. +func ageFile(t *testing.T, path string, age time.Duration) { + t.Helper() + old := time.Now().Add(-age) + if err := os.Chtimes(path, old, old); err != nil { + t.Fatalf("age %s: %v", path, err) + } +} + +func releaseTestLock(t *testing.T, lock *heldLock) { + t.Helper() + if err := lock.release(); err != nil { + t.Errorf("release gc lock: %v", err) + } +} + +// requireKeptLock runs acquire with a deadline that has already passed. A lock +// that is kept then surfaces as exit code 4 at once, without any wait. +func requireKeptLock(t *testing.T, agentDir string) { + t.Helper() + started := time.Now() + lock, err := acquire(t.Context(), agentDir, started) + if time.Since(started) >= lockPollInterval { + t.Fatal("acquire waited a poll interval after its deadline had passed") + } + if err == nil { + releaseTestLock(t, lock) + t.Fatal("acquire took a lock that should have been kept") + } + var exitErr *ExitError + if !errors.As(err, &exitErr) || exitErr.ExitCode() != 4 { + t.Fatalf("acquire error = %v, want exit code 4 for a kept lock", err) + } +} + +func TestAcquireTakesLockFromDeadPID(t *testing.T) { + agentDir := t.TempDir() + lockPath := filepath.Join(agentDir, "gc.lock") + writeTestFile(t, lockPath, []byte(deadPID+"\n2026-01-01T00:00:00.000Z\n")) + + lock, err := acquire(t.Context(), agentDir, time.Now()) + if err != nil { + t.Fatalf("acquire over dead-PID lock: %v", err) + } + t.Cleanup(func() { releaseTestLock(t, lock) }) + + contents, err := os.ReadFile(lockPath) + if err != nil { + t.Fatalf("read taken lock: %v", err) + } + if want := strconv.Itoa(os.Getpid()) + "\n"; !strings.HasPrefix(string(contents), want) { + t.Fatalf("lock = %q, want own PID first %q", contents, want) + } +} + +func TestAcquireBreaksStaleBreakerBeforeTakingDeadLock(t *testing.T) { + agentDir := t.TempDir() + lockPath := filepath.Join(agentDir, "gc.lock") + breakerPath := lockPath + breakerSuffix + writeTestFile(t, lockPath, []byte(deadPID+"\n2026-01-01T00:00:00.000Z\n")) + writeTestFile(t, breakerPath, []byte(deadPID+"\n2026-01-01T00:00:00.000Z\n")) + + // The deadline has already passed. Without the stale-breaker retry, acquire + // would return errTakeoverInProgress and exit 4 here instead of taking the lock. + lock, err := acquire(t.Context(), agentDir, time.Now()) + if err != nil { + t.Fatalf("acquire with stale breaker and dead lock: %v", err) + } + t.Cleanup(func() { releaseTestLock(t, lock) }) + if _, err := os.Stat(breakerPath); !errors.Is(err, os.ErrNotExist) { + t.Fatal("acquire left the stale gc breaker behind") + } +} + +func TestAcquireBreaksNoPIDLockOlderThanWriteGrace(t *testing.T) { + agentDir := t.TempDir() + lockPath := filepath.Join(agentDir, "gc.lock") + writeTestFile(t, lockPath, []byte("not a pid\n")) + ageFile(t, lockPath, 2*writeGrace) + + lock, err := acquire(t.Context(), agentDir, time.Now()) + if err != nil { + t.Fatalf("acquire over aged no-PID lock: %v", err) + } + t.Cleanup(func() { releaseTestLock(t, lock) }) +} + +func TestAcquireKeepsNoPIDLockYoungerThanWriteGrace(t *testing.T) { + agentDir := t.TempDir() + lockPath := filepath.Join(agentDir, "gc.lock") + writeTestFile(t, lockPath, []byte("not a pid\n")) + + requireKeptLock(t, agentDir) + if _, err := os.Stat(lockPath); err != nil { + t.Fatal("acquire removed a no-PID lock younger than writeGrace") + } +} + +func TestAcquireKeepsLockWithPIDAboveInt32(t *testing.T) { + agentDir := t.TempDir() + lockPath := filepath.Join(agentDir, "gc.lock") + // 2^31 does not fit pid_t, but the lock still counts as live. The timestamp + // is old on purpose: a timestamp-only judgement would break this lock, so + // only the PID rule keeps it. + stamp := time.Now().Add(-2 * writeGrace).UTC().Format(time.RFC3339Nano) + writeTestFile(t, lockPath, []byte("2147483648\n"+stamp+"\n")) + + requireKeptLock(t, agentDir) + if _, err := os.Stat(lockPath); err != nil { + t.Fatal("acquire broke a lock whose PID exceeds MaxInt32") + } +} + +func TestShouldBreakLockReadsOnlySecondLineTimestamp(t *testing.T) { + path := filepath.Join(t.TempDir(), "gc.lock") + writeTestFile(t, path, nil) + info, err := os.Stat(path) + if err != nil { + t.Fatal("stat lock fixture") + } + // The file mtime is fresh. Line 2 is older than writeGrace, and line 3 is an + // extra line. Only line 2 may decide, so the lock must break. + text := "not a pid\n2026-01-01T00:00:00.000Z\nextra\n" + if !shouldBreakLock(lockSnapshot{info: info, text: text}) { + t.Fatal("shouldBreakLock ignored the stale timestamp on line 2") + } +} + +func TestSameLockFileDetectsChangeTime(t *testing.T) { + path := filepath.Join(t.TempDir(), "gc.lock") + writeTestFile(t, path, []byte("1\n")) + before, err := os.Stat(path) + if err != nil { + t.Fatal("stat lock fixture") + } + if changeTime(before) == 0 { + t.Skip("change time is not readable on this platform") + } + + // Rewrite with the same size and restore the mtime, so size and mtime match + // and only the change time differs. Chtimes also moves ctime, and the kernel + // clock is coarse, so retry at a fixed pace until ctime has moved past before's. + timer := time.NewTimer(5 * time.Second) + defer timer.Stop() + ticker := time.NewTicker(10 * time.Millisecond) + defer ticker.Stop() + var after os.FileInfo + for { + if err := os.WriteFile(path, []byte("2\n"), 0o600); err != nil { + t.Fatal("rewrite lock fixture") + } + if err := os.Chtimes(path, before.ModTime(), before.ModTime()); err != nil { + t.Fatal("restore lock mtime") + } + after, err = os.Stat(path) + if err != nil { + t.Fatal("restat lock fixture") + } + if changeTime(after) != changeTime(before) { + break + } + select { + case <-timer.C: + t.Skip("filesystem change time did not advance; ctime comparison is not observable here") + case <-ticker.C: + } + } + if changeTime(after) == changeTime(before) { + t.Skip("filesystem change time did not advance; ctime comparison is not observable here") + } + if before.Size() != after.Size() || !before.ModTime().Equal(after.ModTime()) { + t.Fatal("fixture did not keep size and mtime, so the ctime check is not isolated") + } + if sameLockFile(before, after) { + t.Fatal("sameLockFile matched a lock whose change time advanced") + } +} diff --git a/tools/transcript-archive/internal/inventory/assign.go b/tools/transcript-archive/internal/inventory/assign.go new file mode 100644 index 000000000..1bf3f690a --- /dev/null +++ b/tools/transcript-archive/internal/inventory/assign.go @@ -0,0 +1,176 @@ +package inventory + +import ( + "bufio" + "fmt" + "os" + "path/filepath" + "regexp" + "slices" + "strings" +) + +var blobPattern = regexp.MustCompile(`blob:sha256:([0-9a-fA-F]{64})`) +var artifactPattern = regexp.MustCompile(`artifact://([0-9]+)`) + +func (s *walkState) assignRecords() { + rootIDs := make(map[string]string) + rootStems := make(map[string]string) + s.indexRootSessions(rootIDs, rootStems) + s.assignSessionRecords(rootIDs, rootStems) +} + +func (s *walkState) indexRootSessions(rootIDs, rootStems map[string]string) { + for _, line := range s.inventory.Lines { + if !isSessionsRoot(s.relative(line.Path)) || !isRootSession(s.relative(line.Path)) { + continue + } + if line.SessionID == "" { + s.inventory.Errors = append(s.inventory.Errors, AssignError{Path: line.Path, Reason: "root session has no session id"}) + continue + } + if previousPath, exists := rootIDs[line.SessionID]; exists { + s.inventory.Errors = append(s.inventory.Errors, AssignError{Path: line.Path, Reason: "duplicate root session id also used by " + previousPath}) + continue + } + rootIDs[line.SessionID] = line.Path + stem := strings.TrimSuffix(filepath.ToSlash(line.Path), filepath.Ext(line.Path)) + rootStems[stem] = "omp-session/" + line.SessionID + } +} + +func (s *walkState) assignSessionRecords(rootIDs, rootStems map[string]string) { + for index := range s.inventory.Lines { + line := &s.inventory.Lines[index] + if !isSessionsRoot(s.relative(line.Path)) { + line.Record = "tree/" + line.Root + continue + } + if isRootSession(s.relative(line.Path)) { + if line.SessionID != "" { + line.Record = "omp-session/" + line.SessionID + } + continue + } + stem, record := longestStem(line.Path, rootStems) + if stem == "" { + line.Record = "tree/unassigned-" + line.Root + } else { + line.Record = record + if line.SessionID != "" && rootIDs[line.SessionID] != "" { + s.inventory.Errors = append(s.inventory.Errors, AssignError{Path: line.Path, Reason: "nested session id matches root session " + rootIDs[line.SessionID]}) + } + } + } +} + +func longestStem(path string, stems map[string]string) (string, string) { + var selected string + var record string + for stem, candidate := range stems { + if strings.HasPrefix(path, stem+"/") && len(stem) > len(selected) { + selected = stem + record = candidate + } + } + return selected, record +} + +func (s *walkState) relative(path string) string { + rel, err := filepath.Rel(s.cfg.Root, path) + if err != nil { + return path + } + return rel +} + +func isSessionsRoot(path string) bool { + return slices.Contains(strings.Split(filepath.ToSlash(path), "/"), "sessions") +} + +func isRootSession(path string) bool { + parts := strings.Split(filepath.ToSlash(path), "/") + for index, part := range parts { + if part == "sessions" { + return len(parts)-index == 3 && strings.HasSuffix(strings.ToLower(parts[len(parts)-1]), ".jsonl") + } + } + return false +} + +func (s *walkState) checkClosure() { + blobFiles := make(map[string]Line) + artifacts := indexArtifacts(s.inventory.Lines) + for _, line := range s.inventory.Lines { + if strings.Contains(filepath.ToSlash(line.Path), "/blobs/") || strings.HasPrefix(filepath.ToSlash(line.Path), "blobs/") { + blobFiles[filepath.Base(line.Path)] = line + } + } + for _, line := range s.inventory.Lines { + s.scanClosureFile(line, blobFiles, artifacts) + } +} + +func (s *walkState) scanClosureFile(line Line, blobs map[string]Line, artifacts map[string]map[string]struct{}) { + if line.Type != "file" || line.Class == "final-only" { + return + } + file, err := os.Open(s.absolute[line.Path]) + if err != nil { + s.inventory.Errors = append(s.inventory.Errors, AssignError{Path: line.Path, Reason: "open file for closure scan"}) + return + } + reader := bufio.NewReader(file) + for { + chunk, readErr := reader.ReadString('\n') + if strings.Contains(chunk, "blob:sha256:") || strings.Contains(chunk, "artifact://") { + s.checkReferences(line, chunk, blobs, artifacts) + } + if readErr != nil { + break + } + } + if err := file.Close(); err != nil { + s.inventory.Errors = append(s.inventory.Errors, AssignError{Path: line.Path, Reason: "close file in closure scan"}) + } +} + +func indexArtifacts(lines []Line) map[string]map[string]struct{} { + artifacts := make(map[string]map[string]struct{}) + for _, line := range lines { + base := filepath.Base(line.Path) + id, _, ok := strings.Cut(base, ".") + if !ok { + continue + } + for dir := filepath.Dir(line.Path); dir != "." && dir != "/"; dir = filepath.Dir(dir) { + key := line.Record + "\x00" + filepath.ToSlash(dir) + if artifacts[key] == nil { + artifacts[key] = make(map[string]struct{}) + } + artifacts[key][id] = struct{}{} + } + } + return artifacts +} + +func (s *walkState) checkReferences(line Line, text string, blobs map[string]Line, artifacts map[string]map[string]struct{}) { + for _, match := range blobPattern.FindAllStringSubmatch(text, -1) { + digest := strings.ToLower(match[1]) + blob, ok := blobs[digest] + if !ok { + s.inventory.Dangling = append(s.inventory.Dangling, Dangling{Path: line.Path, Record: line.Record, Reference: match[0], Reason: "missing"}) + continue + } + if fmt.Sprintf("%x", blob.SHA256) != digest { + s.inventory.Dangling = append(s.inventory.Dangling, Dangling{Path: line.Path, Record: line.Record, Reference: match[0], Reason: "digest-mismatch"}) + } + } + stem := strings.TrimSuffix(filepath.ToSlash(line.Path), filepath.Ext(line.Path)) + for _, match := range artifactPattern.FindAllStringSubmatch(text, -1) { + if _, found := artifacts[line.Record+"\x00"+stem][match[1]]; !found { + s.inventory.Dangling = append(s.inventory.Dangling, Dangling{Path: line.Path, Record: line.Record, Reference: match[0], Reason: "artifact-missing"}) + } + } + +} diff --git a/tools/transcript-archive/internal/inventory/inventory.go b/tools/transcript-archive/internal/inventory/inventory.go new file mode 100644 index 000000000..6cc040ead --- /dev/null +++ b/tools/transcript-archive/internal/inventory/inventory.go @@ -0,0 +1,156 @@ +package inventory + +import ( + "crypto/sha256" + "encoding/binary" + "encoding/json" + "sort" +) + +// Line describes one file in a source walk. +type Line struct { + Root string `json:"root"` + Path string `json:"path"` + Type string `json:"type"` + Record string `json:"record"` + SessionID string `json:"sessionId,omitempty"` + Class string `json:"class"` + LinkTarget string `json:"linkTarget,omitempty"` + Size int64 `json:"size"` + MtimeNs int64 `json:"mtimeNs"` + SHA256 [32]byte `json:"sha256"` +} + +// Dangling records a blob or artifact reference without valid closure. +type Dangling struct { + Path string `json:"path"` + Record string `json:"record"` + Reference string `json:"reference"` + Reason string `json:"reason"` +} + +// Excluded reports aggregate size and count without storing excluded content. +type Excluded struct { + Count int `json:"count"` + Bytes int64 `json:"bytes"` +} + +// AssignError describes a failed record assignment or an unclassified watch file. +type AssignError struct { + Path string `json:"path"` + Reason string `json:"reason"` +} + +// Inventory is a complete result for one walk. +type Inventory struct { + Lines []Line `json:"lines"` + Dangling []Dangling `json:"dangling"` + Excluded []Excluded `json:"excluded"` + OutsideTargets int `json:"outsideTargets"` + Errors []AssignError `json:"errors"` +} + +// Delta contains the file lines added, changed or removed between walks. +type Delta struct { + Added []Line `json:"added"` + Changed []Line `json:"changed"` + Removed []Line `json:"removed"` +} + +// DeltaRow is one change or the counts summary in a scan delta. +type DeltaRow struct { + Event string `json:"event"` + Line *Line `json:"line,omitempty"` + Added int `json:"added,omitempty"` + Changed int `json:"changed,omitempty"` + Removed int `json:"removed,omitempty"` +} + +// WriteDelta encodes a delta in the shared JSONL format. +func WriteDelta(enc *json.Encoder, delta Delta) error { + for _, group := range []struct { + event string + lines []Line + }{{"added", delta.Added}, {"changed", delta.Changed}, {"removed", delta.Removed}} { + for _, line := range group.lines { + if err := enc.Encode(DeltaRow{Event: group.event, Line: &line}); err != nil { + return err + } + } + } + return enc.Encode(DeltaRow{Event: "summary", Added: len(delta.Added), Changed: len(delta.Changed), Removed: len(delta.Removed)}) +} + +// Since returns the current file versions that differ from the baseline. +// MtimeNs is deliberately excluded from the comparison. +func Since(baseline, now Inventory) []Line { + previous := make(map[string]Line, len(baseline.Lines)) + for _, line := range baseline.Lines { + previous[lineKey(line)] = line + } + + changed := make([]Line, 0) + for _, line := range now.Lines { + old, ok := previous[lineKey(line)] + if !ok || !sameContent(old, line) { + changed = append(changed, line) + } + } + sortLines(changed) + return changed +} + +// ContentDigest hashes the sorted file path, type, size and SHA-256 tuples. +// Mtime, exclusions, errors and summary data do not affect the digest. +func ContentDigest(inv Inventory) [32]byte { + lines := append([]Line(nil), inv.Lines...) + sort.Slice(lines, func(i, j int) bool { + if lines[i].Path != lines[j].Path { + return lines[i].Path < lines[j].Path + } + if lines[i].Type != lines[j].Type { + return lines[i].Type < lines[j].Type + } + if lines[i].Size != lines[j].Size { + return lines[i].Size < lines[j].Size + } + return string(lines[i].SHA256[:]) < string(lines[j].SHA256[:]) + }) + + hash := sha256.New() + var number [8]byte + for _, line := range lines { + writeDigestString(hash, line.Path, &number) + writeDigestString(hash, line.Type, &number) + binary.BigEndian.PutUint64(number[:], uint64(line.Size)) //nolint:gosec // Bit-preserving conversion for a digest, not arithmetic. + _, _ = hash.Write(number[:]) + _, _ = hash.Write(line.SHA256[:]) + } + var digest [32]byte + copy(digest[:], hash.Sum(nil)) + return digest +} +func writeDigestString(hash interface { + Write(data []byte) (int, error) +}, value string, number *[8]byte) { + binary.BigEndian.PutUint64(number[:], uint64(len(value))) + _, _ = hash.Write(number[:]) + _, _ = hash.Write([]byte(value)) +} + +func lineKey(line Line) string { + return line.Path +} + +func sameContent(left, right Line) bool { + return left.Path == right.Path && left.Type == right.Type && left.Size == right.Size && left.SHA256 == right.SHA256 +} + +func sortLines(lines []Line) { + sort.Slice(lines, func(i, j int) bool { + if lines[i].Path != lines[j].Path { + return lines[i].Path < lines[j].Path + } + return lines[i].Root < lines[j].Root + }) +} diff --git a/tools/transcript-archive/internal/inventory/json.go b/tools/transcript-archive/internal/inventory/json.go new file mode 100644 index 000000000..4452d84d9 --- /dev/null +++ b/tools/transcript-archive/internal/inventory/json.go @@ -0,0 +1,66 @@ +package inventory + +import ( + "encoding/hex" + "encoding/json" + "errors" + "fmt" +) + +// MarshalJSON writes the inventory line with a hex SHA-256. +func (line Line) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Root string `json:"root"` + Path string `json:"path"` + Type string `json:"type"` + Size int64 `json:"size"` + MtimeNs int64 `json:"mtimeNs"` + SHA256 string `json:"sha256"` + Record string `json:"record"` + SessionID string `json:"sessionId,omitempty"` + Class string `json:"class"` + LinkTarget string `json:"linkTarget,omitempty"` + }{ + Root: line.Root, Path: line.Path, Type: line.Type, Size: line.Size, MtimeNs: line.MtimeNs, + SHA256: hex.EncodeToString(line.SHA256[:]), Record: line.Record, SessionID: line.SessionID, + Class: line.Class, LinkTarget: line.LinkTarget, + }) +} + +func (line *Line) UnmarshalJSON(data []byte) error { + var decoded struct { + Root string `json:"root"` + Path string `json:"path"` + Type string `json:"type"` + Size int64 `json:"size"` + MtimeNs int64 `json:"mtimeNs"` + SHA256 json.RawMessage `json:"sha256"` + Record string `json:"record"` + SessionID string `json:"sessionId"` + Class string `json:"class"` + LinkTarget string `json:"linkTarget"` + } + if err := json.Unmarshal(data, &decoded); err != nil { + return err + } + var digest [32]byte + var encoded string + if err := json.Unmarshal(decoded.SHA256, &encoded); err == nil { + if len(encoded) != 64 { + return errors.New("sha256 must contain 64 hexadecimal characters") + } + if _, err := hex.Decode(digest[:], []byte(encoded)); err != nil { + return fmt.Errorf("decode sha256: %w", err) + } + } else if len(decoded.SHA256) != 0 && string(decoded.SHA256) != "null" { + if err := json.Unmarshal(decoded.SHA256, &digest); err != nil { + return fmt.Errorf("decode sha256: %w", err) + } + } + *line = Line{ + Root: decoded.Root, Path: decoded.Path, Type: decoded.Type, Size: decoded.Size, + MtimeNs: decoded.MtimeNs, SHA256: digest, Record: decoded.Record, SessionID: decoded.SessionID, + Class: decoded.Class, LinkTarget: decoded.LinkTarget, + } + return nil +} diff --git a/tools/transcript-archive/internal/inventory/session.go b/tools/transcript-archive/internal/inventory/session.go new file mode 100644 index 000000000..aae39b058 --- /dev/null +++ b/tools/transcript-archive/internal/inventory/session.go @@ -0,0 +1,51 @@ +package inventory + +import ( + "bufio" + "encoding/json" + "os" + "path/filepath" + "regexp" + "strings" +) + +var sessionIDPattern = regexp.MustCompile(`(?i)^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`) + +type sessionEntry struct { + Session struct { + ID string `json:"id"` + } `json:"session"` +} + +func sessionID(absolutePath, relativePath string) string { + file, err := os.Open(absolutePath) //nolint:gosec // Paths come from the configured walk roots. + if err != nil { + return "" + } + defer func() { + _ = file.Close() + }() + scanner := bufio.NewScanner(file) + scanner.Buffer(make([]byte, 4096), 1024*1024) + for scanner.Scan() { + var entry sessionEntry + if err := json.Unmarshal(scanner.Bytes(), &entry); err != nil { + continue + } + if entry.Session.ID != "" { + return entry.Session.ID + } + var kind struct { + Type string `json:"type"` + ID string `json:"id"` + } + if err := json.Unmarshal(scanner.Bytes(), &kind); err == nil && kind.Type == "session" && kind.ID != "" { + return kind.ID + } + } + stem := strings.TrimSuffix(filepath.Base(relativePath), filepath.Ext(relativePath)) + if sessionIDPattern.MatchString(stem) { + return stem + } + return "" +} diff --git a/tools/transcript-archive/internal/inventory/sources.go b/tools/transcript-archive/internal/inventory/sources.go new file mode 100644 index 000000000..78db88a3d --- /dev/null +++ b/tools/transcript-archive/internal/inventory/sources.go @@ -0,0 +1,59 @@ +package inventory + +import ( + "bufio" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/config" +) + +func (s *walkState) addOutsideTargets(source config.Source, rootPath string) error { + if filepath.Base(source.Path) != "custom-session-files" { + return nil + } + return filepath.WalkDir(rootPath, func(path string, entry os.DirEntry, walkErr error) error { + if walkErr != nil { + return fmt.Errorf("walking custom session markers: %w", walkErr) + } + if entry.IsDir() || entry.Type()&os.ModeSymlink != 0 { + return nil + } + marker, err := os.Open(path) //nolint:gosec // Paths come from the configured walk roots. + if err != nil { + return fmt.Errorf("read custom session marker: %w", err) + } + return scanMarker(marker, s) + }) +} + +func scanMarker(marker *os.File, state *walkState) error { + scanner := bufio.NewScanner(marker) + for scanner.Scan() { + target := strings.TrimSpace(scanner.Text()) + if target == "" || !filepath.IsAbs(target) { + continue + } + if _, err := os.Lstat(target); err != nil { + if errors.Is(err, os.ErrNotExist) { + continue + } + closeErr := marker.Close() + return errors.Join(fmt.Errorf("stat custom session target: %w", err), closeErr) + } + inside, err := filepath.Rel(state.cfg.Root, target) + if err != nil { + closeErr := marker.Close() + return errors.Join(fmt.Errorf("classify custom session target: %w", err), closeErr) + } + if inside == ".." || strings.HasPrefix(inside, ".."+string(filepath.Separator)) { + state.inventory.OutsideTargets++ + } + } + scanErr := scanner.Err() + closeErr := marker.Close() + return errors.Join(scanErr, closeErr) +} diff --git a/tools/transcript-archive/internal/inventory/walk.go b/tools/transcript-archive/internal/inventory/walk.go new file mode 100644 index 000000000..a0c44fb17 --- /dev/null +++ b/tools/transcript-archive/internal/inventory/walk.go @@ -0,0 +1,286 @@ +package inventory + +import ( + "crypto/sha256" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strings" + + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/config" +) + +type walkState struct { + cfg config.Walk + previous map[string]Line + inventory Inventory + stems map[string]string + absolute map[string]string +} + +// Walk scans configured roots without following symlinks and compares file content to previous. +func Walk(cfg config.Walk, previous *Inventory) (Inventory, Delta, error) { + root, err := filepath.Abs(cfg.Root) + if err != nil { + return Inventory{}, Delta{}, fmt.Errorf("inventory: resolve root: %w", err) + } + cfg.Root = root + state := walkState{ + cfg: cfg, + previous: make(map[string]Line), + inventory: Inventory{Lines: []Line{}, Dangling: []Dangling{}, Excluded: []Excluded{}, Errors: []AssignError{}}, + stems: make(map[string]string), + absolute: make(map[string]string), + } + if previous != nil { + for _, line := range previous.Lines { + state.previous[lineKey(line)] = line + } + } + if err := state.walkSources(); err != nil { + return Inventory{}, Delta{}, err + } + state.assignRecords() + state.checkClosure() + sortLines(state.inventory.Lines) + delta := Diff(previous, state.inventory) + return state.inventory, delta, nil +} + +// Diff reports added, changed and removed file versions between two inventories. +func Diff(previous *Inventory, now Inventory) Delta { + delta := Delta{Added: []Line{}, Changed: []Line{}, Removed: []Line{}} + if previous == nil { + delta.Added = append(delta.Added, now.Lines...) + return delta + } + oldLines := make(map[string]Line, len(previous.Lines)) + for _, line := range previous.Lines { + oldLines[lineKey(line)] = line + } + newLines := make(map[string]Line, len(now.Lines)) + for _, line := range now.Lines { + key := lineKey(line) + newLines[key] = line + old, ok := oldLines[key] + if !ok { + delta.Added = append(delta.Added, line) + continue + } + if !sameContent(old, line) { + delta.Changed = append(delta.Changed, line) + } + } + for key, line := range oldLines { + if _, ok := newLines[key]; !ok { + delta.Removed = append(delta.Removed, line) + } + } + sortLines(delta.Added) + sortLines(delta.Changed) + sortLines(delta.Removed) + return delta +} + +func (s *walkState) walkSources() error { + if len(s.cfg.Sources) == 0 { + return errors.New("inventory: no source roots configured") + } + for _, source := range s.cfg.Sources { + pattern, err := s.sourcePath(source.Path) + if err != nil { + return fmt.Errorf("inventory: source %q: %w", source.Name, err) + } + roots, err := filepath.Glob(pattern) + if err != nil { + return fmt.Errorf("inventory: source pattern: %w", err) + } + for _, rootPath := range roots { + if err := s.walkSource(source, rootPath); err != nil { + return err + } + } + } + return s.validateWatchRoots() +} + +func (s *walkState) walkSource(source config.Source, rootPath string) error { + info, err := os.Lstat(rootPath) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + return fmt.Errorf("inventory: source %q: %w", source.Name, err) + } + if err := s.addOutsideTargets(source, rootPath); err != nil { + return err + } + if info.Mode()&os.ModeSymlink != 0 || !info.IsDir() { + relative, err := filepath.Rel(s.cfg.Root, rootPath) + if err != nil { + return fmt.Errorf("relative source path: %w", err) + } + return s.addFile(source.Name, rootPath, filepath.ToSlash(relative), info) + } + return filepath.WalkDir(rootPath, func(path string, entry os.DirEntry, walkErr error) error { + return s.walkSourceEntry(source.Name, rootPath, path, entry, walkErr) + }) +} + +func (s *walkState) walkSourceEntry(source, rootPath, path string, entry os.DirEntry, walkErr error) error { + if walkErr != nil { + return fmt.Errorf("walking source %q: %w", source, walkErr) + } + if path == rootPath { + return nil + } + relative, err := filepath.Rel(s.cfg.Root, path) + if err != nil { + return fmt.Errorf("relative source path: %w", err) + } + relative = filepath.ToSlash(relative) + excluded, err := s.excluded(relative) + if err != nil { + return err + } + if excluded { + if entry.IsDir() && entry.Type()&os.ModeSymlink == 0 { + return filepath.SkipDir + } + return s.addExcluded(relative, path) + } + if entry.IsDir() && entry.Type()&os.ModeSymlink == 0 { + return nil + } + info, err := os.Lstat(path) + if err != nil { + return fmt.Errorf("stat source entry: %w", err) + } + return s.addFile(source, path, relative, info) +} + +func (s *walkState) sourcePath(path string) (string, error) { + return SourcePath(s.cfg, path) +} + +// SourcePath resolves a configured source path (absolute, ~/, or relative to cfg.Root) to its glob pattern. +func SourcePath(cfg config.Walk, path string) (string, error) { + if filepath.IsAbs(path) { + return filepath.Clean(path), nil + } + if strings.HasPrefix(path, "~/") { + home, err := os.UserHomeDir() + if err != nil { + return "", fmt.Errorf("resolve home directory: %w", err) + } + return filepath.Join(home, filepath.FromSlash(path[2:])), nil + } + return filepath.Join(cfg.Root, filepath.FromSlash(path)), nil +} +func (s *walkState) excluded(path string) (bool, error) { + for _, exclusion := range s.cfg.Exclude { + pattern := filepath.ToSlash(exclusion.Path) + matched, err := filepath.Match(pattern, path) + if err != nil { + return false, fmt.Errorf("invalid exclusion pattern: %w", err) + } + underDirectory := strings.HasPrefix(path, strings.TrimSuffix(pattern, "/")+"/") + if matched || underDirectory { + return true, nil + } + } + return false, nil +} + +func (s *walkState) addExcluded(_ string, path string) error { + info, err := os.Lstat(path) + if err != nil { + return fmt.Errorf("stat excluded entry: %w", err) + } + if len(s.inventory.Excluded) == 0 { + s.inventory.Excluded = append(s.inventory.Excluded, Excluded{}) + } + s.inventory.Excluded[0].Count++ + s.inventory.Excluded[0].Bytes += info.Size() + return nil +} + +func (s *walkState) addFile(source, absolutePath, path string, info os.FileInfo) error { + line := Line{ + Root: source, + Path: filepath.ToSlash(filepath.Clean(absolutePath)), + Type: fileType(info.Mode()), + Class: "normal", + Size: info.Size(), + MtimeNs: info.ModTime().UnixNano(), + } + if line.Type == "symlink" { + target, err := os.Readlink(absolutePath) + if err != nil { + return fmt.Errorf("read symlink: %w", err) + } + line.LinkTarget = target + line.SHA256 = sha256.Sum256([]byte(target)) + } else { + if isFinalOnly(path, s.cfg.FinalOnly) { + line.Class = "final-only" + } + if previous, ok := s.previous[lineKey(line)]; ok && previous.Size == line.Size && previous.MtimeNs == line.MtimeNs { + line.SHA256 = previous.SHA256 + } else { + hash, err := hashFile(absolutePath) + if err != nil { + return fmt.Errorf("hash source entry: %w", err) + } + line.SHA256 = hash + } + } + if strings.HasSuffix(strings.ToLower(line.Path), ".jsonl") { + line.SessionID = sessionID(absolutePath, line.Path) + } + s.inventory.Lines = append(s.inventory.Lines, line) + s.absolute[line.Path] = absolutePath + return nil +} + +func hashFile(path string) ([32]byte, error) { + file, err := os.Open(path) //nolint:gosec // Paths come from the configured walk roots. + if err != nil { + return [32]byte{}, err + } + defer func() { + _ = file.Close() + }() + hash := sha256.New() + if _, err := io.Copy(hash, file); err != nil { + return [32]byte{}, err + } + var result [32]byte + copy(result[:], hash.Sum(nil)) + return result, nil +} + +func fileType(mode os.FileMode) string { + if mode&os.ModeSymlink != 0 { + return "symlink" + } + if mode.IsDir() { + return "directory" + } + if mode.IsRegular() { + return "file" + } + return "other" +} + +func isFinalOnly(path string, entries []string) bool { + for _, entry := range entries { + matched, err := filepath.Match(filepath.ToSlash(entry), filepath.ToSlash(path)) + if err == nil && matched { + return true + } + } + return false +} diff --git a/tools/transcript-archive/internal/inventory/walk_test.go b/tools/transcript-archive/internal/inventory/walk_test.go new file mode 100644 index 000000000..74575fbbb --- /dev/null +++ b/tools/transcript-archive/internal/inventory/walk_test.go @@ -0,0 +1,395 @@ +package inventory + +import ( + "crypto/sha256" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/config" +) + +func TestWalkOrphanSymlinkAndOutside(t *testing.T) { + t.Parallel() + root := t.TempDir() + mustMkdir(t, filepath.Join(root, "sessions", "orphan")) + mustWrite(t, filepath.Join(root, "sessions", "orphan", "file.log"), "not a root session") + target := filepath.Join(t.TempDir(), "outside.jsonl") + mustWrite(t, target, "outside") + mustWrite(t, filepath.Join(root, "custom-session-files", "marker"), target+"\n") + link := filepath.Join(root, "sessions", "orphan", "link") + if err := os.Symlink(target, link); err != nil { + t.Fatal(err) + } + cfg := config.Walk{Root: root, Sources: []config.Source{ + {Name: "sessions", Path: "sessions"}, + {Name: "custom-session-files", Path: "custom-session-files"}, + }} + got, _, err := Walk(cfg, nil) + if err != nil { + t.Fatal(err) + } + if !hasLine(got.Lines, filepath.Join(root, "sessions/orphan/file.log"), "tree/unassigned-sessions") { + t.Fatalf("orphan record missing: %#v", got.Lines) + } + if !hasType(got.Lines, filepath.Join(root, "sessions/orphan/link"), "symlink") { + t.Fatalf("symlink not recorded: %#v", got.Lines) + } + if got.OutsideTargets != 1 { + t.Fatalf("outside targets = %d, want 1", got.OutsideTargets) + } +} + +func TestWalkRootUnderSessions(t *testing.T) { + root := filepath.Join(t.TempDir(), "sessions", "seat") + mustWrite(t, filepath.Join(root, "data", "file.log"), "data") + mustWrite(t, filepath.Join(root, "sessions", "project", "one.jsonl"), "{\"type\":\"session\",\"id\":\"one\"}\n") + got, _, err := Walk(config.Walk{Root: root, Sources: []config.Source{{Name: "data", Path: "data"}, {Name: "sessions", Path: "sessions"}}}, nil) + if err != nil { + t.Fatal(err) + } + if !hasLine(got.Lines, filepath.Join(root, "data", "file.log"), "tree/data") || !hasLine(got.Lines, filepath.Join(root, "sessions", "project", "one.jsonl"), "omp-session/one") { + t.Fatalf("wrong records: %#v", got.Lines) + } +} + +func TestWalkDuplicateSession(t *testing.T) { + t.Parallel() + root := t.TempDir() + for _, name := range []string{"a", "b"} { + file := filepath.Join(root, "sessions", name, name+".jsonl") + mustMkdir(t, filepath.Dir(file)) + mustWrite(t, file, "{\"type\":\"session\",\"id\":\"same-id\"}\n") + } + got, _, err := Walk(config.Walk{Root: root, Sources: []config.Source{{Name: "sessions", Path: "sessions"}}}, nil) + if err != nil { + t.Fatal(err) + } + if len(got.Errors) != 1 { + t.Fatalf("assignment errors = %d, want 1: %#v", len(got.Errors), got.Errors) + } +} + +func TestWalkUnknownWatch(t *testing.T) { + t.Parallel() + root := t.TempDir() + mustMkdir(t, filepath.Join(root, ".omp", "new-store")) + mustWrite(t, filepath.Join(root, ".omp", "new-store", "data"), "data") + got, _, err := Walk(config.Walk{ + Root: root, Sources: []config.Source{{Name: "known", Path: "known"}}, Watch: []string{".omp"}, + }, nil) + if err != nil { + t.Fatal(err) + } + if len(got.Errors) != 1 || got.Errors[0].Reason != "unknown watched file" { + t.Fatalf("errors = %#v, want unknown watched file", got.Errors) + } +} + +func TestWalkExcluded(t *testing.T) { + t.Parallel() + root := t.TempDir() + mustWrite(t, filepath.Join(root, "data", "config.yml"), "secret-materialized-config") + got, _, err := Walk(config.Walk{ + Root: root, Sources: []config.Source{{Name: "data", Path: "data"}}, + Exclude: []config.Exclusion{{Path: "data/config.yml"}}, + }, nil) + if err != nil { + t.Fatal(err) + } + if len(got.Excluded) != 1 || got.Excluded[0].Count != 1 || got.Excluded[0].Bytes != int64(len("secret-materialized-config")) { + t.Fatalf("excluded summary = %#v", got.Excluded) + } + encoded, err := json.Marshal(got.Excluded) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(encoded), "config.yml") || strings.Contains(string(encoded), "secret-materialized-config") { + t.Fatalf("excluded record leaked path or contents: %s", encoded) + } +} + +func TestWalkMissingReferences(t *testing.T) { + root := t.TempDir() + path := filepath.Join(root, "sessions", "stem", "stem.jsonl") + mustWrite(t, path, "{\"type\":\"session\",\"id\":\"one\",\"blob\":\"blob:sha256:"+strings.Repeat("a", 64)+"\",\"artifact\":\"artifact://7\"}\n") + got, _, err := Walk(config.Walk{Root: root, Sources: []config.Source{{Name: "sessions", Path: "sessions"}}}, nil) + if err != nil { + t.Fatal(err) + } + reasons := make(map[string]bool) + for _, item := range got.Dangling { + reasons[item.Reason] = true + } + if !reasons["missing"] || !reasons["artifact-missing"] { + t.Fatalf("dangling reasons: %#v", got.Dangling) + } +} + +func TestWalkSessionClosure(t *testing.T) { + t.Parallel() + root := t.TempDir() + blob := strings.Repeat("a", 64) + rootSession := filepath.Join(root, "sessions", "stem", "stem.jsonl") + mustMkdir(t, filepath.Join(root, "sessions", "stem")) + mustWrite(t, rootSession, "{\"type\":\"session\",\"id\":\"session-a\",\"blob\":\"blob:sha256:"+blob+"\"}\n") + mustWrite(t, filepath.Join(root, "sessions", "stem", "7.webp"), "artifact") + mustMkdir(t, filepath.Join(root, "blobs")) + mustWrite(t, filepath.Join(root, "blobs", blob), "not matching content") + got, _, err := Walk(config.Walk{Root: root, Sources: []config.Source{ + {Name: "sessions", Path: "sessions"}, {Name: "blobs", Path: "blobs"}, + }}, nil) + if err != nil { + t.Fatal(err) + } + if len(got.Dangling) != 1 || got.Dangling[0].Reason != "digest-mismatch" { + t.Fatalf("dangling = %#v, want digest-mismatch", got.Dangling) + } + if !hasLine(got.Lines, rootSession, "omp-session/session-a") { + t.Fatalf("root session record missing: %#v", got.Lines) + } +} + +func TestSince(t *testing.T) { + t.Parallel() + old := Line{Root: "root", Path: "same", Type: "file", Size: 1, MtimeNs: 1, SHA256: sha256.Sum256([]byte("a"))} + newerMtime := old + newerMtime.MtimeNs = 100 + changed := old + changed.Size = 2 + changed.SHA256 = sha256.Sum256([]byte("bb")) + added := Line{Root: "root", Path: "added", Type: "file", Size: 0} + got := Since(Inventory{Lines: []Line{old}}, Inventory{Lines: []Line{newerMtime, changed, added}}) + if len(got) != 2 || got[0].Path != "added" || got[1].Path != "same" { + t.Fatalf("Since = %#v, want added and changed, ignoring mtime", got) + } +} + +func TestContentDigest(t *testing.T) { + t.Parallel() + first := Inventory{ + Lines: []Line{{Path: "transcript.jsonl", Type: "file", Size: 10, SHA256: sha256.Sum256([]byte("b"))}}, + Excluded: []Excluded{{Count: 2, Bytes: 20}}, + } + changedMaterialized := first + changedMaterialized.Excluded = []Excluded{{Count: 1, Bytes: 20}} + if ContentDigest(first) != ContentDigest(changedMaterialized) { + t.Fatal("excluded materialized config changed content digest") + } + changedTranscript := changedMaterialized + changedTranscript.Lines = append([]Line(nil), changedMaterialized.Lines...) + changedTranscript.Lines[0].SHA256 = sha256.Sum256([]byte("changed")) + if ContentDigest(first) == ContentDigest(changedTranscript) { + t.Fatal("transcript content did not change content digest") + } +} + +func TestWalkReusesPreviousHash(t *testing.T) { + t.Parallel() + root := t.TempDir() + path := filepath.Join(root, "source", "file") + mustWrite(t, path, "content") + cfg := config.Walk{Root: root, Sources: []config.Source{{Name: "source", Path: "source"}}} + first, _, err := Walk(cfg, nil) + if err != nil { + t.Fatal(err) + } + second, _, err := Walk(cfg, &first) + if err != nil { + t.Fatal(err) + } + if len(second.Lines) != 1 || second.Lines[0].SHA256 != sha256.Sum256([]byte("content")) { + t.Fatalf("previous digest not reused: %#v", second.Lines) + } +} + +func TestWalkAbsolutePathsInWatchRoot(t *testing.T) { + root := t.TempDir() + path := filepath.Join(root, ".omp", "source", "file") + mustWrite(t, path, "content") + cfg := config.Walk{ + Root: filepath.Join(root, "."), + Sources: []config.Source{{Name: "source", Path: ".omp/source"}}, + Watch: []string{".omp"}, + } + got, _, err := Walk(cfg, nil) + if err != nil { + t.Fatal(err) + } + if len(got.Errors) != 0 || len(got.Lines) != 1 || got.Lines[0].Path != path { + t.Fatalf("walk = %#v", got) + } +} + +func hasLine(lines []Line, path, record string) bool { + for _, line := range lines { + if line.Path == path && line.Record == record { + return true + } + } + return false +} + +func hasType(lines []Line, path, kind string) bool { + for _, line := range lines { + if line.Path == path && line.Type == kind { + return true + } + } + return false +} + +func mustMkdir(t *testing.T, path string) { + t.Helper() + if err := os.MkdirAll(path, 0o700); err != nil { + t.Fatal(err) + } +} + +func mustWrite(t *testing.T, path, content string) { + t.Helper() + mustMkdir(t, filepath.Dir(path)) + if err := os.WriteFile(path, []byte(content), 0o600); err != nil { + t.Fatal(err) + } +} + +// layoutHost is the synthetic host in testdata/archive.cue whose layout the walk tests exercise. +const layoutHost = "example-host" + +// sharedSourceFiles holds one file under each shared source in testdata/archive.cue. +var sharedSourceFiles = []string{ + ".example/agent/sessions/session.log", + ".example/agent/blobs/0123456789abcdef", + ".example/agent/custom-session-files/marker", + ".example/logs/example.log", + ".example/agent/agent.db", + ".example/agent/agent.db-wal", + ".example/agent/agent.db-shm", +} + +// excludedFiles are classified exclusions under the watched .example root. +var excludedFiles = []string{ + ".example/cache/github-cache.db", + ".example/install-id", +} + +// excludedSymlinks are config links under .example/agent that the walk must skip. +var excludedSymlinks = []string{ + ".example/agent/config.yml", +} + +func TestLayoutHostHasNoWatchRootErrors(t *testing.T) { + t.Parallel() + got := walkLayoutHost(t, layoutHost, buildLayoutHome(t)) + for _, assignment := range got.Errors { + if assignment.Reason == "unknown watched file" { + t.Errorf("watch-root error on %s", assignment.Path) + } + } +} + +func TestLayoutHostWalksClassifiedEntries(t *testing.T) { + t.Parallel() + got := walkLayoutHost(t, layoutHost, buildLayoutHome(t)) + for _, rel := range sharedSourceFiles { + if !hasPathSuffix(got.Lines, "/"+rel) { + t.Errorf("source %s has no inventory line", rel) + } + } + for _, group := range [][]string{excludedFiles, excludedSymlinks} { + for _, rel := range group { + if hasPathSuffix(got.Lines, "/"+rel) { + t.Errorf("%s was walked", rel) + } + } + } +} + +func TestLayoutHostFlagsUnlistedEntry(t *testing.T) { + t.Parallel() + home := buildLayoutHome(t) + mustWrite(t, filepath.Join(home, ".example", "unlisted-store", "data"), "unlisted") + got := walkLayoutHost(t, layoutHost, home) + want := filepath.ToSlash(filepath.Join(home, ".example", "unlisted-store", "data")) + found := false + for _, assignment := range got.Errors { + if assignment.Reason == "unknown watched file" && assignment.Path == want { + found = true + } + } + if !found { + t.Errorf("no watch-root error for unlisted %s; errors = %#v", want, got.Errors) + } + if !hasPathSuffix(got.Lines, "/.example/agent/agent.db") { + t.Error("walk lost source lines after an unlisted entry") + } +} + +func TestLayoutHostMarksFinalOnlyDatabases(t *testing.T) { + t.Parallel() + got := walkLayoutHost(t, layoutHost, buildLayoutHome(t)) + for _, rel := range []string{".example/agent/agent.db", ".example/agent/agent.db-wal", ".example/agent/agent.db-shm"} { + line, ok := findPathSuffix(got.Lines, "/"+rel) + if !ok { + t.Fatalf("missing final-only database %s", rel) + } + if line.Class != "final-only" { + t.Errorf("%s class = %q, want final-only", rel, line.Class) + } + } +} + +// walkLayoutHost runs the synthetic testdata host entry against a synthetic home. +func walkLayoutHost(t *testing.T, host, home string) Inventory { + t.Helper() + loaded, err := config.Load(filepath.Join("..", "..", "testdata", "archive.cue")) + if err != nil { + t.Fatal(err) + } + walk, err := loaded.Walk(host) + if err != nil { + t.Fatal(err) + } + walk.Root = home + got, _, err := Walk(walk, nil) + if err != nil { + t.Fatalf("%s: walk aborted: %v", host, err) + } + return got +} + +// buildLayoutHome writes every path the layout names; it never writes an unlisted entry. +func buildLayoutHome(t *testing.T) string { + t.Helper() + home := t.TempDir() + for _, group := range [][]string{sharedSourceFiles, excludedFiles} { + for _, rel := range group { + mustWrite(t, filepath.Join(home, filepath.FromSlash(rel)), "fixture") + } + } + for _, rel := range excludedSymlinks { + link := filepath.Join(home, filepath.FromSlash(rel)) + mustMkdir(t, filepath.Dir(link)) + if err := os.Symlink("/nix/store/fixture", link); err != nil { + t.Fatal(err) + } + } + return home +} + +func hasPathSuffix(lines []Line, suffix string) bool { + _, ok := findPathSuffix(lines, suffix) + return ok +} + +func findPathSuffix(lines []Line, suffix string) (Line, bool) { + for _, line := range lines { + if strings.HasSuffix(line.Path, suffix) { + return line, true + } + } + return Line{}, false +} diff --git a/tools/transcript-archive/internal/inventory/watch.go b/tools/transcript-archive/internal/inventory/watch.go new file mode 100644 index 000000000..b12b9623a --- /dev/null +++ b/tools/transcript-archive/internal/inventory/watch.go @@ -0,0 +1,51 @@ +package inventory + +import ( + "fmt" + "os" + "path/filepath" +) + +func (s *walkState) validateWatchRoots() error { + paths := make(map[string]struct{}, len(s.inventory.Lines)) + for _, line := range s.inventory.Lines { + paths[line.Path] = struct{}{} + } + for _, watch := range s.cfg.Watch { + watchPath := filepath.Join(s.cfg.Root, filepath.FromSlash(watch)) + if err := filepath.WalkDir(watchPath, func(path string, entry os.DirEntry, walkErr error) error { + return s.validateWatchEntry(path, entry, walkErr, paths) + }); err != nil { + return fmt.Errorf("validate watch root: %w", err) + } + } + return nil +} + +func (s *walkState) validateWatchEntry(path string, entry os.DirEntry, walkErr error, paths map[string]struct{}) error { + if walkErr != nil { + if os.IsNotExist(walkErr) { + return nil + } + return fmt.Errorf("walking watch root: %w", walkErr) + } + if entry.IsDir() && entry.Type()&os.ModeSymlink == 0 { + return nil + } + relative, err := filepath.Rel(s.cfg.Root, path) + if err != nil { + return fmt.Errorf("relative watch path: %w", err) + } + excluded, err := s.excluded(filepath.ToSlash(relative)) + if err != nil { + return err + } + if excluded { + return nil + } + clean := filepath.ToSlash(filepath.Clean(path)) + if _, ok := paths[clean]; !ok { + s.inventory.Errors = append(s.inventory.Errors, AssignError{Path: clean, Reason: "unknown watched file"}) + } + return nil +} diff --git a/tools/transcript-archive/internal/rawcap/rawcap.go b/tools/transcript-archive/internal/rawcap/rawcap.go new file mode 100644 index 000000000..9a816b2b2 --- /dev/null +++ b/tools/transcript-archive/internal/rawcap/rawcap.go @@ -0,0 +1,31 @@ +// Package rawcap decides whether a transcript archive pass may run, from the repository's raw-data byte count. +package rawcap + +import ( + "encoding/json" + "errors" + "fmt" +) + +// ErrOverCap reports that the repository holds at least the cap in raw bytes. +var ErrOverCap = errors.New("repository raw bytes at or above cap") + +// statsOutput is the subset of `restic stats --mode raw-data --json` the cap reads. +type statsOutput struct { + TotalSize *uint64 `json:"total_size"` +} + +// Check returns nil when the raw-data size is below capBytes. It fails closed: an absent or unparseable size is an error, not a pass. +func Check(statsJSON []byte, capBytes uint64) error { + var stats statsOutput + if err := json.Unmarshal(statsJSON, &stats); err != nil { + return fmt.Errorf("decode restic stats: %w", err) + } + if stats.TotalSize == nil { + return errors.New("restic stats has no total_size") + } + if *stats.TotalSize >= capBytes { + return fmt.Errorf("%w: %d >= %d", ErrOverCap, *stats.TotalSize, capBytes) + } + return nil +} diff --git a/tools/transcript-archive/internal/rawcap/rawcap_test.go b/tools/transcript-archive/internal/rawcap/rawcap_test.go new file mode 100644 index 000000000..89d3fc0e7 --- /dev/null +++ b/tools/transcript-archive/internal/rawcap/rawcap_test.go @@ -0,0 +1,34 @@ +package rawcap + +import ( + "errors" + "testing" +) + +const capBytes = uint64(500) << 30 + +func TestCheckBoundary(t *testing.T) { + cases := []struct { + name string + json string + wantErr bool + wantOver bool + }{ + {name: "under cap passes", json: `{"total_size": 536870911999}`}, + {name: "at cap refuses", json: `{"total_size": 536870912000}`, wantErr: true, wantOver: true}, + {name: "over cap refuses", json: `{"total_size": 536870912001}`, wantErr: true, wantOver: true}, + {name: "missing total_size fails closed", json: `{"total_bytes": 1}`, wantErr: true}, + {name: "malformed json fails closed", json: `{`, wantErr: true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + err := Check([]byte(tc.json), capBytes) + if (err != nil) != tc.wantErr { + t.Fatalf("Check() error = %v, want error %v", err, tc.wantErr) + } + if got := errors.Is(err, ErrOverCap); got != tc.wantOver { + t.Fatalf("errors.Is(ErrOverCap) = %v, want %v (err %v)", got, tc.wantOver, err) + } + }) + } +} diff --git a/tools/transcript-archive/internal/resticenv/env.go b/tools/transcript-archive/internal/resticenv/env.go new file mode 100644 index 000000000..c1380c6d8 --- /dev/null +++ b/tools/transcript-archive/internal/resticenv/env.go @@ -0,0 +1,37 @@ +// Package resticenv filters inherited restic configuration. +package resticenv + +import ( + "os" + "strings" +) + +// Filter removes inherited restic variables and optionally overrides TMPDIR. +func Filter(tmpDir string) []string { + environ := os.Environ() + result := make([]string, 0, len(environ)+1) + for _, entry := range environ { + key, _, _ := strings.Cut(entry, "=") + if strings.HasPrefix(key, "RESTIC_") || (tmpDir != "" && key == "TMPDIR") { + continue + } + result = append(result, entry) + } + if tmpDir != "" { + result = append(result, "TMPDIR="+tmpDir) + } + return result +} + +// backendPrefixes are the restic repository schemes that do not name a local directory. +var backendPrefixes = []string{"s3:", "rest:", "b2:", "azure:", "gs:", "sftp:", "swift:", "rclone:"} + +// IsBackend reports whether repo names a remote restic backend rather than a local path. +func IsBackend(repo string) bool { + for _, prefix := range backendPrefixes { + if strings.HasPrefix(repo, prefix) { + return true + } + } + return false +} diff --git a/tools/transcript-archive/internal/resticenv/env_test.go b/tools/transcript-archive/internal/resticenv/env_test.go new file mode 100644 index 000000000..487dd2f6c --- /dev/null +++ b/tools/transcript-archive/internal/resticenv/env_test.go @@ -0,0 +1,19 @@ +package resticenv + +import ( + "strings" + "testing" +) + +func TestCoverageEnvironment(t *testing.T) { + t.Setenv("RESTIC_PASSWORD", "secret") + t.Setenv("TMPDIR", "unsafe") + t.Setenv("COVERAGE_KEEP", "yes") + env := Filter("/safe") + joined := strings.Join(env, "\n") + if strings.Contains(joined, "RESTIC_PASSWORD=") || + !strings.Contains(joined, "TMPDIR=/safe") || + !strings.Contains(joined, "COVERAGE_KEEP=yes") { + t.Fatal("environment filter did not preserve its contract") + } +} diff --git a/tools/transcript-archive/internal/retrieve/get.go b/tools/transcript-archive/internal/retrieve/get.go new file mode 100644 index 000000000..10ecc469e --- /dev/null +++ b/tools/transcript-archive/internal/retrieve/get.go @@ -0,0 +1,347 @@ +package retrieve + +import ( + "bufio" + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "os/exec" //nolint:depguard // restic runs directly, without a shell + "path/filepath" + "regexp" + "strings" + + "filippo.io/age" + "filippo.io/age/armor" + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/resticenv" +) + +const resticGet = "restic" + +var blobReference = regexp.MustCompile(`blob:sha256:([0-9a-f]{64})`) + +type snapshotNode struct { + Name string `json:"name"` + Type string `json:"type"` + Path string `json:"path"` +} + +// Options identifies the repository, escrow and record to restore. +type Options struct { + Repo, Escrow, Identity string + Snapshot, Record, Output string +} + +// Get restores one record from an escrow-protected restic snapshot. +func Get(ctx context.Context, options Options) (resultErr error) { + repo, escrowPath, identityPath := options.Repo, options.Escrow, options.Identity + snapshot, record, output := options.Snapshot, options.Record, options.Output + if err := validateGetInputs(repo, escrowPath, identityPath, snapshot, record, output); err != nil { + return err + } + password, err := decryptEscrow(escrowPath, identityPath) + if err != nil { + return err + } + passwordPath, err := privateSecret(password) + if err != nil { + return err + } + defer func() { resultErr = errors.Join(resultErr, removeSecret(passwordPath)) }() + if err := os.MkdirAll(output, 0o700); err != nil { + return fmt.Errorf("create output directory: %w", err) + } + return restoreRecord(ctx, repo, passwordPath, snapshot, record, output) +} + +func validateGetInputs(repo, escrow, identity, snapshot, record, output string) error { + if repo == "" || escrow == "" || identity == "" || snapshot == "" || record == "" || output == "" { + return errors.New("repo, escrow, identity, snapshot, record and out are required") + } + if strings.ContainsAny(record, "/\\\r\n") || record == "." || record == ".." { + return errors.New("record must be a path-free stem") + } + return nil +} + +func decryptEscrow(escrowPath, identityPath string) (body []byte, resultErr error) { + identityFile, err := os.Open(identityPath) //nolint:gosec // identityPath is supplied by the operator + if err != nil { + return nil, fmt.Errorf("open age identity: %w", err) + } + identities, err := age.ParseIdentities(identityFile) + closeErr := identityFile.Close() + if err != nil { + return nil, fmt.Errorf("parse age identity: %w", errors.Join(err, closeErr)) + } + if closeErr != nil { + return nil, fmt.Errorf("close age identity: %w", closeErr) + } + ciphertext, err := os.Open(escrowPath) //nolint:gosec // escrowPath is supplied by the operator + if err != nil { + return nil, fmt.Errorf("open age escrow: %w", err) + } + defer func() { + if closeErr := ciphertext.Close(); closeErr != nil { + resultErr = errors.Join(resultErr, fmt.Errorf("close age escrow: %w", closeErr)) + } + }() + buffer := bufio.NewReader(ciphertext) + prefix, err := buffer.Peek(5) + if err != nil && !errors.Is(err, io.EOF) { + return nil, fmt.Errorf("read escrow header: %w", err) + } + var source io.Reader = buffer + if bytes.Equal(prefix, []byte("-----")) { + source = armor.NewReader(buffer) + } + plaintext, err := age.Decrypt(source, identities...) + if err != nil { + return nil, fmt.Errorf("decrypt age escrow: %w", err) + } + body, err = io.ReadAll(io.LimitReader(plaintext, 65)) + if err != nil { + return nil, fmt.Errorf("read decrypted escrow: %w", err) + } + if len(body) == 0 || len(body) > 64 { + return nil, errors.New("decrypted escrow must contain a password of at most 64 bytes") + } + return body, nil +} + +func privateSecret(value []byte) (string, error) { + file, err := os.CreateTemp("", "transcript-archive-password-*") + if err != nil { + return "", fmt.Errorf("create private password file: %w", err) + } + path := file.Name() + if err := file.Chmod(0o600); err != nil { + closeErr := file.Close() + removeErr := os.Remove(path) + return "", errors.Join(fmt.Errorf("protect private password file: %w", err), closeErr, removeErr) + } + if _, err := file.Write(value); err != nil { + closeErr := file.Close() + removeErr := os.Remove(path) + return "", errors.Join(fmt.Errorf("write private password file: %w", err), closeErr, removeErr) + } + if err := file.Sync(); err != nil { + closeErr := file.Close() + removeErr := os.Remove(path) + return "", errors.Join(fmt.Errorf("sync private password file: %w", err), closeErr, removeErr) + } + if err := file.Close(); err != nil { + removeErr := os.Remove(path) + return "", errors.Join(fmt.Errorf("close private password file: %w", err), removeErr) + } + return path, nil +} + +func restoreRecord(ctx context.Context, repo, passwordPath, snapshot, record, output string) (resultErr error) { + listing, err := runRestic(ctx, repo, passwordPath, "ls", "--no-lock", snapshot, "--json") + if err != nil { + return fmt.Errorf("list snapshot: %w", err) + } + paths, prefix, err := recordPaths(listing, record) + if err != nil { + return err + } + if len(paths) == 0 { + return fmt.Errorf("snapshot has no paths for record %q", record) + } + includePath, err := privateList(paths) + if err != nil { + return err + } + defer func() { resultErr = errors.Join(resultErr, removeSecret(includePath)) }() + target, err := os.MkdirTemp(output, ".transcript-archive-restore-*") + if err != nil { + return fmt.Errorf("create restore directory: %w", err) + } + defer func() { + if removeErr := os.RemoveAll(target); removeErr != nil { + resultErr = errors.Join(resultErr, fmt.Errorf("remove restore directory: %w", removeErr)) + } + }() + if _, err := runRestic(ctx, repo, passwordPath, "restore", "--no-lock", snapshot, "--target", target, "--include-file", includePath); err != nil { + return fmt.Errorf("restore transcript record: %w", err) + } + blobs, err := findBlobPaths(target) + if err != nil { + return err + } + for i := range blobs { + blobs[i] = prefix + "/" + blobs[i] + } + if len(blobs) > 0 { + blobList, err := privateList(blobs) + if err != nil { + return err + } + defer func() { resultErr = errors.Join(resultErr, removeSecret(blobList)) }() + if _, err := runRestic(ctx, repo, passwordPath, "restore", "--no-lock", snapshot, "--target", target, "--include-file", blobList); err != nil { + return fmt.Errorf("restore referenced transcript blobs: %w", err) + } + } + return moveRestored(target, output, prefix, append(paths, blobs...)) +} + +func runRestic(ctx context.Context, repo, passwordPath string, args ...string) ([]byte, error) { + global := make([]string, 0, 5+len(args)) + global = append(global, "--repo", repo, "--password-file", passwordPath, "--no-cache") + global = append(global, args...) + command := exec.CommandContext(ctx, resticGet, global...) //nolint:gosec // command resolves the fixed restic binary + command.Env = resticenv.Filter("") + var output bytes.Buffer + command.Stdout = &output + command.Stderr = io.Discard + if err := command.Run(); err != nil { + return output.Bytes(), errors.New("restic command failed") + } + return output.Bytes(), nil +} + +func recordPaths(listing []byte, record string) ([]string, string, error) { + paths := make([]string, 0) + prefix := "" + scanner := bufio.NewScanner(bytes.NewReader(listing)) + for scanner.Scan() { + var node snapshotNode + if err := json.Unmarshal(scanner.Bytes(), &node); err != nil { + return nil, "", fmt.Errorf("parse snapshot listing: %w", err) + } + if node.Type == "dir" || !strings.HasPrefix(node.Path, "/") { + continue + } + index := strings.Index(node.Path, "/sessions/") + if index >= 0 && recordMatch(node.Path[index:], record) { + candidate := node.Path[:index] + if len(paths) > 0 && prefix != candidate { + return nil, "", errors.New("record matches multiple watch roots") + } + prefix = candidate + paths = append(paths, node.Path) + } + } + if err := scanner.Err(); err != nil { + return nil, "", fmt.Errorf("read snapshot listing: %w", err) + } + return paths, prefix, nil +} + +func recordMatch(path, record string) bool { + parts := strings.Split(strings.TrimPrefix(path, "/"), "/") + if len(parts) < 3 || parts[0] != "sessions" { + return false + } + rootName := record + ".jsonl" + if parts[2] == rootName { + return true + } + return len(parts) > 3 && parts[2] == record +} + +func moveRestored(target, output, prefix string, paths []string) error { + for _, path := range uniqueStrings(paths) { + relative := strings.TrimPrefix(path, prefix+"/") + source := filepath.Join(target, strings.TrimPrefix(path, "/")) + if _, err := os.Lstat(source); err != nil { + return fmt.Errorf("inspect restored file: %w", err) + } + dest := filepath.Join(output, relative) + if err := os.MkdirAll(filepath.Dir(dest), 0o700); err != nil { + return fmt.Errorf("create restored directory: %w", err) + } + if err := os.Rename(source, dest); err != nil { + return fmt.Errorf("move restored file: %w", err) + } + } + return nil +} + +func findBlobPaths(root string) ([]string, error) { + paths := make([]string, 0) + err := filepath.WalkDir(root, func(path string, entry os.DirEntry, walkErr error) error { + if walkErr != nil { + return walkErr + } + if entry.IsDir() || entry.Type()&os.ModeSymlink != 0 || filepath.Ext(path) != ".jsonl" { + return nil + } + file, err := os.Open(path) //nolint:gosec // path is inside the private restore directory + if err != nil { + return fmt.Errorf("open restored transcript: %w", err) + } + body, readErr := io.ReadAll(file) + closeErr := file.Close() + if readErr != nil || closeErr != nil { + return errors.Join(fmt.Errorf("read restored transcript: %w", readErr), closeErr) + } + for _, match := range blobReference.FindAllSubmatch(body, -1) { + paths = append(paths, "blobs/"+string(match[1])) + } + return nil + }) + if err != nil { + return nil, err + } + return uniqueStrings(paths), nil +} + +func privateList(values []string) (string, error) { + file, err := os.CreateTemp("", "transcript-archive-paths-*") + if err != nil { + return "", fmt.Errorf("create private restore list: %w", err) + } + path := file.Name() + if err := file.Chmod(0o600); err != nil { + closeErr := file.Close() + removeErr := os.Remove(path) + return "", errors.Join(fmt.Errorf("protect private restore list: %w", err), closeErr, removeErr) + } + for _, value := range values { + if value == "" || strings.ContainsAny(value, "\r\n") { + closeErr := file.Close() + removeErr := os.Remove(path) + return "", errors.Join(errors.New("restore path is invalid"), closeErr, removeErr) + } + if _, err := file.WriteString(value + "\n"); err != nil { + closeErr := file.Close() + removeErr := os.Remove(path) + return "", errors.Join(fmt.Errorf("write private restore list: %w", err), closeErr, removeErr) + } + } + if err := file.Sync(); err != nil { + closeErr := file.Close() + removeErr := os.Remove(path) + return "", errors.Join(fmt.Errorf("sync private restore list: %w", err), closeErr, removeErr) + } + if err := file.Close(); err != nil { + removeErr := os.Remove(path) + return "", errors.Join(fmt.Errorf("close private restore list: %w", err), removeErr) + } + return path, nil +} + +func uniqueStrings(values []string) []string { + seen := make(map[string]struct{}, len(values)) + unique := make([]string, 0, len(values)) + for _, value := range values { + if _, exists := seen[value]; exists { + continue + } + seen[value] = struct{}{} + unique = append(unique, value) + } + return unique +} + +func removeSecret(path string) error { + if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("remove secret file: %w", err) + } + return nil +} diff --git a/tools/transcript-archive/internal/retrieve/get_internal_test.go b/tools/transcript-archive/internal/retrieve/get_internal_test.go new file mode 100644 index 000000000..bb4df09c0 --- /dev/null +++ b/tools/transcript-archive/internal/retrieve/get_internal_test.go @@ -0,0 +1,38 @@ +package retrieve + +import ( + "errors" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestMoveRestoredMissingFile(t *testing.T) { + err := moveRestored(t.TempDir(), t.TempDir(), "/source", []string{"/source/missing.jsonl"}) + if !errors.Is(err, os.ErrNotExist) { + t.Fatalf("moveRestored missing file: got %v, want not-exist error", err) + } +} + +func TestRemoveSecretReturnsRemoveError(t *testing.T) { + const secret = "restic-password-must-not-appear" + dir := t.TempDir() + // os.Remove fails on a non-empty directory, and that failure is not ErrNotExist. + if err := os.WriteFile(filepath.Join(dir, "child"), []byte(secret), 0o600); err != nil { + t.Fatal(err) + } + err := removeSecret(dir) + if err == nil { + t.Fatal("removeSecret on a non-empty directory: got nil, want remove error") + } + if strings.Contains(err.Error(), secret) { + t.Fatalf("removeSecret error contains the secret: %q", err) + } +} + +func TestRemoveSecretMissingFileIsNotAnError(t *testing.T) { + if err := removeSecret(filepath.Join(t.TempDir(), "missing")); err != nil { + t.Fatalf("removeSecret on a missing file: got %v, want nil", err) + } +} diff --git a/tools/transcript-archive/internal/retrieve/get_test.go b/tools/transcript-archive/internal/retrieve/get_test.go new file mode 100644 index 000000000..d06aa8e73 --- /dev/null +++ b/tools/transcript-archive/internal/retrieve/get_test.go @@ -0,0 +1,199 @@ +package retrieve_test + +import ( + "bytes" + "context" + "crypto/sha256" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "filippo.io/age" + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/client" + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/inventory" + "github.com/RigelBuild/nebula/tools/transcript-archive/internal/retrieve" +) + +type escrow struct{} + +func (escrow) Put(_ context.Context, _ string, body []byte) ([32]byte, error) { + return sha256.Sum256(body), nil +} + +func writeFile(t *testing.T, path string, body []byte) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, body, 0o600); err != nil { + t.Fatal(err) + } +} + +func wrapRestic(t *testing.T) string { + t.Helper() + real, err := exec.LookPath("restic") + if err != nil { + t.Fatal(err) + } + dir := t.TempDir() + log := filepath.Join(t.TempDir(), "calls") + script := fmt.Sprintf("#!/bin/sh\ncat /proc/$$/cmdline >> %q\ncat /proc/$$/environ >> %q\nprintf '\\n' >> %q\nexec %q \"$@\"\n", log, log, log, real) + writeFile(t, filepath.Join(dir, "restic"), []byte(script)) + if err := os.Chmod(filepath.Join(dir, "restic"), 0o700); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + return log +} + +func createEscrow(t *testing.T, password []byte) (string, string) { + t.Helper() + identity, err := age.GenerateX25519Identity() + if err != nil { + t.Fatal(err) + } + identityPath := filepath.Join(t.TempDir(), "identity") + writeFile(t, identityPath, []byte(identity.String()+"\n")) + var encrypted bytes.Buffer + writer, err := age.Encrypt(&encrypted, identity.Recipient()) + if err != nil { + t.Fatal(err) + } + if _, err := writer.Write(password); err != nil { + t.Fatal(err) + } + if err := writer.Close(); err != nil { + t.Fatal(err) + } + escrowPath := filepath.Join(t.TempDir(), "escrow.age") + writeFile(t, escrowPath, encrypted.Bytes()) + return escrowPath, identityPath +} + +func fixture(t *testing.T, root string) (map[string][]byte, string) { + t.Helper() + blob := []byte("fixture image bytes") + digest := fmt.Sprintf("%x", sha256.Sum256(blob)) + files := map[string][]byte{ + "sessions/work/record.jsonl": []byte(`{"blob":"blob:sha256:` + digest + `"}` + "\n"), + "sessions/work/record/sub.jsonl": []byte("nested\n"), + "sessions/work/record/output.log": []byte("log\n"), + "sessions/work/record/note.md": []byte("markdown\n"), + "blobs/" + digest: blob, + "sessions/work/record/image.webp": blob, + } + for path, body := range files { + if strings.HasSuffix(path, ".webp") { + continue + } + writeFile(t, filepath.Join(root, path), body) + } + if err := os.Link(filepath.Join(root, "blobs", digest), filepath.Join(root, "sessions/work/record/image.webp")); err != nil { + t.Fatal(err) + } + link := "sessions/work/record/link" + if err := os.Symlink("note.md", filepath.Join(root, link)); err != nil { + t.Fatal(err) + } + return files, link +} + +func archive(t *testing.T, root, repo, state string, files map[string][]byte, link string) (client.Outcome, []byte) { + t.Helper() + c, err := client.Open(state, client.RepoRef{Scope: "k3s-test-one", Repository: repo}, escrow{}, client.WithScratch(t.TempDir())) + if err != nil { + t.Fatal(err) + } + password, err := os.ReadFile(filepath.Join(state, "password")) + if err != nil { + t.Fatal(err) + } + lines := make([]inventory.Line, 0, len(files)+1) + paths := make([]string, 0, len(files)+1) + for path, body := range files { + absolute := filepath.Join(root, path) + paths = append(paths, absolute) + lines = append(lines, inventory.Line{Path: absolute, Type: "file", Size: int64(len(body)), SHA256: sha256.Sum256(body)}) + } + linkPath := filepath.Join(root, link) + paths = append(paths, linkPath) + lines = append(lines, inventory.Line{Path: linkPath, Type: "symlink", LinkTarget: "note.md"}) + if err := c.Scan(t.Context(), inventory.Inventory{Lines: lines}, inventory.Delta{Added: lines}); err != nil { + t.Fatal(err) + } + outcome, err := c.Pass(t.Context(), paths, nil) + if err != nil || outcome.Kind != client.Acked { + t.Fatalf("pass = %+v, %v", outcome, err) + } + return outcome, password +} + +func TestGetRoundTripAndArgv(t *testing.T) { + log := wrapRestic(t) + root := filepath.Join(t.TempDir(), "unique-source-sentinel-8274") + repo := filepath.Join(t.TempDir(), "repo") + files, link := fixture(t, root) + state := filepath.Join(t.TempDir(), "state") + outcome, password := archive(t, root, repo, state, files, link) + escrowPath, identity := createEscrow(t, password) + output := filepath.Join(t.TempDir(), "out") + for _, name := range []string{"HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"} { + t.Setenv(name, "http://127.0.0.1:1/") + } + t.Setenv("RESTIC_REPOSITORY", "rest:http://127.0.0.1:1/") + if err := retrieve.Get(t.Context(), retrieve.Options{Repo: repo, Escrow: escrowPath, Identity: identity, Snapshot: outcome.SnapshotID, Record: "record", Output: output}); err != nil { + t.Fatal(err) + } + for path, want := range files { + got, err := os.ReadFile(filepath.Join(output, path)) + if err != nil || !bytes.Equal(got, want) { + t.Errorf("restored %s: %q, %v", path, got, err) + } + } + if target, err := os.Readlink(filepath.Join(output, link)); err != nil || target != "note.md" { + t.Errorf("symlink = %q, %v", target, err) + } + cmd := exec.CommandContext(t.Context(), "restic", "--repo", repo, "--password-file", filepath.Join(state, "password"), "snapshots") + if output, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("snapshots: %s: %v", output, err) + } + checkOfflineListings(t, repo, filepath.Join(state, "password"), outcome.SnapshotID) + calls, err := os.ReadFile(log) + if err != nil { + t.Fatal(err) + } + if bytes.Contains(calls, []byte("unique-source-sentinel-8274")) || bytes.Contains(calls, password) { + t.Fatal("source sentinel or password appeared in restic argv or environment") + } +} + +// Restic restore lchown fails in user namespaces, so namespace checks use read-only commands. +func checkOfflineListings(t *testing.T, repo, password, snapshot string) { + t.Helper() + unshare, err := exec.LookPath("unshare") + if err != nil { + offlineUnavailable(t, err) + } + if err := exec.CommandContext(t.Context(), unshare, "-rn", "true").Run(); err != nil { + offlineUnavailable(t, err) + } + for _, args := range [][]string{{"snapshots", "--json"}, {"ls", "--json", snapshot}} { + commandArgs := append([]string{"-rn", "restic", "--repo", repo, "--password-file", password, "--no-lock"}, args...) + cmd := exec.CommandContext(t.Context(), unshare, commandArgs...) + if output, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("offline restic listing: %v: %s", err, output) + } + } +} + +func offlineUnavailable(t *testing.T, err error) { + t.Helper() + if os.Getenv("CI") != "" { + t.Fatalf("network namespace unavailable: %v", err) + } + t.Skipf("network namespace unavailable: %v", err) +} diff --git a/tools/transcript-archive/moon.yml b/tools/transcript-archive/moon.yml new file mode 100644 index 000000000..113da4f9e --- /dev/null +++ b/tools/transcript-archive/moon.yml @@ -0,0 +1,17 @@ +# yaml-language-server: $schema=https://moonrepo.dev/schemas/project.json +layer: "tool" +language: "go" +tags: ["go"] + +tasks: + test: + command: "nix" + args: ["develop", "../..#transcript-archive", "--command", "go", "test", "./..."] + options: + cache: false + # Enters the .#transcript-archive devShell, which provides restic for the tests. + # The root devShell lacks it. + runInCI: true + env: + CGO_ENABLED: "0" + inputs: ["**/*.go", "go.mod", "go.sum", "**/testdata/**/*", "**/*.cue"] diff --git a/tools/transcript-archive/testdata/archive.cue b/tools/transcript-archive/testdata/archive.cue new file mode 100644 index 000000000..c13c88753 --- /dev/null +++ b/tools/transcript-archive/testdata/archive.cue @@ -0,0 +1,43 @@ +package archive + +// Synthetic archive config for tests. It mirrors the shape of a real host +// config with placeholder names only, so nothing here names a real machine. + +let sharedLayout = { + sources: [ + {name: "sessions", path: ".example/agent/sessions"}, + {name: "blobs", path: ".example/agent/blobs"}, + {name: "custom-session-files", path: ".example/agent/custom-session-files"}, + {name: "logs", path: ".example/logs"}, + {name: "agent-db", path: ".example/agent/agent.db"}, + {name: "agent-db-wal", path: ".example/agent/agent.db-wal"}, + {name: "agent-db-shm", path: ".example/agent/agent.db-shm"}, + ] + watch: [".example"] + exclude: [ + {path: ".example/cache"}, + {path: ".example/install-id"}, + {path: ".example/agent/config.yml"}, + ] + finalOnly: [ + ".example/agent/agent.db", + ".example/agent/agent.db-wal", + ".example/agent/agent.db-shm", + ] +} + +hosts: "example-host": { + state: "unmeasured" + sources: sharedLayout.sources + watch: sharedLayout.watch + exclude: sharedLayout.exclude + finalOnly: sharedLayout.finalOnly +} + +hosts: "example-empty": { + state: "empty" + sources: [] + watch: [] + exclude: [] + finalOnly: [] +}