diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..a5670de --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Signed fixtures must keep their bytes on every platform. +selfupdate/testdata/minisign/** -text diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..caf869a --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,2 @@ +# Default reviewers for every change. +* @dgrieser diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 1028e4a..2498ff4 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -67,7 +67,9 @@ jobs: - uses: actions/setup-go@v7 with: go-version: stable - - run: go run golang.org/x/vuln/cmd/govulncheck@latest ./... + # Pinned like golangci-lint, so a new release cannot fail an + # unchanged commit. The vulnerability database is always current. + - run: go run golang.org/x/vuln/cmd/govulncheck@v1.9.0 ./... cross: name: Cross-compile diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1d772b4..d180aa4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -17,9 +17,15 @@ make test-min # run the tests on Go 1.27.0, the oldest supported release ``` Interactive packages (`pick`, `live`, `progress`) are tested without a -terminal. To try them by hand, write a small `main` package in a scratch -directory with a `replace github.com/mittwald/cli-kit => ../cli-kit` -directive. +terminal. To try them by hand, run the demo program: +`go run ./examples/demo --help` lists its commands, and `make demo ARGS=pick` +runs one. + +Code that reads untrusted input (escape sequences, archives, signatures, +redaction, style specifications) has fuzz targets. Their seeds run with +`go test`; `make fuzz` runs every target for `FUZZTIME` (30s by default). +Add a target when you add such a parser, and commit any failing input the +fuzzer finds under `testdata/fuzz` together with the fix. ## Ground rules diff --git a/Makefile b/Makefile index d7696eb..5a52839 100644 --- a/Makefile +++ b/Makefile @@ -3,7 +3,7 @@ GOLANGCI_LINT ?= golangci-lint # The oldest Go release cli-kit supports; keep it in sync with go.mod. GO_MIN ?= go1.27.0 -.PHONY: all test race cover lint fmt vet cross test-min test-locale tidy-check check +.PHONY: all test race cover lint fmt vet cross test-min test-locale fuzz demo tidy-check check all: check @@ -44,6 +44,21 @@ test-min: test-locale: LC_ALL=ja_JP.UTF-8 RUNEWIDTH_EASTASIAN=1 $(GO) test ./... +# Run every fuzz target for FUZZTIME each. Their seed corpora already run +# with the plain tests. +FUZZTIME ?= 30s +fuzz: + @set -e; for pkg in $$($(GO) list ./...); do \ + for target in $$($(GO) test -list '^Fuzz' $$pkg | grep '^Fuzz' || true); do \ + echo "$$pkg $$target"; \ + $(GO) test -run '^$$' -fuzz "^$$target$$" -fuzztime $(FUZZTIME) $$pkg; \ + done; \ + done + +# Try the interactive packages by hand: make demo ARGS=pick +demo: + $(GO) run ./examples/demo $(ARGS) + tidy-check: $(GO) mod tidy -diff diff --git a/README.md b/README.md index c24a5f3..2994fe5 100644 --- a/README.md +++ b/README.md @@ -35,8 +35,9 @@ compiled into your binary. | [`table`](https://pkg.go.dev/github.com/mittwald/cli-kit/table) | Tables in plain, framed and Markdown styles, and CSV/TSV records, with spreadsheet formulas escaped on request | | [`format`](https://pkg.go.dev/github.com/mittwald/cli-kit/format) | An `--output` flag value, JSON/YAML writers driven by the same struct tags, and compact ages ("3h", "5mo") | | [`ics`](https://pkg.go.dev/github.com/mittwald/cli-kit/ics) | An RFC 5545 iCalendar writer | -| [`secret`](https://pkg.go.dev/github.com/mittwald/cli-kit/secret) | Credentials from flags, files, environment, stdin, the OS keyring or a hidden prompt, and redaction of known and recognizable secrets | -| [`selfupdate`](https://pkg.go.dev/github.com/mittwald/cli-kit/selfupdate) | Self-updates from GitHub Releases or a GitLab package registry, checked against the release's checksums file | +| [`secret`](https://pkg.go.dev/github.com/mittwald/cli-kit/secret) | Credentials from flags, files, environment, stdin, the OS keyring or a hidden prompt | +| [`redact`](https://pkg.go.dev/github.com/mittwald/cli-kit/redact) | Known secrets and recognizable credentials removed from text before it is logged, with the standard library only | +| [`selfupdate`](https://pkg.go.dev/github.com/mittwald/cli-kit/selfupdate) | Self-updates from GitHub Releases or a GitLab package registry, checked against the release's checksums file and, optionally, its minisign signature | | [`cobrax`](https://pkg.go.dev/github.com/mittwald/cli-kit/cobrax) | Cobra helpers: `--color` and other auto/always/never flags, enum flags, deprecated flag spellings as hidden aliases, hardened, cached and prefix-filtered shell completion with an optional `--install` or a script written to a path, version command | | [`fsx`](https://pkg.go.dev/github.com/mittwald/cli-kit/fsx) | Files replaced atomically with a chosen mode, refusing a symbolic link in their place | | [`browser`](https://pkg.go.dev/github.com/mittwald/cli-kit/browser) | A web page opened in the user's browser, http and https URLs only, without a shell | @@ -46,6 +47,13 @@ compiled into your binary. ## Examples +To see the interactive packages at work, run the demo program: + +```shell +go run github.com/mittwald/cli-kit/examples/demo@latest --help +go run github.com/mittwald/cli-kit/examples/demo@latest pick +``` + ### Color and terminal ```go @@ -65,7 +73,7 @@ fmt.Print(th.PaintDiff(term.Plain(diff))) // a diff from elsewhere: made plain f fmt.Println(term.Sanitize(jobLog)) // its colors kept, every other escape gone fmt.Println(term.PlainLine(name)) // one line, no escape sequence, no color fmt.Println(th.PaintJSON(string(data))) // JSON from encoding/json: keys, strings, numbers, literals -author := theme.Hashed(name, nil) // the same color for the same name, on every run +author := th.Hashed(name) // the same color for the same name, on every run if term.ShouldLink(links.Mode(), os.Stdout) { fmt.Println(term.Hyperlink(url, term.PlainLine(name))) } @@ -164,18 +172,24 @@ without a terminal, set `StdinBusy` so that stdin is left alone. ### Self-update ```go +verifier, err := selfupdate.NewMinisign(publicKey) // "RWQ…", from minisign -G u := &selfupdate.Updater{ - Source: &selfupdate.GitHub{Owner: "example", Repo: "tool"}, - Current: buildinfo.Get().Version, - Asset: selfupdate.VersionedAssets("tool"), + Source: &selfupdate.GitHub{Owner: "example", Repo: "tool"}, + Current: buildinfo.Get().Version, + Asset: selfupdate.VersionedAssets("tool"), + Verifier: verifier, // checksums.txt must carry a valid checksums.txt.minisig } res, err := u.Update(ctx, false) // checks the archive against checksums.txt; refuses package-managed installs ``` -The checksum detects a corrupted or altered download. It does not protect -against someone who can write the release's files, because the checksums -file is published in the same place. The archive must hold an executable -for the platform, and a credential is only sent to an `https` API address. +The checksum detects a corrupted or altered download. On its own it does +not protect against someone who can write the release's files, because the +checksums file is published in the same place. A `Verifier` closes that +gap: the checksums file must be signed with a key that never touches the +release, such as a minisign key held in a CI secret. The package +documentation shows the GoReleaser `signs` entry. The archive must hold an +executable for the platform, and a credential is only sent to an `https` +API address. ### Files, browser and logs @@ -191,6 +205,7 @@ if verbose { } logger := slog.New(logx.NewLineHandler(os.Stderr, &logx.Options{Level: level})) logger.Debug("sent a request", "path", path, "status", status) // plain, credentials redacted +logger.Debug("response", "body", redact.Values(body, token)) // the token the program sent, in any escaped form ``` ### Shell completion and version diff --git a/examples/demo/interactive.go b/examples/demo/interactive.go new file mode 100644 index 0000000..6421fb7 --- /dev/null +++ b/examples/demo/interactive.go @@ -0,0 +1,86 @@ +package main + +import ( + "errors" + "fmt" + "os" + "strings" + + "github.com/spf13/cobra" + + "github.com/mittwald/cli-kit/pick" + "github.com/mittwald/cli-kit/theme" +) + +// newPickCommand returns the pick command: a list to choose a release from, +// then a typed answer and a hidden one. +func newPickCommand() *cobra.Command { + return &cobra.Command{ + Use: "pick", + Short: "Choose from a list, then type a text and a secret", + Args: cobra.NoArgs, + RunE: func(*cobra.Command, []string) error { + return runPick() + }, + } +} + +func runPick() error { + releases := []pick.Item{ + {Cells: []string{"1.4.2", "latest", "2 days ago"}, Action: "deploy", Groups: []string{"stable"}}, + {Cells: []string{"1.4.1", "current", "2 weeks ago"}, Action: "redeploy", Groups: []string{"stable"}}, + {Cells: []string{"1.5.0-rc.1", "release candidate", "yesterday"}, Action: "try", Groups: []string{"preview"}}, + {Cells: []string{"1.3.9", "end of life", "4 months ago"}, Muted: true, Groups: []string{"stable"}}, + {Cells: []string{"1.2.0", "withdrawn"}, Disabled: true, Groups: []string{"stable"}}, + } + // Views narrow the rows to their groups; Tab switches between them. + _, index, err := pick.SelectView(os.Stdin, os.Stderr, pick.Options{ + Title: "Deploy which version of %s?", + Subject: "api", + Note: "Muted rows are old, the withdrawn one cannot be chosen.", + Items: releases, + Views: []pick.View{ + {Name: "all"}, + {Name: "stable", Groups: []string{"stable"}}, + {Name: "preview", Groups: []string{"preview"}}, + }, + }) + switch { + case errors.Is(err, pick.ErrNotATerminal): + fmt.Println("pick needs a terminal: run it without a pipe or redirection.") + return nil + case errors.Is(err, pick.ErrAborted): + fmt.Println("Nothing chosen.") + return nil + case err != nil: + return err + } + th := theme.Active().For(os.Stdout) + fmt.Println("Chose", th.Value.Paint(releases[index].Cells[0])) + + note, err := pick.Input(os.Stdin, os.Stderr, pick.InputOptions{ + Prompt: "Note for the deployment of %s: ", + // What a user typed is shown as plain text. + Subject: releases[index].Cells[0], + Value: "routine update", + }) + if err != nil { + return ignoreAbort(err) + } + token, err := pick.Input(os.Stdin, os.Stderr, pick.InputOptions{Prompt: "Token (hidden): ", Secret: true}) + if err != nil { + return ignoreAbort(err) + } + fmt.Printf("Note %q, token of %d characters %s\n", + note, len([]rune(token)), th.Muted.Paint("("+strings.Repeat("•", min(len([]rune(token)), 8))+")")) + return nil +} + +// ignoreAbort turns Esc or Ctrl-C at a prompt into a quiet exit. +func ignoreAbort(err error) error { + if errors.Is(err, pick.ErrAborted) { + fmt.Println("Canceled.") + return nil + } + return err +} diff --git a/examples/demo/main.go b/examples/demo/main.go new file mode 100644 index 0000000..cb67d15 --- /dev/null +++ b/examples/demo/main.go @@ -0,0 +1,77 @@ +// Command demo shows the visual packages of cli-kit at work. Run it from the +// module root: +// +// go run ./examples/demo +// +// The commands are: +// +// - pick: choose a release from a list with views and muted rows, then +// type a text answer and a hidden secret (needs a terminal) +// - progress: a progress bar over fake steps, with log lines that step +// around it and a stalled step that counts down its timeout +// - live: a block of lines redrawn in place +// - table: a table in every drawn style, or in the format --output names +// - theme: the color roles, a painted diff, painted JSON, a stable color +// per name and a style read from --style +// - term: hyperlinks, truncation, wrapping and hostile text made safe +// - version: the version, commit and build date +// - completion: shell completion scripts, with --install for bash, zsh +// and fish +// +// Every command keeps its output plain when it does not go to a terminal, +// so piping it through cat shows what a script would read. --color and +// --links take auto, always or never. +package main + +import ( + "fmt" + "os" + + "github.com/spf13/cobra" + + "github.com/mittwald/cli-kit/buildinfo" + "github.com/mittwald/cli-kit/cobrax" + "github.com/mittwald/cli-kit/live" +) + +func main() { + os.Exit(run()) +} + +// run builds and executes the command tree. It is separate from main so its +// deferred calls run before the process exits. +func run() int { + // Never leave the cursor hidden or the terminal in raw mode, also when + // the demo is interrupted. + defer live.InstallSignalRestore()() + + root := &cobra.Command{ + Use: "demo", + Short: "Show the visual packages of cli-kit at work", + SilenceUsage: true, + SilenceErrors: true, + } + cobrax.AddColorFlag(root, "when to use color: auto, always or never") + links := cobrax.AddModeFlag(root, "links", "when to make links: auto, always or never") + + info := buildinfo.Get() + cobrax.SetVersion(root, info) + root.AddCommand( + newPickCommand(), + newProgressCommand(), + newLiveCommand(), + newTableCommand(), + newThemeCommand(), + newTermCommand(links), + cobrax.NewVersionCommand(info), + ) + cobrax.NoFileArgs(root) + // The completion command exists only once the subcommands are added. + cobrax.AddCompletionInstall(cobrax.HardenCompletion(root)) + + if err := root.Execute(); err != nil { + fmt.Fprintln(os.Stderr, "demo:", err) + return 1 + } + return 0 +} diff --git a/examples/demo/motion.go b/examples/demo/motion.go new file mode 100644 index 0000000..c66b9ee --- /dev/null +++ b/examples/demo/motion.go @@ -0,0 +1,129 @@ +package main + +import ( + "fmt" + "log" + "os" + "time" + + "github.com/spf13/cobra" + + "github.com/mittwald/cli-kit/live" + "github.com/mittwald/cli-kit/progress" + "github.com/mittwald/cli-kit/term" + "github.com/mittwald/cli-kit/theme" +) + +// newProgressCommand returns the progress command: a bar over fake steps, +// one of which stalls long enough to show the countdown. +func newProgressCommand() *cobra.Command { + var stall bool + cmd := &cobra.Command{ + Use: "progress", + Short: "Show a progress bar with log lines and a stalled step", + Args: cobra.NoArgs, + RunE: func(*cobra.Command, []string) error { + runProgress(stall) + return nil + }, + } + cmd.Flags().BoolVar(&stall, "stall", true, "let one step stall to show the countdown") + return cmd +} + +func runProgress(stall bool) { + type step struct { + name string + took time.Duration + } + steps := []step{ + {"Resolving dependencies", 300 * time.Millisecond}, + {"Downloading archive", 600 * time.Millisecond}, + {"Verifying checksum", 200 * time.Millisecond}, + {"Waiting for the registry", 2500 * time.Millisecond}, + {"Installing", 400 * time.Millisecond}, + } + if !stall { + steps[3].took = 300 * time.Millisecond + } + + // The bar counts down after a second of waiting, sooner than the default, + // so the demo shows it quickly. + bar := progress.New(os.Stderr, progress.Options{StallDelay: time.Second}) + // Log lines written through the bar appear above it, never under it. + logger := log.New(bar.Writer(os.Stderr), "", 0) + bar.Start(len(steps), 10*time.Second) + for _, s := range steps { + bar.Advance(s.name) + done := bar.BeginWait() + time.Sleep(s.took) + done() + logger.Printf("%s: done in %s", s.name, s.took) + } + bar.Finish(true) + // Erase the bar right before the result. + bar.Clear() + fmt.Println(theme.Active().For(os.Stdout).Success.Paint("Installed 1.4.2")) +} + +// newLiveCommand returns the live command: a block of status lines redrawn +// in place. +func newLiveCommand() *cobra.Command { + return &cobra.Command{ + Use: "live", + Short: "Redraw a block of lines in place", + Args: cobra.NoArgs, + RunE: func(*cobra.Command, []string) error { + return runLive() + }, + } +} + +func runLive() error { + th := theme.Active().For(os.Stdout) + jobs := []string{"build", "test", "lint", "package"} + progress := make([]int, len(jobs)) + render := func() []string { + lines := make([]string, len(jobs)) + for i, job := range jobs { + state := th.Muted.Paint(fmt.Sprintf("%3d%%", progress[i])) + if progress[i] == 100 { + state = th.Success.Paint("done") + } + lines[i] = fmt.Sprintf("%-8s %s", job, state) + } + return lines + } + + // Where stdout cannot be redrawn in place (a pipe, a file, TERM=dumb), + // show the result once instead of every frame. + if !term.CanAnimate(os.Stdout) { + for i := range progress { + progress[i] = 100 + } + for _, line := range render() { + fmt.Println(line) + } + return nil + } + + cursor := live.NewCursor(os.Stdout) + cursor.Hide() + defer cursor.Show() + block := live.New(os.Stdout) + for tick := 0; ; tick++ { + finished := true + for i := range progress { + // Each job moves at its own pace. + progress[i] = min(100, tick*(i+2)*3) + finished = finished && progress[i] == 100 + } + if err := block.Draw(render()); err != nil { + return err + } + if finished { + return nil + } + time.Sleep(60 * time.Millisecond) + } +} diff --git a/examples/demo/output.go b/examples/demo/output.go new file mode 100644 index 0000000..cbb8d2c --- /dev/null +++ b/examples/demo/output.go @@ -0,0 +1,209 @@ +package main + +import ( + "fmt" + "os" + + "github.com/spf13/cobra" + + "github.com/mittwald/cli-kit/cobrax" + "github.com/mittwald/cli-kit/format" + "github.com/mittwald/cli-kit/table" + "github.com/mittwald/cli-kit/term" + "github.com/mittwald/cli-kit/theme" +) + +// service is one row of the table command. Its json tags drive JSON and +// YAML alike. +type service struct { + Name string `json:"name"` + Status string `json:"status"` + Replicas int `json:"replicas"` + Image string `json:"image"` +} + +var services = []service{ + {"api", "running", 3, "registry.example.com/api:1.4.2"}, + {"worker", "stopped", 0, "registry.example.com/worker:1.4.2"}, + {"scheduler", "running", 1, "registry.example.com/scheduler:1.3.9"}, +} + +// newTableCommand returns the table command: the services in one style, in +// every style, or in the format --output names. +func newTableCommand() *cobra.Command { + var ( + out format.Format + all bool + styleFlag *cobrax.Enum + ) + cmd := &cobra.Command{ + Use: "table", + Short: "Draw a table in any style, or write it as JSON, YAML, CSV, TSV or Markdown", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + if out.IsStructured() { + return format.Write(os.Stdout, out, services) + } + if all && out.IsVerbatim() { + return fmt.Errorf("--all draws the table and cannot be combined with --output %s", out) + } + if !all { + s, err := table.ParseStyle(styleFlag.Value()) + if err != nil { + return err + } + return renderServices(s, out) + } + for _, name := range table.StyleNames() { + s, _ := table.LookupStyle(name) + fmt.Println(theme.Active().For(os.Stdout).Title.Paint(name)) + if err := renderServices(s, out); err != nil { + return err + } + fmt.Println() + } + return nil + }, + } + cmd.Flags().VarP(format.NewValue(&out, format.Text, nil), "output", "o", + "output format: "+format.Default.String()) + styleFlag = cobrax.AddEnumFlag(cmd, cmd.Flags(), "style", "s", "rounded", + "table style", table.StyleNames()...) + cmd.Flags().BoolVar(&all, "all", false, "draw the table in every style") + return cmd +} + +// renderServices draws the services table in style s, or writes it in the +// record or Markdown format out selects. +func renderServices(s table.Style, out format.Format) error { + t := table.New(os.Stdout, []string{"Name", "Status", "Replicas", "Image"}, + table.UppercaseHeaders(), + table.WithStyle(s), + table.WithAlignment(table.AlignLeft, table.AlignLeft, table.AlignRight), + // Applied last: Markdown, CSV and TSV replace the style. + table.WithFormat(out), + table.EscapeFormulas(), + ) + for _, svc := range services { + t.Append(svc.Name, svc.Status, fmt.Sprint(svc.Replicas), svc.Image) + } + return t.Render() +} + +const sampleDiff = "diff --git a/version.yaml b/version.yaml\n" + + "--- a/version.yaml\n" + + "+++ b/version.yaml\n" + + "@@ -1,3 +1,3 @@\n" + + " name: api\n" + + "-version: 1.4.1\n" + + "+version: 1.4.2\n" + + " stable: true\n" + +// newThemeCommand returns the theme command: what the color roles look like, +// and what the theme paints for diffs, JSON and names. +func newThemeCommand() *cobra.Command { + var spec string + cmd := &cobra.Command{ + Use: "theme", + Short: "Show the color roles, a painted diff, painted JSON and per-name colors", + Args: cobra.NoArgs, + RunE: func(*cobra.Command, []string) error { + return runTheme(spec) + }, + } + cmd.Flags().StringVar(&spec, "style", "fg=white:bg=#aa0000:bold", + `a style as a user would set it, such as "red:bold", "245" or "bg=#aa0000"`) + return cmd +} + +func runTheme(spec string) error { + // Plain wherever stdout takes no color, so a pipe sees no escapes. + th := theme.Active().For(os.Stdout) + + heading := func(s string) { fmt.Println(th.Title.Paint(s)) } + heading("Roles") + roles := []struct { + name string + style theme.Style + }{ + {"Info", th.Info}, {"Success", th.Success}, {"Warning", th.Warning}, {"Error", th.Error}, + {"Accent", th.Accent}, {"Flag", th.Flag}, {"Value", th.Value}, {"Qualifier", th.Qualifier}, + {"Muted", th.Muted}, {"Added", th.Added}, {"Removed", th.Removed}, + } + for _, r := range roles { + fmt.Println(" " + r.style.Paint(r.name)) + } + + fmt.Println() + heading("Diff") + fmt.Print(th.PaintDiff(sampleDiff)) + + fmt.Println() + heading("JSON") + fmt.Println(th.PaintJSON(`{"name":"api","replicas":3,"stable":true,"owner":null}`)) + + fmt.Println() + heading("A stable color per name") + // A nil palette means theme.NamePalette. Case and surrounding space do + // not change the color, so both spellings of alice match. + for _, name := range []string{"alice", "bob", "carol", "Alice"} { + fmt.Println(" " + th.Hashed(name).Paint(name)) + } + + fmt.Println() + heading("Style from --style") + style, ok := theme.ParseStyle(spec) + if !ok { + return fmt.Errorf("--style %q is no style", spec) + } + fmt.Println(" " + style.For(os.Stdout).Paint(spec)) + return nil +} + +// newTermCommand returns the term command: what term does to text before it +// reaches the terminal. +func newTermCommand(links *cobrax.ModeValue) *cobra.Command { + return &cobra.Command{ + Use: "term", + Short: "Show hyperlinks, truncation, wrapping and hostile text made safe", + Args: cobra.NoArgs, + RunE: func(*cobra.Command, []string) error { + runTerm(links.Mode()) + return nil + }, + } +} + +func runTerm(linkMode term.ColorMode) { + th := theme.Active().For(os.Stdout) + width := term.Columns(os.Stdout, 80) + heading := func(s string) { fmt.Println(th.Title.Paint(s)) } + + heading("Hyperlinks") + const docs = "https://pkg.go.dev/github.com/mittwald/cli-kit" + if term.ShouldLink(linkMode, os.Stdout) { + fmt.Println(" " + term.Hyperlink(docs, "the package documentation")) + } else { + fmt.Println(" the package documentation: " + docs) + } + + fmt.Println() + heading(fmt.Sprintf("Truncation to %d columns", width/2)) + long := "registry.example.com/team/very-long-service-name/with/a/deep/path:1.4.2-rc.1+build.20261117" + fmt.Println(" end: " + term.Truncate(long, width/2)) + fmt.Println(" middle: " + term.TruncateMiddle(long, width/2)) + fmt.Println(" wide: " + term.Truncate("日本語のサービス名はとても長いです", 20)) + + fmt.Println() + heading("Wrapping") + fmt.Println(term.Wrap(" Dry run: would tag 1.4.2, push it, wait for its pipeline and deploy it to every region one after the other.", + min(width, 60), " ")) + + fmt.Println() + heading("Hostile text") + hostile := "\x1b]0;pwned\x07\x1b[31mURGENT\x1b[0m: invoice\u202efdp.exe\x1b[2J" + fmt.Printf(" raw: %q\n", hostile) + fmt.Printf(" Sanitize: %s\n", term.Sanitize(hostile)) + fmt.Printf(" PlainLine: %s\n", term.PlainLine(hostile)) + fmt.Printf(" width of %q: %d columns\n", "日本 ok", term.VisibleWidth("日本 ok")) +} diff --git a/format/write.go b/format/write.go index d92718c..8547964 100644 --- a/format/write.go +++ b/format/write.go @@ -215,8 +215,8 @@ type yamlEncoder struct { out []byte } -// document writes the whole document. A sequence at the root is indented -// like one under a key. +// document writes the whole document. A sequence at the root starts at the +// first column, as yq, kubectl and the YAML libraries write it. func (e *yamlEncoder) document(v any) { switch v := v.(type) { case yamlMapping: @@ -226,7 +226,7 @@ func (e *yamlEncoder) document(v any) { } case []any: if len(v) > 0 { - e.sequence(v, yamlIndent, false) + e.sequence(v, 0, false) return } } diff --git a/format/write_test.go b/format/write_test.go index 0f196a4..d1444d1 100644 --- a/format/write_test.go +++ b/format/write_test.go @@ -145,7 +145,7 @@ func TestYAMLQuotesWhatReadersTakeForSomethingElse(t *testing.T) { want string }{ {"value", map[string]string{"v": s}, "v: " + quoted + "\n"}, - {"item", []string{s}, " - " + quoted + "\n"}, + {"item", []string{s}, "- " + quoted + "\n"}, {"key", map[string]int{s: 1}, quoted + ": 1\n"}, {"root", s, quoted + "\n"}, } { @@ -672,3 +672,29 @@ func TestYAMLParsesBackToTheJSONView(t *testing.T) { }) } } + +// A list at the root starts at the first column, as yq and kubectl write +// it, and reads back as what JSON holds, block scalars and nested lists +// included. +func TestYAMLRootSequence(t *testing.T) { + in := []any{ + map[string]any{"name": "api", "note": "two\nlines", "ports": []any{80, 443}}, + []any{"a", []any{}}, + "plain", + } + var y bytes.Buffer + if err := WriteYAML(&y, in); err != nil { + t.Fatalf("WriteYAML returned error: %v", err) + } + want := "- name: api\n note: |-\n two\n lines\n ports:\n - 80\n - 443\n- - a\n - []\n- plain\n" + if got := y.String(); got != want { + t.Fatalf("WriteYAML = %q, want %q", got, want) + } + var back []any + if err := yaml.Unmarshal(y.Bytes(), &back); err != nil { + t.Fatalf("re-reading the YAML failed: %v", err) + } + if got, want := viaJSON(t, back), viaJSON(t, in); !reflect.DeepEqual(got, want) { + t.Errorf("YAML reads back as %v, want %v", got, want) + } +} diff --git a/go.mod b/go.mod index a9aca30..abeb4d6 100644 --- a/go.mod +++ b/go.mod @@ -9,6 +9,7 @@ require ( github.com/spf13/cobra v1.10.2 github.com/spf13/pflag v1.1.0 github.com/zalando/go-keyring v0.2.8 + golang.org/x/crypto v0.58.0 golang.org/x/sys v0.50.0 golang.org/x/term v0.48.0 ) diff --git a/go.sum b/go.sum index 6bdbea2..9a56f1b 100644 --- a/go.sum +++ b/go.sum @@ -30,6 +30,8 @@ github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD github.com/zalando/go-keyring v0.2.8 h1:6sD/Ucpl7jNq10rM2pgqTs0sZ9V3qMrqfIIy5YPccHs= github.com/zalando/go-keyring v0.2.8/go.mod h1:tsMo+VpRq5NGyKfxoBVjCuMrG47yj8cmakZDO5QGii0= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= +golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/term v0.48.0 h1:G6UU1eiSB8nl3DzeUGt7Mg+2SctI8tPS6Z5/mBt6cOk= diff --git a/ics/fuzz_test.go b/ics/fuzz_test.go new file mode 100644 index 0000000..9051980 --- /dev/null +++ b/ics/fuzz_test.go @@ -0,0 +1,71 @@ +package ics + +import ( + "strings" + "testing" + "unicode/utf8" +) + +// Fold keeps every physical line within 75 octets and valid UTF-8, and +// unfolding gives the line back. +func FuzzFold(f *testing.F) { + for _, seed := range []string{"", "SUMMARY:short", strings.Repeat("ü", 60), strings.Repeat("a", 75) + "\xff" + strings.Repeat("😀", 30)} { + f.Add(seed) + } + f.Fuzz(func(t *testing.T, line string) { + lines := Fold(line) + for i, l := range lines { + if len(l) > maxLineOctets { + t.Fatalf("Fold(%q) line %d has %d octets", line, i, len(l)) + } + if !utf8.ValidString(l) { + t.Fatalf("Fold(%q) line %d is not valid UTF-8: %q", line, i, l) + } + if i > 0 && !strings.HasPrefix(l, " ") { + t.Fatalf("Fold(%q) continuation %d does not start with a space: %q", line, i, l) + } + } + unfolded := lines[0] + for _, l := range lines[1:] { + unfolded += l[1:] + } + if want := strings.ToValidUTF8(line, "�"); unfolded != want { + t.Fatalf("Fold(%q) unfolds to %q", line, unfolded) + } + }) +} + +// EscapeText leaves nothing that could end the property or the line, and +// nothing a terminal would read as a control. +func FuzzEscapeText(f *testing.F) { + for _, seed := range []string{"a,b;c\\d", "line\r\nbreak", "\x1b[31mred\u009b2J", "\xff"} { + f.Add(seed) + } + f.Fuzz(func(t *testing.T, s string) { + got := EscapeText(s) + if !utf8.ValidString(got) { + t.Fatalf("EscapeText(%q) = %q, not valid UTF-8", s, got) + } + for i, r := range got { + if r != '\t' && (r < 0x20 || r == 0x7f || (r >= 0x80 && r < 0xa0)) { + t.Fatalf("EscapeText(%q) = %q keeps control %U", s, got, r) + } + switch r { + case ';', ',': + if i == 0 || got[i-1] != '\\' || escaped(got, i-1) { + t.Fatalf("EscapeText(%q) = %q leaves %q unescaped", s, got, r) + } + } + } + }) +} + +// escaped reports whether the byte at i is itself escaped: an odd number +// of backslashes stands right before it. +func escaped(s string, i int) bool { + n := 0 + for i--; i >= 0 && s[i] == '\\'; i-- { + n++ + } + return n%2 == 1 +} diff --git a/logx/doc.go b/logx/doc.go index 6dbec48..da46892 100644 --- a/logx/doc.go +++ b/logx/doc.go @@ -5,8 +5,8 @@ // error stream. A log line often carries text from elsewhere, such as a // server's error message or a request URL, so every line is made plain // text (term.Plain), and credentials it recognizes by their shape are -// replaced (secret.RedactPatterns) before it is written. +// replaced (redact.Patterns) before it is written. // -// The handler lives in a package of its own because it needs both term and -// secret, and secret already depends on term. +// The handler depends on term and redact only, so a tool that logs does not +// compile in the keyring and prompt code of the secret package. package logx diff --git a/logx/line.go b/logx/line.go index 1de4645..0bab7a5 100644 --- a/logx/line.go +++ b/logx/line.go @@ -10,7 +10,7 @@ import ( "sync" "unicode" - "github.com/mittwald/cli-kit/secret" + "github.com/mittwald/cli-kit/redact" "github.com/mittwald/cli-kit/term" ) @@ -39,12 +39,12 @@ type Options struct { // never in doubt. // // The message goes through term.Plain as well. Then the message and each -// key=value pair go through secret.RedactPatterns, each on its own, so +// key=value pair go through redact.Patterns, each on its own, so // that text in one cannot hide a credential in another: escape sequences // and control characters but the newline are taken out, and recognizable // credentials such as password=… or Bearer tokens are replaced, a quoted // value as a whole. A message with a newline still spans several lines. The handler does not -// know the secrets the program holds; pass those through secret.Redact +// know the secrets the program holds; pass those through redact.Values // before they reach a log record. // // A LineHandler and the handlers derived from it share one lock, so lines @@ -74,7 +74,7 @@ func (h *LineHandler) Enabled(_ context.Context, level slog.Level) bool { // Handle writes the record as one line. func (h *LineHandler) Handle(_ context.Context, record slog.Record) error { var line strings.Builder - line.WriteString(secret.RedactPatterns(term.Plain(record.Message))) + line.WriteString(redact.Patterns(term.Plain(record.Message))) line.WriteString(h.attrs) record.Attrs(func(attr slog.Attr) bool { appendAttr(&line, h.groups, attr) @@ -140,7 +140,7 @@ func appendAttr(b *strings.Builder, groups []string, attr slog.Attr) { } key.WriteString(attr.Key) b.WriteByte(' ') - b.WriteString(secret.RedactPatterns(quote(key.String()) + "=" + quote(attr.Value.String()))) + b.WriteString(redact.Patterns(quote(key.String()) + "=" + quote(attr.Value.String()))) } // quote returns s as plain text, in double quotes when it is empty or holds diff --git a/pick/list.go b/pick/list.go index aef9c1c..bdead6e 100644 --- a/pick/list.go +++ b/pick/list.go @@ -1,10 +1,8 @@ package pick import ( - "fmt" "math" "slices" - "strconv" "strings" "github.com/mittwald/cli-kit/theme" @@ -183,25 +181,6 @@ func newList(opts Options, height int, color bool) *list { return l } -// plainViews copies the views with what they draw made plain text. The copy -// is the list's own, so rows a view loads never show up in the caller's. -func plainViews(views []View) []View { - plain := slices.Clone(views) - for i := range plain { - plain[i].Name = plainLine(plain[i].Name) - plain[i].Title = plainLine(plain[i].Title) - plain[i].Loading = plainLine(plain[i].Loading) - plain[i].Empty = plainLine(plain[i].Empty) - } - return plain -} - -// viewLabel names a view in the status line and in a Lens: its name, or its -// position, counted from 1, when it has none. -func (l *list) viewLabel(view int) string { - return firstNonEmpty(l.views[view].Name, strconv.Itoa(view+1)) -} - // moveToItem puts the cursor on the item with the index Options.Initial // names. Initial names an item, and the cursor stands among the matches: an // item the filter or view hides, or an index out of range, leaves the cursor @@ -238,9 +217,6 @@ func (l *list) setItems(items []Item) { } } -// switchable reports whether there are views to switch between. -func (l *list) switchable() bool { return len(l.views) > 1 } - // lens is the filter and the view the list stands on now. A list without // views to switch between leaves the view in was alone, so a list of another // shape asked in between does not lose it for the next. @@ -489,119 +465,6 @@ func (l *list) narrowed() bool { return !l.scoped && len(l.views) > 0 && len(l.views[l.view].Groups) > 0 } -// switchView moves delta views along, wrapping at both ends. It does nothing -// while a range is open or when there is no view to switch to. -func (l *list) switchView(delta int) { - if !l.switchable() || l.anchor >= 0 { - return - } - n := len(l.views) - if !l.scoped { - l.view = (l.view + delta + n) % n - l.applyViewTitle() - l.setFilter(l.filter) - return - } - key := "" - if index := l.selected(); index >= 0 && index < len(l.items) { - key = l.items[index].Key - } - l.view = (l.view + delta + n) % n - // Initial was about the view the list opened on. - l.initial = 0 - l.pendingKey = "" - if l.loading() { - l.pendingKey = key - } - l.loadView(key) -} - -// applyViewTitle shows the current view's title, or the options' title for -// a view without one. -func (l *list) applyViewTitle() { - if len(l.views) > 0 { - l.title = firstNonEmpty(l.views[l.view].Title, l.fallback) - } -} - -// loadView makes the current view's own rows the ones on screen. The filter -// carries over, and the cursor lands on the row carrying key, or at the top. -func (l *list) loadView(key string) { - view := l.views[l.view] - l.applyViewTitle() - l.setItems(view.Items) - l.cursor, l.top = 0, 0 - l.applyFilter() - // The view the list opened on starts where Options.Initial says, also - // when its rows only arrive now. - if !l.loading() { - l.moveToItem(l.initial) - l.initial = 0 - } - if key != "" { - for position, index := range l.matches { - if l.items[index].Key == key { - l.cursor = position - break - } - } - } - l.scrollToCursor() -} - -// needsLoad reports whether the current view has rows to fetch and nobody -// fetching them yet. -func (l *list) needsLoad() bool { - return l.scoped && l.views[l.view].Load != nil && l.loads[l.view] == loadWaiting -} - -// loading reports whether the current view is still without the rows it -// loads: the fetch has not started yet, or has not come back. -func (l *list) loading() bool { - return l.scoped && l.views[l.view].Load != nil && l.loads[l.view] != loadDone -} - -// nextLoad hands the key loop the fetch of the current view's rows, once: -// a function that calls the view's Load, to be run off the key loop, whose -// result takes the rows into the list, back on the key loop. The key loop -// asks after a draw, so the view and its loading line are on screen while -// the fetch runs, and the list keeps taking keys meanwhile: Esc leaves it, -// Tab moves on to another view, and typing already filters what is to come. -func (l *list) nextLoad() func() func() { - if !l.needsLoad() { - return nil - } - view := l.view - load := l.views[view].Load - l.loads[view] = loadRunning - return func() func() { - items, err := load() - return func() { l.finishLoad(view, items, err) } - } -} - -// finishLoad takes the rows a view loaded. They go on screen when the list -// still stands on that view, with the cursor on the row it was to land on, -// and are kept for the view otherwise. -func (l *list) finishLoad(view int, items []Item, err error) { - l.loads[view] = loadDone - if err != nil { - // Whatever was gathered before the failure is still worth showing; - // with nothing gathered, the rows the view already had stay. - l.failures[view] = plainLine(err.Error()) - if len(items) == 0 { - return - } - } - l.views[view].Items = items - if view != l.view { - return - } - key := l.pendingKey - l.pendingKey = "" - l.loadView(key) -} - // toggleMark marks the row under the cursor or unmarks it. The cursor stays, // so the mark is seen landing and a second Space takes it back. A disabled // row cannot be marked. A typed row becomes a row of its own as it is @@ -769,280 +632,3 @@ func (l *list) scrollToCursor() { } l.top = max(min(l.top, len(l.matches)-l.visible), 0) } - -func (l *list) painter() painter { return painter{color: l.color, theme: l.theme} } - -func (l *list) styled(style theme.Style, text string) string { - return l.painter().paint(style, text) -} - -// render returns the block to draw, one string per terminal line, already cut -// to width. The caller owns cursor movement and erasing. -func (l *list) render(width int) []string { - if width <= 0 { - width = 80 - } - th := l.theme - widths := l.fittedWidths(width) - lines := make([]string, 0, l.visible+6) - if l.frame.title { - lines = append(lines, l.renderTitle(width)) - } - if l.frame.note { - lines = append(lines, l.styled(th.Muted, cut(l.note, width))) - } - if l.frame.gapAbove { - lines = append(lines, "") - } - end := min(l.top+l.visible, len(l.matches)) - for position := l.top; position < end; position++ { - lines = append(lines, l.renderRowWith(position, width, widths)) - } - if len(l.matches) == 0 { - text, style := l.emptyLine() - lines = append(lines, l.styled(style, cut(text, width))) - } - if l.frame.gapBelow { - lines = append(lines, "") - } - if l.frame.position { - lines = append(lines, l.renderPosition(width)) - } - if l.frame.hint { - lines = append(lines, l.styled(firstStyle(l.hintStyle, th.Muted), l.hint(width))) - } - return lines -} - -// emptyLine says why there are no rows: the view is still loading, it failed -// to load, the filter matched nothing, or the view holds nothing. -func (l *list) emptyLine() (string, theme.Style) { - var view View - if len(l.views) > 0 { - view = l.views[l.view] - } - switch { - case l.loading(): - return " " + firstNonEmpty(view.Loading, "loading…"), firstStyle(l.emptyStyle, l.theme.Muted) - case len(l.views) > 0 && l.failures[l.view] != "": - return " " + l.failures[l.view], l.theme.Warning - case len(l.filter) > 0: - return " no match", firstStyle(l.emptyStyle, l.theme.Muted) - } - return " " + firstNonEmpty(view.Empty, "nothing here"), firstStyle(l.emptyStyle, l.theme.Muted) -} - -// hint names the keys of the state the list is in, in as much detail as the -// terminal has room for. -func (l *list) hint(width int) string { - if l.keyLine != "" { - return cut(l.keyLine, width) - } - if l.anchor >= 0 { - return fitHint( - "↑/↓ extend · PgUp/PgDn page · Enter selects the range · Esc drops it", - "↑/↓ extend · Enter selects · Esc drops the range", width) - } - enter := "Enter select" - if l.rangeMode { - enter = "Enter opens the range" - } - esc := firstNonEmpty(l.keys.Cancel, "Esc cancel") - if l.nested { - esc = firstNonEmpty(l.keys.Back, "Esc back") - } - view := firstNonEmpty(l.keys.View, "Tab view") - viewShort := firstNonEmpty(l.keys.ViewShort, view) - long := []string{"↑/↓ move", "PgUp/PgDn page"} - short := []string{"↑/↓ move"} - if l.switchable() && !l.keys.ViewLast { - long = append(long, view) - short = append(short, viewShort) - } - if l.multi { - long = append(long, "Space mark") - short = append(short, "Space mark") - } - long = append(long, "type to filter", "Ctrl-U clear", enter, esc) - short = append(short, "type to filter", enter, esc) - if l.switchable() && l.keys.ViewLast { - long = append(long, view) - short = append(short, viewShort) - } - return fitHint(strings.Join(long, separator), strings.Join(short, separator), width) -} - -// renderTitle draws the question, the subject in the theme's subject style, -// followed by the details of the row under the cursor or the summary of an -// open range. -func (l *list) renderTitle(width int) string { - parts := titleParts(l.title, l.subject, l.theme) - if l.anchor >= 0 { - parts = append(parts, l.spanParts()...) - } else if index := l.selected(); index >= 0 { - parts = append(parts, l.detailParts(l.row(index))...) - } - return drawParts(parts, width, l.painter()) -} - -func (l *list) detailStyleOrDefault() theme.Style { - if l.detailStyle != "" { - return l.detailStyle - } - return l.theme.Detail -} - -// detailParts is what the title line says about the row under the cursor. -func (l *list) detailParts(item Item) []styledText { - if len(item.Details) == 0 { - if item.Detail == "" { - return nil - } - return []styledText{{" ", ""}, l.paintedPart(item.Detail, l.detailStyleOrDefault(), l.paintDetail)} - } - var parts []styledText - for _, field := range item.Details { - if field.Text == "" { - continue - } - parts = append(parts, styledText{separator, l.theme.Muted}, l.paintedPart(field.Text, field.Style, field.Paint)) - } - return parts -} - -// paintedPart is text in base, or as paint paints it where color is on and -// paint only adds colors to it. -func (l *list) paintedPart(text string, base theme.Style, paint func(string, theme.Style) string) styledText { - if l.color && paint != nil && text != "" { - if painted := paint(text, base); paintedFrom(painted, text) { - return styledText{painted, ""} - } - } - return styledText{text, base} -} - -// spanParts summarizes an open range after the title: how many rows it -// covers and, where both ends carry a Detail, the two ends. -func (l *list) spanParts() []styledText { - size := l.spanSize() - count := strconv.Itoa(size) - if l.unit != "" { - count += " " + l.unit - if size != 1 { - count += "s" - } - } - parts := []styledText{{" " + count, l.theme.Muted}} - first, last := l.selectedRange() - if first < 0 { - return parts - } - from, to := l.row(last).Detail, l.row(first).Detail - if from == "" || to == "" { - return parts - } - // Oldest first, the way a range is written: "from..to". - style := l.detailStyleOrDefault() - return append(parts, styledText{separator, l.theme.Muted}, l.paintedPart(from, style, l.paintDetail), - styledText{"..", l.theme.Muted}, l.paintedPart(to, style, l.paintDetail)) -} - -// position is the position line as plain text. -func (l *list) position() string { - var b strings.Builder - for _, part := range l.positionParts() { - b.WriteString(part.text) - } - return b.String() -} - -// positionPart is a stretch of the position line. Active parts are what the -// user set, the view showing and the filter typed, and are not muted; style -// overrides the muted style, or the terminal's color of an active part. -type positionPart struct { - text string - active bool - style theme.Style -} - -func (l *list) positionParts() []positionPart { - count := fmt.Sprintf("%d of %d", l.cursor+1, len(l.matches)) - if len(l.matches) == 0 { - count = fmt.Sprintf("0 of %d", len(l.items)) - } - if l.switchable() || len(l.filter) > 0 { - // Whatever follows the count keeps its place while the count changes - // length. - count = pad(count, l.countWidth()) - } - parts := []positionPart{{text: count}} - if l.switchable() { - // A view an open range has set aside is not the one in force. - inForce := l.anchor < 0 || !l.narrowed() - for i := range l.views { - label := l.viewLabel(i) - if i == l.view && inForce { - parts = append(parts, positionPart{text: separator}, positionPart{text: "[" + label + "]", active: true, style: l.activeView}) - continue - } - if l.hintStyle == "" { - parts = append(parts, positionPart{text: separator + label}) - continue - } - parts = append(parts, positionPart{text: separator}, positionPart{text: label, style: l.hintStyle}) - } - } - if l.loading() { - parts = append(parts, positionPart{text: separator + firstNonEmpty(l.views[l.view].Loading, "loading…")}) - } else if len(l.views) > 0 && l.failures[l.view] != "" && len(l.items) > 0 { - // With no rows at all the failure stands in their place instead. - parts = append(parts, positionPart{text: separator}, positionPart{text: l.failures[l.view], style: l.theme.Warning}) - } - if len(l.filter) > 0 { - parts = append(parts, positionPart{text: separator + "filter: "}, positionPart{text: string(l.filter), active: true}) - } - if len(l.marked) > 0 { - parts = append(parts, positionPart{text: separator}, positionPart{text: fmt.Sprintf("%d marked", len(l.marked)), active: true}) - } - if index := l.selected(); index >= 0 && l.row(index).Disabled { - parts = append(parts, positionPart{text: separator + "nothing to do"}) - } - return parts -} - -// countWidth is room for the widest count the list can show. -func (l *list) countWidth() int { - total := max(len(l.items), 999) - return width(fmt.Sprintf("%d of %d", total, total)) -} - -// renderPosition draws the position line muted, except for the parts the -// user set. -func (l *list) renderPosition(n int) string { - var b strings.Builder - left := n - for _, part := range l.positionParts() { - if left <= 0 { - break - } - text := cut(part.text, left) - left -= width(text) - style := l.theme.Muted - switch { - case part.style != "": - style = part.style - case part.active: - style = "" - } - b.WriteString(l.styled(style, text)) - } - return b.String() -} - -// firstStyle returns style, or fallback when style is empty. -func firstStyle(style, fallback theme.Style) theme.Style { - if style != "" { - return style - } - return fallback -} diff --git a/pick/list_render.go b/pick/list_render.go new file mode 100644 index 0000000..47cd4e5 --- /dev/null +++ b/pick/list_render.go @@ -0,0 +1,286 @@ +package pick + +import ( + "fmt" + "strconv" + "strings" + + "github.com/mittwald/cli-kit/theme" +) + +func (l *list) painter() painter { return painter{color: l.color, theme: l.theme} } + +func (l *list) styled(style theme.Style, text string) string { + return l.painter().paint(style, text) +} + +// render returns the block to draw, one string per terminal line, already cut +// to width. The caller owns cursor movement and erasing. +func (l *list) render(width int) []string { + if width <= 0 { + width = 80 + } + th := l.theme + widths := l.fittedWidths(width) + lines := make([]string, 0, l.visible+6) + if l.frame.title { + lines = append(lines, l.renderTitle(width)) + } + if l.frame.note { + lines = append(lines, l.styled(th.Muted, cut(l.note, width))) + } + if l.frame.gapAbove { + lines = append(lines, "") + } + end := min(l.top+l.visible, len(l.matches)) + for position := l.top; position < end; position++ { + lines = append(lines, l.renderRowWith(position, width, widths)) + } + if len(l.matches) == 0 { + text, style := l.emptyLine() + lines = append(lines, l.styled(style, cut(text, width))) + } + if l.frame.gapBelow { + lines = append(lines, "") + } + if l.frame.position { + lines = append(lines, l.renderPosition(width)) + } + if l.frame.hint { + lines = append(lines, l.styled(firstStyle(l.hintStyle, th.Muted), l.hint(width))) + } + return lines +} + +// emptyLine says why there are no rows: the view is still loading, it failed +// to load, the filter matched nothing, or the view holds nothing. +func (l *list) emptyLine() (string, theme.Style) { + var view View + if len(l.views) > 0 { + view = l.views[l.view] + } + switch { + case l.loading(): + return " " + firstNonEmpty(view.Loading, "loading…"), firstStyle(l.emptyStyle, l.theme.Muted) + case len(l.views) > 0 && l.failures[l.view] != "": + return " " + l.failures[l.view], l.theme.Warning + case len(l.filter) > 0: + return " no match", firstStyle(l.emptyStyle, l.theme.Muted) + } + return " " + firstNonEmpty(view.Empty, "nothing here"), firstStyle(l.emptyStyle, l.theme.Muted) +} + +// hint names the keys of the state the list is in, in as much detail as the +// terminal has room for. +func (l *list) hint(width int) string { + if l.keyLine != "" { + return cut(l.keyLine, width) + } + if l.anchor >= 0 { + return fitHint( + "↑/↓ extend · PgUp/PgDn page · Enter selects the range · Esc drops it", + "↑/↓ extend · Enter selects · Esc drops the range", width) + } + enter := "Enter select" + if l.rangeMode { + enter = "Enter opens the range" + } + esc := firstNonEmpty(l.keys.Cancel, "Esc cancel") + if l.nested { + esc = firstNonEmpty(l.keys.Back, "Esc back") + } + view := firstNonEmpty(l.keys.View, "Tab view") + viewShort := firstNonEmpty(l.keys.ViewShort, view) + long := []string{"↑/↓ move", "PgUp/PgDn page"} + short := []string{"↑/↓ move"} + if l.switchable() && !l.keys.ViewLast { + long = append(long, view) + short = append(short, viewShort) + } + if l.multi { + long = append(long, "Space mark") + short = append(short, "Space mark") + } + long = append(long, "type to filter", "Ctrl-U clear", enter, esc) + short = append(short, "type to filter", enter, esc) + if l.switchable() && l.keys.ViewLast { + long = append(long, view) + short = append(short, viewShort) + } + return fitHint(strings.Join(long, separator), strings.Join(short, separator), width) +} + +// renderTitle draws the question, the subject in the theme's subject style, +// followed by the details of the row under the cursor or the summary of an +// open range. +func (l *list) renderTitle(width int) string { + parts := titleParts(l.title, l.subject, l.theme) + if l.anchor >= 0 { + parts = append(parts, l.spanParts()...) + } else if index := l.selected(); index >= 0 { + parts = append(parts, l.detailParts(l.row(index))...) + } + return drawParts(parts, width, l.painter()) +} + +func (l *list) detailStyleOrDefault() theme.Style { + if l.detailStyle != "" { + return l.detailStyle + } + return l.theme.Detail +} + +// detailParts is what the title line says about the row under the cursor. +func (l *list) detailParts(item Item) []styledText { + if len(item.Details) == 0 { + if item.Detail == "" { + return nil + } + return []styledText{{" ", ""}, l.paintedPart(item.Detail, l.detailStyleOrDefault(), l.paintDetail)} + } + var parts []styledText + for _, field := range item.Details { + if field.Text == "" { + continue + } + parts = append(parts, styledText{separator, l.theme.Muted}, l.paintedPart(field.Text, field.Style, field.Paint)) + } + return parts +} + +// paintedPart is text in base, or as paint paints it where color is on and +// paint only adds colors to it. +func (l *list) paintedPart(text string, base theme.Style, paint func(string, theme.Style) string) styledText { + if l.color && paint != nil && text != "" { + if painted := paint(text, base); paintedFrom(painted, text) { + return styledText{painted, ""} + } + } + return styledText{text, base} +} + +// spanParts summarizes an open range after the title: how many rows it +// covers and, where both ends carry a Detail, the two ends. +func (l *list) spanParts() []styledText { + size := l.spanSize() + count := strconv.Itoa(size) + if l.unit != "" { + count += " " + l.unit + if size != 1 { + count += "s" + } + } + parts := []styledText{{" " + count, l.theme.Muted}} + first, last := l.selectedRange() + if first < 0 { + return parts + } + from, to := l.row(last).Detail, l.row(first).Detail + if from == "" || to == "" { + return parts + } + // Oldest first, the way a range is written: "from..to". + style := l.detailStyleOrDefault() + return append(parts, styledText{separator, l.theme.Muted}, l.paintedPart(from, style, l.paintDetail), + styledText{"..", l.theme.Muted}, l.paintedPart(to, style, l.paintDetail)) +} + +// position is the position line as plain text. +func (l *list) position() string { + var b strings.Builder + for _, part := range l.positionParts() { + b.WriteString(part.text) + } + return b.String() +} + +// positionPart is a stretch of the position line. Active parts are what the +// user set, the view showing and the filter typed, and are not muted; style +// overrides the muted style, or the terminal's color of an active part. +type positionPart struct { + text string + active bool + style theme.Style +} + +func (l *list) positionParts() []positionPart { + count := fmt.Sprintf("%d of %d", l.cursor+1, len(l.matches)) + if len(l.matches) == 0 { + count = fmt.Sprintf("0 of %d", len(l.items)) + } + if l.switchable() || len(l.filter) > 0 { + // Whatever follows the count keeps its place while the count changes + // length. + count = pad(count, l.countWidth()) + } + parts := []positionPart{{text: count}} + if l.switchable() { + // A view an open range has set aside is not the one in force. + inForce := l.anchor < 0 || !l.narrowed() + for i := range l.views { + label := l.viewLabel(i) + if i == l.view && inForce { + parts = append(parts, positionPart{text: separator}, positionPart{text: "[" + label + "]", active: true, style: l.activeView}) + continue + } + if l.hintStyle == "" { + parts = append(parts, positionPart{text: separator + label}) + continue + } + parts = append(parts, positionPart{text: separator}, positionPart{text: label, style: l.hintStyle}) + } + } + if l.loading() { + parts = append(parts, positionPart{text: separator + firstNonEmpty(l.views[l.view].Loading, "loading…")}) + } else if len(l.views) > 0 && l.failures[l.view] != "" && len(l.items) > 0 { + // With no rows at all the failure stands in their place instead. + parts = append(parts, positionPart{text: separator}, positionPart{text: l.failures[l.view], style: l.theme.Warning}) + } + if len(l.filter) > 0 { + parts = append(parts, positionPart{text: separator + "filter: "}, positionPart{text: string(l.filter), active: true}) + } + if len(l.marked) > 0 { + parts = append(parts, positionPart{text: separator}, positionPart{text: fmt.Sprintf("%d marked", len(l.marked)), active: true}) + } + if index := l.selected(); index >= 0 && l.row(index).Disabled { + parts = append(parts, positionPart{text: separator + "nothing to do"}) + } + return parts +} + +// countWidth is room for the widest count the list can show. +func (l *list) countWidth() int { + total := max(len(l.items), 999) + return width(fmt.Sprintf("%d of %d", total, total)) +} + +// renderPosition draws the position line muted, except for the parts the +// user set. +func (l *list) renderPosition(n int) string { + var b strings.Builder + left := n + for _, part := range l.positionParts() { + if left <= 0 { + break + } + text := cut(part.text, left) + left -= width(text) + style := l.theme.Muted + switch { + case part.style != "": + style = part.style + case part.active: + style = "" + } + b.WriteString(l.styled(style, text)) + } + return b.String() +} + +// firstStyle returns style, or fallback when style is empty. +func firstStyle(style, fallback theme.Style) theme.Style { + if style != "" { + return style + } + return fallback +} diff --git a/pick/list_views.go b/pick/list_views.go new file mode 100644 index 0000000..f2626eb --- /dev/null +++ b/pick/list_views.go @@ -0,0 +1,141 @@ +package pick + +import ( + "slices" + "strconv" +) + +// plainViews copies the views with what they draw made plain text. The copy +// is the list's own, so rows a view loads never show up in the caller's. +func plainViews(views []View) []View { + plain := slices.Clone(views) + for i := range plain { + plain[i].Name = plainLine(plain[i].Name) + plain[i].Title = plainLine(plain[i].Title) + plain[i].Loading = plainLine(plain[i].Loading) + plain[i].Empty = plainLine(plain[i].Empty) + } + return plain +} + +// viewLabel names a view in the status line and in a Lens: its name, or its +// position, counted from 1, when it has none. +func (l *list) viewLabel(view int) string { + return firstNonEmpty(l.views[view].Name, strconv.Itoa(view+1)) +} + +// switchable reports whether there are views to switch between. +func (l *list) switchable() bool { return len(l.views) > 1 } + +// switchView moves delta views along, wrapping at both ends. It does nothing +// while a range is open or when there is no view to switch to. +func (l *list) switchView(delta int) { + if !l.switchable() || l.anchor >= 0 { + return + } + n := len(l.views) + if !l.scoped { + l.view = (l.view + delta + n) % n + l.applyViewTitle() + l.setFilter(l.filter) + return + } + key := "" + if index := l.selected(); index >= 0 && index < len(l.items) { + key = l.items[index].Key + } + l.view = (l.view + delta + n) % n + // Initial was about the view the list opened on. + l.initial = 0 + l.pendingKey = "" + if l.loading() { + l.pendingKey = key + } + l.loadView(key) +} + +// applyViewTitle shows the current view's title, or the options' title for +// a view without one. +func (l *list) applyViewTitle() { + if len(l.views) > 0 { + l.title = firstNonEmpty(l.views[l.view].Title, l.fallback) + } +} + +// loadView makes the current view's own rows the ones on screen. The filter +// carries over, and the cursor lands on the row carrying key, or at the top. +func (l *list) loadView(key string) { + view := l.views[l.view] + l.applyViewTitle() + l.setItems(view.Items) + l.cursor, l.top = 0, 0 + l.applyFilter() + // The view the list opened on starts where Options.Initial says, also + // when its rows only arrive now. + if !l.loading() { + l.moveToItem(l.initial) + l.initial = 0 + } + if key != "" { + for position, index := range l.matches { + if l.items[index].Key == key { + l.cursor = position + break + } + } + } + l.scrollToCursor() +} + +// needsLoad reports whether the current view has rows to fetch and nobody +// fetching them yet. +func (l *list) needsLoad() bool { + return l.scoped && l.views[l.view].Load != nil && l.loads[l.view] == loadWaiting +} + +// loading reports whether the current view is still without the rows it +// loads: the fetch has not started yet, or has not come back. +func (l *list) loading() bool { + return l.scoped && l.views[l.view].Load != nil && l.loads[l.view] != loadDone +} + +// nextLoad hands the key loop the fetch of the current view's rows, once: +// a function that calls the view's Load, to be run off the key loop, whose +// result takes the rows into the list, back on the key loop. The key loop +// asks after a draw, so the view and its loading line are on screen while +// the fetch runs, and the list keeps taking keys meanwhile: Esc leaves it, +// Tab moves on to another view, and typing already filters what is to come. +func (l *list) nextLoad() func() func() { + if !l.needsLoad() { + return nil + } + view := l.view + load := l.views[view].Load + l.loads[view] = loadRunning + return func() func() { + items, err := load() + return func() { l.finishLoad(view, items, err) } + } +} + +// finishLoad takes the rows a view loaded. They go on screen when the list +// still stands on that view, with the cursor on the row it was to land on, +// and are kept for the view otherwise. +func (l *list) finishLoad(view int, items []Item, err error) { + l.loads[view] = loadDone + if err != nil { + // Whatever was gathered before the failure is still worth showing; + // with nothing gathered, the rows the view already had stay. + l.failures[view] = plainLine(err.Error()) + if len(items) == 0 { + return + } + } + l.views[view].Items = items + if view != l.view { + return + } + key := l.pendingKey + l.pendingKey = "" + l.loadView(key) +} diff --git a/redact/doc.go b/redact/doc.go new file mode 100644 index 0000000..942eb14 --- /dev/null +++ b/redact/doc.go @@ -0,0 +1,17 @@ +// Package redact removes credentials from text before it is logged, stored +// or shown. +// +// [Values] removes secrets a program knows, such as the token it just sent, +// as they are and in the forms they take inside a request: URL-escaped and +// JSON-escaped. It does not find a secret inside a larger encoded value, +// such as the Base64 string of HTTP Basic authentication. +// +// [Patterns] removes the credentials it recognizes by their shape, for text +// from elsewhere whose secrets are not known: labeled assignments such as +// password=…, Bearer tokens, and tokens whose prefix names their issuer. +// It is a safety net, not a substitute for [Values]. +// +// Both replace what they find with [Marker]. The package depends on the +// standard library only, so a logger can redact without pulling in a +// keyring or a terminal. +package redact diff --git a/redact/example_test.go b/redact/example_test.go new file mode 100644 index 0000000..16711be --- /dev/null +++ b/redact/example_test.go @@ -0,0 +1,21 @@ +package redact_test + +import ( + "fmt" + + "github.com/mittwald/cli-kit/redact" +) + +func ExampleValues() { + token := "glpat-abc123" + fmt.Println(redact.Values("GET /api?private_token=glpat-abc123", token)) + // Output: GET /api?private_token=[REDACTED] +} + +func ExamplePatterns() { + fmt.Println(redact.Patterns(`{"user":"alice","password":"hunter2"}`)) + fmt.Println(redact.Patterns("https://example.com/hook?token=abc123&page=2")) + // Output: + // {"user":"alice","password":"[REDACTED]"} + // https://example.com/hook?token=[REDACTED] +} diff --git a/redact/fuzz_test.go b/redact/fuzz_test.go new file mode 100644 index 0000000..35c4d40 --- /dev/null +++ b/redact/fuzz_test.go @@ -0,0 +1,52 @@ +package redact + +import ( + "encoding/json" + "strings" + "testing" +) + +// No occurrence of a secret survives Values. A secret that is part of the +// marker, or that holds one of its brackets and so can line up with a +// marker and the text beside it, is left out: the marker itself is not +// what the check is about. +func FuzzValues(f *testing.F) { + f.Add("token=abc123 again abc123", "abc123") + f.Add("-aaa-", "aa") + f.Add(`{"password":"p@ss w\/rd&"}`, "p@ss w/rd&") + f.Add("?pw=%25%FF", "%\xff") + f.Fuzz(func(t *testing.T, text, secret string) { + got := Values(text, secret) + if secret == "" || strings.Contains(Marker, secret) || strings.ContainsAny(secret, "[]") { + return + } + if strings.Contains(got, secret) { + t.Fatalf("Values(%q, %q) = %q, still holds the secret", text, secret, got) + } + }) +} + +// Patterns never turns valid JSON into something else, as its +// documentation promises. +func FuzzPatternsKeepsJSONValid(f *testing.F) { + for _, seed := range []string{ + `{"api_key":"sk-secretvalue","n":1}`, + `{"token": 12345, "ok": true}`, + `{"message":"token=abc def"}`, + `{"body":"{\"password\":\"x y\"}"}`, + `{"token":["abc]secret","d}e\"]"],"n":1}`, + `{"m":"token: [\"a]\", \"b\"] rest"}`, + "{\"password\":\n \"hunter2\"}", + `["auth=Basic dXNlcjpwYXNz", "secret: 'x'"]`, + "password: |\n a\n b\nnext: 1", + "Authorization: Bearer abcdefgh.ijklmnop", + } { + f.Add(seed) + } + f.Fuzz(func(t *testing.T, in string) { + got := Patterns(in) + if json.Valid([]byte(in)) && !json.Valid([]byte(got)) { + t.Fatalf("Patterns(%q) = %q, not valid JSON", in, got) + } + }) +} diff --git a/redact/patterns.go b/redact/patterns.go new file mode 100644 index 0000000..3527993 --- /dev/null +++ b/redact/patterns.go @@ -0,0 +1,675 @@ +package redact + +import ( + "regexp" + "strings" +) + +// The shapes [Patterns] looks for. +var ( + // labelPattern is the name of a credential and what assigns it a value, + // in JSON, YAML, an environment file or a query: the name, quoted or + // not, also in the backslash-escaped quotes of JSON inside a JSON + // string (group 1 is the quote after it), then a colon or an equals + // sign, with spaces and tabs around it but no line break. The value + // that follows is read by labeledValue. + labelPattern = regexp.MustCompile(`(?i)(?:\\?["'])?(?:(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|token|secret|password|credential|authorization|auth))(\\?["'])?[ \t]*[:=][ \t]*`) + // schemePattern is the scheme of an HTTP authorization at the start of + // an unquoted value, which the credential after it belongs to. + schemePattern = regexp.MustCompile(`(?i)^(?:Basic|Bearer|Bot|Digest|Negotiate|Token)[ \t]+`) + // bearerPattern is the credential of an HTTP Bearer authorization. + bearerPattern = regexp.MustCompile(`(?i)\bBearer\s+[A-Za-z0-9._~+/=-]{8,}`) + // prefixedPattern is a token whose prefix names its issuer: OpenAI and + // Anthropic (sk-), GitHub (ghp_, gho_, ghu_, ghs_, ghr_), GitLab + // (glpat-) and an AWS access key ID (AKIA). + prefixedPattern = regexp.MustCompile(`(?i)\b(?:sk-[A-Za-z0-9_-]{8,}|gh[pousr]_[A-Za-z0-9]{8,}|glpat-[A-Za-z0-9_-]{8,}|AKIA[A-Z0-9]{16,})`) + // propertiesPattern is the tags and anchors of a YAML node in front of + // its value: !!str, !secret, a verbatim !, &name, + // followed by white space or the end of their line, below which the + // value may stand. + propertiesPattern = regexp.MustCompile(`(?m)\A(?:(?:!<[^>\s]*>|[!&][^\s,\[\]{}]*)(?:[ \t]+|$))+`) + // blockPattern is the header of a YAML block scalar, | or > with its + // chomping and indentation indicators, up to the end of its line. + blockPattern = regexp.MustCompile(`^[|>][-+0-9]*[ \t]*(?:#[^\n]*)?(?:\r?\n|$)`) +) + +// Patterns returns text with the credentials it can recognize by +// their shape replaced by [Marker]. Use it where the secrets are not known +// in advance, as they are for [Values]: on what a server, a model or a log +// file says, before it is stored or shown. It replaces +// +// - the value of a labeled assignment, in JSON, YAML, an environment +// file or a query string, whose name ends in api_key, access_token, +// token, secret, password, credential, authorization or auth, in any +// case and with "-" or "_" between the words; +// - the credential after "Bearer "; +// - tokens whose prefix names their issuer: sk-, ghp_, gho_, ghu_, ghs_, +// ghr_, glpat- and the AKIA of an AWS access key ID. +// +// The value of an assignment is read the way the formats write it, so that +// none of it is left behind and the text keeps its structure: +// +// - A quoted value keeps its quotes: {"api_key":"sk-…"} becomes +// {"api_key":"[REDACTED]"}. Backslash escapes and the doubled quotes +// of YAML ('it”s') are part of the value. +// - An unquoted value is replaced without quotes, DB_PASSWORD=hunter2 +// becomes DB_PASSWORD=[REDACTED], unless it is the value of a quoted +// JSON name, {"token": 12345}, which becomes {"token": "[REDACTED]"} so +// that JSON stays JSON. It runs up to white space, a comma, a +// semicolon, a closing brace or a quote, so the rest of a query string +// after a credential goes with it, and takes the scheme of an HTTP +// authorization along: "Authorization: Basic …" becomes +// "Authorization: [REDACTED]". +// - An array or an object is replaced as a whole, nested ones and +// brackets inside its strings included: {"token": ["a", "b"]} becomes +// {"token": "[REDACTED]"}. +// - An HTTP authorization with a scheme, such as "Authorization: Digest +// username=…, response=…", is replaced up to the end of its line. +// - A YAML block scalar, password: | or >, and a value on the lines +// indented below its name, are replaced with all of those lines. A +// name without a value on its line or below it, as in an empty +// PASSWORD= followed by the next setting, is left alone. +// - The value of a JSON name may stand on a later line. The tags and +// anchors of a YAML value, password: !!str hunter2, go with it, and a +// comment after the name stays while the value below it goes. +// - An assignment inside a JSON string, as in +// {"message":"token=abc def"}, is replaced inside the string, and its +// value ends at the latest where the string does. A value in the +// escaped quotes of JSON inside a JSON string keeps them. +// - A quoted value, an array or an object that is never closed, in text +// cut short, is replaced up to the end of the text, or of the JSON +// string it is in. +// +// A secret without a label or a known prefix looks like any other word and +// stays. Patterns is a safety net for text from elsewhere, not a +// substitute for [Values] with the secrets a program holds itself. +func Patterns(text string) string { + if text == "" { + return text + } + text = redactLabeled(text) + text = bearerPattern.ReplaceAllString(text, "Bearer "+Marker) + return prefixedPattern.ReplaceAllString(text, Marker) +} + +// redactLabeled replaces the value of every labeled assignment in text. +func redactLabeled(text string) string { + var ( + b strings.Builder + inStrings jsonStrings + ) + pos := 0 + for pos < len(text) { + m := labelPattern.FindStringSubmatchIndex(text[pos:]) + if m == nil { + break + } + for i := range m { + if m[i] >= 0 { + m[i] += pos + } + } + start := m[1] + jsonName := m[2] >= 0 && text[m[2]:m[3]] == `"` + end, replacement := labeledValue(text, start, m[0], inStrings.inside(text, start), jsonName) + b.WriteString(text[pos:start]) + if end == start { + // No value: nothing to replace, and the label is passed by. + pos = start + continue + } + b.WriteString(replacement) + pos = end + } + b.WriteString(text[pos:]) + return b.String() +} + +// labeledValue reads the value that starts at start, after a label that +// starts at label, and returns where it ends and what replaces it. inString +// says whether the value lies inside a JSON string, jsonName whether the +// label is a quoted JSON name. A value of nothing ends at start. +// +// The value of a JSON name may follow on a later line, after JSON white +// space, which is kept. The tags and anchors of a YAML node in front of a +// value (!!str, &name) are replaced with it. +func labeledValue(text string, start, label int, inString, jsonName bool) (int, string) { + from := start + if jsonName && !inString { + for from < len(text) && strings.IndexByte(" \t\r\n", text[from]) >= 0 { + from++ + } + // A quoted name is YAML as often as JSON. A value on a later line + // that cannot start a JSON value, such as a YAML sequence or block, + // is left to the YAML rules, which take all of it. + if strings.ContainsRune(text[start:from], '\n') && (!jsonMember(text, label) || !jsonValueStart(text[from:])) { + from = start + } + } + properties := 0 + if !inString { + if loc := propertiesPattern.FindStringIndex(text[from:]); loc != nil && loc[0] == 0 { + properties = loc[1] + } + } + comment := "" + if at := from + properties; !inString && at > 0 && (text[at-1] == ' ' || text[at-1] == '\t') && + strings.HasPrefix(text[at:], "#") { + // A YAML comment ends the line; the value may stand below it. + comment = text[at:] + if i := strings.IndexByte(comment, '\n'); i >= 0 { + comment = strings.TrimSuffix(comment[:i], "\r") + } + } + at := from + properties + len(comment) + end, replacement := valueAt(text, at, label, inString, jsonName) + if end == at { + return start, "" + } + return end, text[start:from] + comment + replacement +} + +// valueAt is labeledValue for a value that starts right at start. +func valueAt(text string, start, label int, inString, jsonName bool) (int, string) { + rest := text[start:] + switch { + case rest == "": + return start, "" + case inString && rest[0] == '"' && closesString(text, start): + // No value before the end of the JSON string the assignment is in. + return start, "" + case inString && rest[0] == '"': + // A quote that does not end the string: what looked like a JSON + // string was a stray quote, as in the YAML {note: 5" screen, + // password: "…"}, and the value is a quoted string of its own. + return quotedEnd(text, start, false), `"` + Marker + `"` + case strings.HasPrefix(rest, `\"`): + return escapedStringEnd(text, start), `\"` + Marker + `\"` + case rest[0] == '"' || rest[0] == '\'': + return quotedEnd(text, start, inString), rest[:1] + Marker + rest[:1] + case rest[0] == '[' || rest[0] == '{': + return compositeEnd(text, start, inString), quoted(Marker, jsonName) + case !inString && (rest[0] == '\n' || strings.HasPrefix(rest, "\r\n")): + // Nothing on the line of the label: the value is on the lines + // indented below it, as YAML may write it, or there is none, as in + // an empty PASSWORD= followed by the next setting. + from := start + 1 + if rest[0] == '\r' { + from++ + } + end := blockEnd(text, from, lineIndent(text, label)) + if end == from { + // YAML lets a sequence stand at the indentation of its key. + end = sequenceEnd(text, from, lineIndent(text, label)) + } + if end == from { + return start, "" + } + // The value keeps the line and indentation of its first line that + // is not blank. + value := text[from:end] + for { + line, rest, more := strings.Cut(value, "\n") + if !more || strings.TrimSpace(line) != "" { + break + } + value = rest + } + indent := value[:len(value)-len(strings.TrimLeft(value, " \t"))] + return end, text[start:from] + indent + Marker + } + if header := blockPattern.FindString(rest); header != "" && !inString { + from := start + len(header) + end := blockEnd(text, from, lineIndent(text, label)) + if end == from { + // No lines below the header: its line break stays. + return end, Marker + lineBreakOf(header) + } + // The line break after the last line of the block stays. + return end, Marker + } + scheme := schemePattern.FindString(rest) + if scheme != "" { + if end := authorizationEnd(text, start+len(scheme), inString); end > start+len(scheme) { + return end, quoted(Marker, jsonName) + } + } + // A member of a flow mapping, YAML ({password: two words}) or JSON, + // ends its plain value at a comma or a closing bracket, not at a space + // or a line break: a YAML flow scalar may have both, and a JSON number + // or literal ends there anyway. + flow := !inString && jsonMember(text, label) + end := start + len(scheme) + for end < len(text) { + c := text[end] + if c == '\\' { + // An escape, \" inside a JSON string among them, is part of + // the value. + end = min(end+2, len(text)) + continue + } + if flow { + if strings.IndexByte(`,}]`, c) >= 0 { + break + } + } else if c <= ' ' || strings.IndexByte(`,;}"'`, c) >= 0 { + break + } + end++ + } + if flow { + end = start + len(strings.TrimRight(text[start:end], " \t\r\n")) + } + if end == start+len(scheme) { + // Nothing after a scheme: the scheme word is the value, as in + // auth=Basic. Nothing at all: no value. + end = start + len(strings.TrimRight(scheme, " \t")) + if end == start { + return start, "" + } + } + if !inString && !flow && ownLine(text, label) { + end = max(end, plainScalarEnd(text, start, lineIndent(text, label))) + } + return end, quoted(Marker, jsonName) +} + +// ownLine reports whether the label at label starts its line, white space +// and YAML sequence dashes aside, as a YAML key or a setting in a file of +// settings does. +func ownLine(text string, label int) bool { + lineStart := strings.LastIndexByte(text[:label], '\n') + 1 + return lineStart+lineIndent(text, label) == label +} + +// plainScalarEnd returns where a value that starts at start beside a label +// on its own line ends, read as a YAML plain scalar: at the end of the line +// or before a comment (" #") on it, and past the lines below that are +// indented further than indent, the indentation of the label's line, which +// continue it. +func plainScalarEnd(text string, start, indent int) int { + lineEnd := len(text) + if i := strings.IndexByte(text[start:], '\n'); i >= 0 { + lineEnd = start + i + } + line := text[start:lineEnd] + if i := strings.Index(line, " #"); i >= 0 { + line = line[:i] + } else if i := strings.Index(line, "\t#"); i >= 0 { + line = line[:i] + } + end := start + len(strings.TrimRight(line, " \t\r")) + if lineEnd < len(text) && len(line) == lineEnd-start { + if more := blockEnd(text, lineEnd+1, indent); more > lineEnd+1 { + end = more + } + } + return end +} + +// closesString reports whether the quote at i reads as the end of a JSON +// string: what follows it, after white space, is a comma, a closing bracket +// or brace, a colon, or the end of the line or of the text. +func closesString(text string, i int) bool { + for i++; i < len(text); i++ { + switch text[i] { + case ' ', '\t', '\r': + continue + case ',', '}', ']', ':', '\n': + return true + } + return false + } + return true +} + +// authorizationEnd returns where the credentials of an HTTP authorization +// that start at start end: at the end of the line, or inside a JSON string +// (inString) where that string ends, if that comes first. The parameters of +// a scheme such as Digest, username="…", nonce="…", response="…", are all +// part of them. +func authorizationEnd(text string, start int, inString bool) int { + for i := start; i < len(text); i++ { + switch text[i] { + case '\\': + i++ + case '\n': + return i - boolToInt(i > start && text[i-1] == '\r') + case '"': + if inString { + return i + } + } + } + return len(text) +} + +func boolToInt(b bool) int { + if b { + return 1 + } + return 0 +} + +// quotedEnd returns the index after the string in double or single quotes +// that starts at start. A string that is never closed ends with the text, +// or inside a JSON string (inString) where that string does. +// +// In double quotes a backslash escapes the character after it. Single +// quotes are read both ways they are written: with a backslash as an +// escape, as in Python or JavaScript, and, as in YAML and the shell, with a +// backslash as itself and a doubled quote standing for one. The string +// ends where the later of the two readings ends it, so that no reading +// leaves a part of it behind. +func quotedEnd(text string, start int, inString bool) int { + if text[start] == '\'' { + return max(stringEnd(text, start, inString, true, false), stringEnd(text, start, inString, false, true)) + } + return stringEnd(text, start, inString, true, false) +} + +// stringEnd is quotedEnd for one way of reading the string: escapes says +// whether a backslash escapes the character after it, doubled whether a +// doubled quote stands for one. +func stringEnd(text string, start int, inString, escapes, doubled bool) int { + quote := text[start] + for i := start + 1; i < len(text); i++ { + switch c := text[i]; { + case c == '\\' && (escapes || inString): + // Inside a JSON string a backslash escapes for that string, + // whatever the inner string makes of it: \" is no end there. + i++ + case c == quote && doubled && i+1 < len(text) && text[i+1] == quote: + i++ + case c == quote: + return i + 1 + case c == '"' && inString: + return i + } + } + return len(text) +} + +// escapedStringEnd returns the index after the string in the escaped quotes +// \" of JSON inside a JSON string that starts at start. Its own escaped +// quotes, \\\", are part of it. A string that is never closed ends where +// the enclosing JSON string does, or with the text. +func escapedStringEnd(text string, start int) int { + for i := start + 2; i < len(text); i++ { + switch text[i] { + case '"': + return i + case '\\': + if i+1 < len(text) && text[i+1] == '"' { + return i + 2 + } + if i+1 < len(text) && text[i+1] == '\\' { + // An escaped backslash of the enclosing string. Followed by + // \", it escapes a quote of the inner string, which is part + // of it; otherwise the character after it is read anew, so + // a quote there still ends the inner string. + if i+3 < len(text) && text[i+2] == '\\' && text[i+3] == '"' { + i += 3 + } else { + i++ + } + continue + } + i++ + } + } + return len(text) +} + +// blockEnd returns where the lines of a YAML block scalar end: before the +// line break ahead of the first line that is not blank and is indented no +// further than indent, the indentation of the line holding its key, or at +// the end of the text. from is where its first line starts. +func blockEnd(text string, from, indent int) int { + end := from + for line := from; line < len(text); { + next := strings.IndexByte(text[line:], '\n') + body := text[line:] + if next >= 0 { + body = text[line : line+next] + } + content := strings.TrimLeft(body, " \t") + if strings.TrimSpace(content) != "" && len(body)-len(content) <= indent { + break + } + end = line + len(strings.TrimRight(body, "\r")) + if next < 0 { + return len(text) + } + line += next + 1 + } + return end +} + +// sequenceEnd returns where a YAML sequence written at the indentation of its +// key ends: before the line break ahead of the first line that is not blank, +// is indented no further than indent and is not an item ("- …") at indent +// itself. from is where its first line starts; when that line is no item, +// there is no such sequence and sequenceEnd returns from. +func sequenceEnd(text string, from, indent int) int { + end := from + for line := from; line < len(text); { + next := strings.IndexByte(text[line:], '\n') + body := text[line:] + if next >= 0 { + body = text[line : line+next] + } + content := strings.TrimLeft(body, " \t") + if trimmed := strings.TrimSpace(content); trimmed != "" && len(body)-len(content) <= indent { + item := len(body)-len(content) == indent && (trimmed == "-" || strings.HasPrefix(content, "- ") || strings.HasPrefix(content, "-\t")) + if !item { + break + } + } else if end == from && trimmed != "" { + // A first line indented further is a block, not this sequence. + return from + } + end = line + len(strings.TrimRight(body, "\r")) + if next < 0 { + return len(text) + } + line += next + 1 + } + return end +} + +// lineIndent returns how far the line holding text[i] is indented, up to +// the key or setting that starts there. +func lineIndent(text string, i int) int { + lineStart := strings.LastIndexByte(text[:i], '\n') + 1 + line := text[lineStart:i] + rest := strings.TrimLeft(line, " \t") + // A key in a sequence item is indented as far as the key itself: the + // dashes in front of it are part of its indentation, as YAML counts + // it, so the item's other keys are its siblings. + for len(rest) > 1 && rest[0] == '-' && (rest[1] == ' ' || rest[1] == '\t') { + rest = strings.TrimLeft(rest[1:], " \t") + } + return len(line) - len(rest) +} + +// lineBreakOf returns the line break a block scalar header ends in. +func lineBreakOf(header string) string { + switch { + case strings.HasSuffix(header, "\r\n"): + return "\r\n" + case strings.HasSuffix(header, "\n"): + return "\n" + } + return "" +} + +// quoted returns s in double quotes when quote is set. +func quoted(s string, quote bool) string { + if quote { + return `"` + s + `"` + } + return s +} + +// jsonStrings tells whether a position of a text lies inside a JSON string, +// reading the text once from its start as positions are asked for in +// increasing order. +// +// A double quote opens or closes a JSON string, except inside single +// quotes, the strings of YAML and the shell, where it is a character like +// any other. Every line starts outside of any string: a JSON string holds +// no line break, and so a stray quote, in prose or a plain YAML value, is +// forgotten at the end of its line. +type jsonStrings struct { + pos int + in bool + single bool +} + +// inside reports whether text[i] lies inside a string in double quotes. +func (s *jsonStrings) inside(text string, i int) bool { + for ; s.pos < i && s.pos < len(text); s.pos++ { + switch c := text[s.pos]; { + case c == '\n': + s.in, s.single = false, false + case s.single: + if c == '\'' { + s.single = false + } + case c == '\\': + if s.in { + s.pos++ + } + case c == '"': + s.in = !s.in + case c == '\'' && !s.in: + s.single = true + } + } + return s.in +} + +// compositeEnd returns the index after the array or object that opens at +// start, counting nested brackets and braces and skipping over strings in +// double or single quotes, or len(text) when it is never closed. Inside a +// JSON string (inString), its strings are in escaped quotes, and it ends at +// the latest before the quote that ends the enclosing string. Strings in +// single quotes are read both ways quotedEnd reads them, and the later end +// wins. +func compositeEnd(text string, start int, inString bool) int { + if inString { + return escapedCompositeEnd(text, start) + } + return max(bracketEnd(text, start, false), bracketEnd(text, start, true)) +} + +// bracketEnd is compositeEnd outside a JSON string for one way of reading +// strings in single quotes: literal says whether a backslash in them is +// itself, with a doubled quote standing for one, or escapes the character +// after it. In double quotes a backslash always escapes. +func bracketEnd(text string, start int, literal bool) int { + depth := 0 + var quote byte + for i := start; i < len(text); i++ { + c := text[i] + switch { + case quote == '\'' && literal: + if c == '\'' { + if i+1 < len(text) && text[i+1] == '\'' { + i++ + } else { + quote = 0 + } + } + case quote != 0: + switch c { + case '\\': + i++ + case quote: + quote = 0 + } + case c == '"' || c == '\'': + quote = c + case c == '[' || c == '{': + depth++ + case c == ']' || c == '}': + depth-- + if depth == 0 { + return i + 1 + } + } + } + return len(text) +} + +// escapedCompositeEnd is compositeEnd for an array or object inside a JSON +// string, whose own strings are in the escaped quotes \". +func escapedCompositeEnd(text string, start int) int { + depth := 0 + inner, single := false, false + for i := start; i < len(text); i++ { + switch c := text[i]; { + case c == '"': + return i + case c == '\\' && i+1 < len(text) && text[i+1] == '\\': + // An escaped backslash of the enclosing string. Followed by \", + // it escapes a quote of the inner text: no delimiter. Otherwise + // the character after it is read anew. + if i+3 < len(text) && text[i+2] == '\\' && text[i+3] == '"' { + i += 3 + } else { + i++ + } + case c == '\\': + if i+1 < len(text) && text[i+1] == '"' && !single { + inner = !inner + } + i++ + case inner: + case c == '\'': + // Brackets in a single-quoted string are text, as in a + // composite outside a JSON string. + single = !single + case single: + case c == '[' || c == '{': + depth++ + case c == ']' || c == '}': + depth-- + if depth == 0 { + return i + 1 + } + } + } + return len(text) +} + +// jsonMember reports whether the name at label is a member of a JSON object: +// what stands before it, white space aside, opens the object or ends the +// member before it. +func jsonMember(text string, label int) bool { + before := strings.TrimRight(text[:label], " \t\r\n") + return before != "" && (before[len(before)-1] == '{' || before[len(before)-1] == ',') +} + +// jsonValueStart reports whether s starts with what can start a JSON value: +// a string, an object, an array, a number, true, false or null. +func jsonValueStart(s string) bool { + if s == "" { + return false + } + switch c := s[0]; { + case c == '"' || c == '{' || c == '[': + return true + case c >= '0' && c <= '9': + return true + case c == '-': + return len(s) > 1 && s[1] >= '0' && s[1] <= '9' + } + for _, word := range []string{"true", "false", "null"} { + if strings.HasPrefix(s, word) { + return true + } + } + return false +} diff --git a/secret/redact_test.go b/redact/patterns_test.go similarity index 89% rename from secret/redact_test.go rename to redact/patterns_test.go index 19296a2..8abdaef 100644 --- a/secret/redact_test.go +++ b/redact/patterns_test.go @@ -1,12 +1,13 @@ -package secret +package redact import ( "encoding/json" "strings" "testing" + "time" ) -func TestRedactPatterns(t *testing.T) { +func TestPatterns(t *testing.T) { tests := []struct { name string in string @@ -110,15 +111,15 @@ func TestRedactPatterns(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - if got := RedactPatterns(tt.in); got != tt.want { - t.Fatalf("RedactPatterns(%q) = %q, want %q", tt.in, got, tt.want) + if got := Patterns(tt.in); got != tt.want { + t.Fatalf("Patterns(%q) = %q, want %q", tt.in, got, tt.want) } }) } } // Redacting JSON leaves valid JSON, wherever the credential sits in it. -func TestRedactPatternsKeepsJSONValid(t *testing.T) { +func TestPatternsKeepsJSONValid(t *testing.T) { for _, in := range []string{ `{"api_key":"sk-secretvalue","n":1}`, `{"token": 12345, "ok": true}`, @@ -145,15 +146,41 @@ func TestRedactPatternsKeepsJSONValid(t *testing.T) { `{"message":"token: ['abc]secret-tail', 'other']"}`, `{"m":"password='a''b\"secret-tail'","n":"ok"}`, } { - got := RedactPatterns(in) + got := Patterns(in) if !json.Valid([]byte(got)) { - t.Errorf("RedactPatterns(%s) = %s, not valid JSON", in, got) + t.Errorf("Patterns(%s) = %s, not valid JSON", in, got) } if got == in { - t.Errorf("RedactPatterns(%s) redacted nothing", in) + t.Errorf("Patterns(%s) redacted nothing", in) } if strings.Contains(got, "secret-tail") { - t.Errorf("RedactPatterns(%s) = %s, leaves part of the secret", in, got) + t.Errorf("Patterns(%s) = %s, leaves part of the secret", in, got) } } } + +// Patterns takes time in proportion to the text. A server's response that +// repeats a label, logged at --verbose, once took seconds per 100 KB +// because the YAML properties after each label were searched for in all +// of the text that followed it. +func TestPatternsIsLinear(t *testing.T) { + if testing.Short() { + t.Skip("large inputs") + } + for _, unit := range []string{`"token":"`, "password:\n", "password: |\n", "- token: x\n", `{"m":"token=\"`} { + text := strings.Repeat(unit, 1<<14) + start := time.Now() + Patterns(text) + if elapsed := time.Since(start); elapsed > 5*time.Second { + t.Errorf("Patterns of %d bytes of %q took %v", len(text), unit, elapsed) + } + } +} + +func BenchmarkPatterns(b *testing.B) { + text := strings.Repeat(`{"token":"abc","password":`+"\n"+` !!str x, "note": "hello"}`+"\n", 1000) + b.SetBytes(int64(len(text))) + for b.Loop() { + Patterns(text) + } +} diff --git a/redact/values.go b/redact/values.go new file mode 100644 index 0000000..8228444 --- /dev/null +++ b/redact/values.go @@ -0,0 +1,162 @@ +package redact + +import ( + "bytes" + "cmp" + "encoding/json" + "net/url" + "slices" + "strings" +) + +// Marker is what replaces a secret in text passed through [Values] or +// [Patterns]. +const Marker = "[REDACTED]" + +// Values returns text with every occurrence of each secret replaced by +// [Marker]. Use it on anything that may carry a secret before it is +// logged or shown: an HTTP dump, an error from a server that echoes its +// input. Empty secrets are ignored. +// +// A secret is found as it is and in the forms it takes on its way through +// a request: escaped for a URL query or a form (with a space as "+" or as +// "%20"), escaped for a URL path, and escaped for a JSON string. All +// occurrences are looked for in text as it was passed in and removed +// together, so secrets that overlap, or contain one another, leave no part +// of either behind. +// +// Values cannot find a secret that is part of a larger encoded value. The +// credentials of HTTP Basic authentication are the user name and the +// password encoded as one Base64 string, and a token inside a Base64 or +// compressed body looks like nothing Values knows. Remove such headers and +// bodies before text reaches a log, or pass the encoded value as a secret +// of its own. +func Values(text string, secrets ...string) string { + type span struct{ start, end int } + var spans []span + seen := make(map[string]bool) + for _, s := range secrets { + for _, form := range forms(s) { + if form == "" || seen[form] { + continue + } + seen[form] = true + find := finder(form) + // One byte on from each match, so that occurrences which overlap + // themselves, such as "aa" in "aaa", are all found. + for from := 0; from < len(text); { + i, n := find(text[from:]) + if i < 0 { + break + } + spans = append(spans, span{from + i, from + i + n}) + from += i + 1 + } + } + } + if len(spans) == 0 { + return text + } + slices.SortFunc(spans, func(a, b span) int { + return cmp.Or(cmp.Compare(a.start, b.start), cmp.Compare(a.end, b.end)) + }) + var b strings.Builder + pos := 0 + current := spans[0] + flush := func() { + b.WriteString(text[pos:current.start]) + b.WriteString(Marker) + pos = current.end + } + for _, next := range spans[1:] { + if next.start < current.end { + current.end = max(current.end, next.end) + continue + } + flush() + current = next + } + flush() + b.WriteString(text[pos:]) + return b.String() +} + +// finder returns the function that finds form in a text: the index of its +// first occurrence and its length, or -1. The hexadecimal digits of a URL +// escape (%2F) match in either case, as both are valid; every other byte +// matches exactly, so secrets that are not UTF-8 are found too. +func finder(form string) func(string) (int, int) { + if !strings.Contains(form, "%") { + return func(text string) (int, int) { return strings.Index(text, form), len(form) } + } + // hex marks the bytes of form that are digits of a URL escape. + hex := make([]bool, len(form)) + for i := 0; i+2 < len(form); i++ { + if form[i] == '%' && isHex(form[i+1]) && isHex(form[i+2]) { + hex[i+1], hex[i+2] = true, true + i += 2 + } + } + matchAt := func(text string, at int) bool { + for j := range len(form) { + c := text[at+j] + if c == form[j] || hex[j] && lowerHex(c) == lowerHex(form[j]) { + continue + } + return false + } + return true + } + return func(text string) (int, int) { + for at := 0; at+len(form) <= len(text); at++ { + if matchAt(text, at) { + return at, len(form) + } + } + return -1, 0 + } +} + +// lowerHex returns c with an upper-case letter made lower case. +func lowerHex(c byte) byte { + if 'A' <= c && c <= 'Z' { + return c + 'a' - 'A' + } + return c +} + +// isHex reports whether c is a hexadecimal digit. +func isHex(c byte) bool { + return '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' +} + +// forms returns secret and the escaped forms Values looks for. It returns +// nothing for an empty secret. +func forms(secret string) []string { + if secret == "" { + return nil + } + query := url.QueryEscape(secret) + return []string{ + secret, + query, + strings.ReplaceAll(query, "+", "%20"), + url.PathEscape(secret), + jsonEscape(secret, true), + jsonEscape(secret, false), + } +} + +// jsonEscape returns s as it stands between the quotes of a JSON string, +// with <, > and & written as \u escapes, as encoding/json does by default, +// or as they are. +func jsonEscape(s string, escapeHTML bool) string { + var buf bytes.Buffer + enc := json.NewEncoder(&buf) + enc.SetEscapeHTML(escapeHTML) + if err := enc.Encode(s); err != nil { + return "" + } + quoted := strings.TrimSuffix(buf.String(), "\n") + return strings.TrimSuffix(strings.TrimPrefix(quoted, `"`), `"`) +} diff --git a/redact/values_test.go b/redact/values_test.go new file mode 100644 index 0000000..21541b6 --- /dev/null +++ b/redact/values_test.go @@ -0,0 +1,89 @@ +package redact + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "net/url" + "strings" + "testing" +) + +func TestValues(t *testing.T) { + got := Values("token=abc123 again abc123 and abc", "abc", "abc123", "") + want := "token=[REDACTED] again [REDACTED] and [REDACTED]" + if got != want { + t.Fatalf("Values = %q, want %q", got, want) + } + for _, tc := range []struct { + name string + text string + secrets []string + want string + }{ + {"no secrets", "plain text", nil, "plain text"}, + {"nothing found", "plain text", []string{"hunter2"}, "plain text"}, + {"only empty secrets", "plain text", []string{"", ""}, "plain text"}, + {"overlapping secrets", "abcdef", []string{"abcd", "cdef"}, "[REDACTED]"}, + {"overlap with the longer one behind", "xabcdef!", []string{"bcdef", "abc"}, "x[REDACTED]!"}, + {"a secret overlapping itself", "-aaa-", []string{"aa"}, "-[REDACTED]-"}, + {"neighbors stay apart", "abcabc", []string{"abc"}, "[REDACTED][REDACTED]"}, + {"the marker is never matched", "token=longsecret", []string{"longsecret", "RED", "[", "E"}, "token=[REDACTED]"}, + {"regular expression characters", "a.*b and axxb", []string{".*"}, "a[REDACTED]b and axxb"}, + {"at both ends", "pw and pw", []string{"pw"}, "[REDACTED] and [REDACTED]"}, + } { + if got := Values(tc.text, tc.secrets...); got != tc.want { + t.Errorf("%s: Values(%q, %q) = %q, want %q", tc.name, tc.text, tc.secrets, got, tc.want) + } + } +} + +// A secret is also found in the forms it takes inside a request. +func TestValuesEscapedForms(t *testing.T) { + const tricky = `p@ss w/rd"<1>&ü` + body, err := json.Marshal(map[string]string{"password": tricky}) + if err != nil { + t.Fatal(err) + } + var plain bytes.Buffer + enc := json.NewEncoder(&plain) + enc.SetEscapeHTML(false) + if err := enc.Encode(map[string]string{"password": tricky}); err != nil { + t.Fatal(err) + } + for _, tc := range []struct{ name, text, want string }{ + {"as it is", "password: " + tricky + ".", "password: [REDACTED]."}, + {"form body", "user=alice&password=" + url.QueryEscape(tricky) + "&x=1", "user=alice&password=[REDACTED]&x=1"}, + {"query with %20", "?password=" + strings.ReplaceAll(url.QueryEscape(tricky), "+", "%20") + "&x=1", "?password=[REDACTED]&x=1"}, + {"URL path", "GET /keys/" + url.PathEscape(tricky) + "/info", "GET /keys/[REDACTED]/info"}, + {"JSON", string(body), `{"password":"[REDACTED]"}`}, + {"JSON without HTML escapes", strings.TrimSpace(plain.String()), `{"password":"[REDACTED]"}`}, + {"lower-case URL escapes", "?password=" + strings.ToLower(url.QueryEscape(tricky)) + "&x=1", "?password=[REDACTED]&x=1"}, + } { + got := Values(tc.text, tricky) + if got != tc.want { + t.Errorf("%s: Values(%q) = %q, want %q", tc.name, tc.text, got, tc.want) + } + } + // A secret that is not UTF-8 is matched byte for byte, its URL escapes + // in either case. + if got := Values("pw=%\xff and pw=%25%FF and %25%ff", "%\xff"); got != "pw=[REDACTED] and pw=[REDACTED] and [REDACTED]" { + t.Errorf("Values of a non-UTF-8 secret = %q", got) + } + + // A quote at the end of a secret stays part of its JSON form. + if got := Values(`{"password":"say \"hi\""}`, `say "hi"`); got != `{"password":"[REDACTED]"}` { + t.Errorf("Values of a quoted secret in JSON = %q", got) + } + + // What Values cannot find, as documented: a secret inside a larger + // encoded value. + basic := "Authorization: Basic " + base64.StdEncoding.EncodeToString([]byte("alice:"+tricky)) + if got := Values(basic, tricky); got != basic { + t.Errorf("Values found the password inside Basic credentials: %q; update its documentation", got) + } + encoded := base64.StdEncoding.EncodeToString([]byte("alice:" + tricky)) + if got := Values(basic, tricky, encoded); got != "Authorization: Basic [REDACTED]" { + t.Errorf("Values with the encoded credentials as a secret = %q", got) + } +} diff --git a/secret/coverage_test.go b/secret/coverage_test.go new file mode 100644 index 0000000..91d5ab7 --- /dev/null +++ b/secret/coverage_test.go @@ -0,0 +1,282 @@ +package secret + +import ( + "errors" + "io/fs" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + "time" +) + +// The deprecated forwards do what the redact package does. +func TestDeprecatedRedactForwards(t *testing.T) { + if got := Redact("token abc123", "abc123"); got != "token "+Redacted { + t.Errorf("Redact = %q", got) + } + if got := RedactPatterns("password=hunter2"); got != "password="+Redacted { + t.Errorf("RedactPatterns = %q", got) + } +} + +func TestNewFileStoreWithoutAConfigurationDirectory(t *testing.T) { + if runtime.GOOS != "linux" { + t.Skip("only Linux derives the configuration directory from the environment alone") + } + t.Setenv("XDG_CONFIG_HOME", "") + t.Setenv("HOME", "") + if _, err := NewFileStore("example-tool"); err == nil || !strings.Contains(err.Error(), "locate configuration directory") { + t.Fatalf("NewFileStore = %v, want the missing directory reported", err) + } +} + +func TestFileStoreWithoutDir(t *testing.T) { + s := &FileStore{} + if _, err := s.Get("alice"); err == nil || !strings.Contains(err.Error(), "Dir is empty") { + t.Errorf("Get = %v", err) + } + if err := s.Set("alice", "hunter2"); err == nil || !strings.Contains(err.Error(), "Dir is empty") { + t.Errorf("Set = %v", err) + } + if err := s.Delete("alice"); err == nil || !strings.Contains(err.Error(), "Dir is empty") { + t.Errorf("Delete = %v", err) + } +} + +func TestFileStoreDirThatIsAFile(t *testing.T) { + file := filepath.Join(privateDir(t), "not-a-dir") + if err := os.WriteFile(file, []byte("x"), 0o600); err != nil { + t.Fatal(err) + } + s := &FileStore{Dir: file} + if _, err := s.Get("alice"); err == nil || !strings.Contains(err.Error(), "is not a directory") { + t.Errorf("Get = %v, want the file refused as directory", err) + } + // Set cannot create a directory below a file. + s = &FileStore{Dir: filepath.Join(file, "below")} + if err := s.Set("alice", "hunter2"); err == nil || !strings.Contains(err.Error(), "create") { + t.Errorf("Set = %v, want the directory creation reported", err) + } +} + +func TestFileStoreEmptyFileIsNotFound(t *testing.T) { + s := &FileStore{Dir: privateDir(t)} + if err := os.WriteFile(filepath.Join(s.Dir, "alice"), []byte("\r\n"), 0o600); err != nil { + t.Fatal(err) + } + if _, err := s.Get("alice"); !errors.Is(err, ErrNotFound) { + t.Fatalf("Get of a file holding only a line ending = %v, want ErrNotFound", err) + } +} + +func TestFileStoreDeleteFailure(t *testing.T) { + s := &FileStore{Dir: privateDir(t)} + // A directory that is not empty cannot be removed like a file. + if err := os.MkdirAll(filepath.Join(s.Dir, "alice", "inner"), 0o700); err != nil { + t.Fatal(err) + } + if err := s.Delete("alice"); err == nil || errors.Is(err, ErrNotFound) || !strings.Contains(err.Error(), "delete") { + t.Fatalf("Delete = %v, want the failure reported", err) + } +} + +// fakeInfo describes a file of the given mode. +type fakeInfo struct{ mode fs.FileMode } + +func (f fakeInfo) Name() string { return "alice" } +func (f fakeInfo) Size() int64 { return 0 } +func (f fakeInfo) Mode() fs.FileMode { return f.mode } +func (f fakeInfo) ModTime() time.Time { return time.Time{} } +func (f fakeInfo) IsDir() bool { return f.mode.IsDir() } +func (f fakeInfo) Sys() any { return nil } + +// The open refuses a symbolic link already; the check on what was opened +// refuses one too. +func TestCheckSecretFile(t *testing.T) { + for _, tc := range []struct { + mode fs.FileMode + want string + }{ + {fs.ModeSymlink | 0o600, "symbolic link"}, + {fs.ModeDir | 0o700, "not a regular file"}, + {fs.ModeNamedPipe | 0o600, "not a regular file"}, + } { + err := checkSecretFile("alice", fakeInfo{tc.mode}) + if !errors.Is(err, ErrInsecureFile) || !strings.Contains(err.Error(), tc.want) { + t.Errorf("mode %v: checkSecretFile = %v, want %q", tc.mode, err, tc.want) + } + } + if err := checkSecretFile("alice", fakeInfo{0o600}); err != nil { + t.Errorf("checkSecretFile of a private file = %v", err) + } +} + +func TestRequestPrompt(t *testing.T) { + for _, tc := range []struct { + req Request + want string + }{ + {Request{Label: "Password"}, "Password: "}, + {Request{Label: "Password", Name: "password", Repeat: true}, "Repeat password: "}, + {Request{Label: "Password", Repeat: true}, "Repeat Password: "}, + } { + if got := tc.req.Prompt(); got != tc.want { + t.Errorf("%+v: Prompt = %q, want %q", tc.req, got, tc.want) + } + } +} + +// A Store without an Account is refused before anything is read or written. +func TestResolverRequiresAccountWithAStore(t *testing.T) { + r := &Resolver{Store: &Memory{}} + if _, _, err := r.Lookup(); err == nil || !strings.Contains(err.Error(), "Account is required") { + t.Errorf("Lookup = %v", err) + } + if err := r.Save("hunter2"); err == nil || !strings.Contains(err.Error(), "Account is required") { + t.Errorf("Save = %v", err) + } +} + +func TestLookup(t *testing.T) { + store := &Memory{} + if err := store.Set("default", " stored "); err != nil { + t.Fatal(err) + } + r := &Resolver{File: writeFile(t, "from-file\n"), Store: store, Account: "default", TrimSpace: true} + if value, source, err := r.Lookup(); err != nil || value != "from-file" || source != SourceFile { + t.Errorf("Lookup with File = %q, %v, %v", value, source, err) + } + r.File = "" + if value, source, err := r.Lookup(); err != nil || value != "stored" || source != SourceStore { + t.Errorf("Lookup from the store = %q, %v, %v; want the stored value trimmed", value, source, err) + } + r.Store = failing{} + if _, _, err := r.Lookup(); !errors.Is(err, errUnavailable) { + t.Errorf("Lookup with a failing store = %v, want its error", err) + } +} + +func TestForgetReportsAStoreThatCannotDelete(t *testing.T) { + r := &Resolver{Store: failing{}, Account: "default"} + if err := r.Forget(SourceStore); !errors.Is(err, errUnavailable) { + t.Errorf("Forget = %v, want the store's error", err) + } + r.Store = nil + if err := r.Forget(SourceStore); err != nil { + t.Errorf("Forget without a store = %v", err) + } +} + +func TestResolverStdinDefaultsToOsStdin(t *testing.T) { + if got := (&Resolver{}).stdin(); got != os.Stdin { + t.Errorf("stdin = %v, want os.Stdin", got) + } +} + +func TestResolveDashWhileStdinIsBusy(t *testing.T) { + r := &Resolver{File: "-", StdinBusy: true, FileFlag: "--token-file", Prompt: noPrompt(t)} + _, _, err := r.Resolve() + if err == nil || !strings.Contains(err.Error(), "--token-file - reads the secret from stdin") { + t.Fatalf("Resolve = %v", err) + } + r.FileFlag = "" + if _, _, err := r.Resolve(); err == nil || !strings.Contains(err.Error(), `the file "-" reads`) { + t.Fatalf("Resolve without FileFlag = %v", err) + } +} + +func TestResolveReportsAFailedRead(t *testing.T) { + stdin := stdinFile(t, "hunter2\n") + _ = stdin.Close() + r := &Resolver{File: "-", Stdin: stdin, Prompt: noPrompt(t)} + _, _, err := r.Resolve() + if err == nil || !strings.Contains(err.Error(), "reading secret from stdin") || !errors.Is(err, os.ErrClosed) { + t.Fatalf("Resolve = %v, want the read error", err) + } +} + +func TestWithoutPath(t *testing.T) { + plain := errors.New("plain") + if got := withoutPath(plain); !errors.Is(got, plain) { + t.Errorf("withoutPath of an error without a path = %v", got) + } + pathErr := &fs.PathError{Op: "open", Path: "/secret/hunter2", Err: fs.ErrPermission} + if got := withoutPath(pathErr); !errors.Is(got, fs.ErrPermission) || strings.Contains(got.Error(), "hunter2") { + t.Errorf("withoutPath = %v", got) + } +} + +func TestAskTrimsAndConfirms(t *testing.T) { + var asked []Request + r := &Resolver{StdinBusy: true, TrimSpace: true, Confirm: true, Prompt: answers(&asked, " hunter2 ", "hunter2\t")} + value, source, err := r.Resolve() + if err != nil || value != "hunter2" || source != SourcePrompt { + t.Fatalf("Resolve = %q, %v, %v", value, source, err) + } + // The repetition fails. + asked = nil + r.Prompt = answers(&asked, "hunter2") + if _, _, err := r.Resolve(); err == nil || !strings.Contains(err.Error(), "unexpected prompt") { + t.Fatalf("Resolve with a failing repetition = %v", err) + } + if len(asked) != 2 || !asked[1].Repeat { + t.Fatalf("asked %+v", asked) + } +} + +func TestPromptFailedWithOnlyATerminalLeft(t *testing.T) { + r := &Resolver{StdinBusy: true, Prompt: func(Request) (string, error) { return "", ErrNoSource }} + _, _, err := r.Resolve() + if !errors.Is(err, ErrNoSource) || !strings.HasSuffix(err.Error(), "no secret available: run this on a terminal") { + t.Fatalf("Resolve = %v", err) + } +} + +func TestTTYPromptWithoutATerminal(t *testing.T) { + t.Cleanup(func() { openTTY = defaultOpenTTY }) + errNoTTY := errors.New("no controlling terminal") + openTTY = func() (*os.File, error) { return nil, errNoTTY } + if _, err := TTYPrompt(Request{Label: "Password"}); !errors.Is(err, ErrNoSource) || !errors.Is(err, errNoTTY) { + t.Errorf("TTYPrompt = %v, want ErrNoSource and the cause", err) + } + // A file that opens but is no terminal. + openTTY = func() (*os.File, error) { return os.Open(writeFile(t, "x")) } + if _, err := TTYPrompt(Request{Label: "Password"}); !errors.Is(err, ErrNoSource) { + t.Errorf("TTYPrompt on a regular file = %v, want ErrNoSource", err) + } +} + +func TestFallbackSetFailsWhenBothFail(t *testing.T) { + err := Fallback(failing{}, stuck{&Memory{}}).Set("alice", "hunter2") + if !errors.Is(err, errUnavailable) || !errors.Is(err, errDenied) { + t.Fatalf("Set = %v, want both errors", err) + } +} + +func TestFallbackDeleteReportsBothWhilePrimaryHoldsTheSecret(t *testing.T) { + primary := &Memory{} + if err := primary.Set("alice", "hunter2"); err != nil { + t.Fatal(err) + } + err := Fallback(stuck{primary}, failing{}).Delete("alice") + if !errors.Is(err, errDenied) || !errors.Is(err, errUnavailable) || !strings.Contains(err.Error(), "still holds") { + t.Fatalf("Delete = %v, want both errors", err) + } +} + +func TestFallbackDeleteReportsTheSecondaryFailure(t *testing.T) { + // Primary held nothing; secondary failed, so the secret may still be + // there. + if err := Fallback(&Memory{}, failing{}).Delete("alice"); !errors.Is(err, errUnavailable) { + t.Fatalf("Delete = %v, want the secondary's error", err) + } + primary := &Memory{} + if err := primary.Set("alice", "hunter2"); err != nil { + t.Fatal(err) + } + if err := Fallback(primary, failing{}).Delete("alice"); err != nil { + t.Fatalf("Delete = %v", err) + } +} diff --git a/secret/doc.go b/secret/doc.go index 1af0c2c..b9fc553 100644 --- a/secret/doc.go +++ b/secret/doc.go @@ -40,11 +40,6 @@ // replacing an existing one atomically. // // Nothing in this package prints, logs or embeds a secret value in an error. -// [Redact] removes known secrets from text that is about to be logged, as -// they are and in their URL-escaped and JSON-escaped forms; it does not -// find a secret inside a larger encoded value, such as the Base64 string -// of HTTP Basic authentication. [RedactPatterns] removes the credentials it -// recognizes by their shape, for text from elsewhere whose secrets are not -// known: labeled assignments such as password=…, Bearer tokens, and tokens -// whose prefix names their issuer. +// To remove secrets from text that is about to be logged, use the redact +// package of this module. package secret diff --git a/secret/example_test.go b/secret/example_test.go index 86522be..1105d58 100644 --- a/secret/example_test.go +++ b/secret/example_test.go @@ -46,12 +46,6 @@ func ExampleResolver() { } } -func ExampleRedact() { - token := "glpat-abc123" - fmt.Println(secret.Redact("GET /api?private_token=glpat-abc123", token)) - // Output: GET /api?private_token=[REDACTED] -} - func ExampleFallback() { keyring := secret.NewMemory(nil) // stands in for secret.Keyring files := &secret.Memory{} // stands in for a *secret.FileStore diff --git a/secret/file_coverage_unix_test.go b/secret/file_coverage_unix_test.go new file mode 100644 index 0000000..16038b2 --- /dev/null +++ b/secret/file_coverage_unix_test.go @@ -0,0 +1,27 @@ +//go:build unix + +package secret + +import ( + "errors" + "os" + "path/filepath" + "strings" + "testing" +) + +// A file that cannot be opened is reported as such, not as missing or as +// a symbolic link. +func TestFileStoreReportsAFileThatDoesNotOpen(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root opens any file") + } + s := &FileStore{Dir: privateDir(t)} + if err := os.WriteFile(filepath.Join(s.Dir, "alice"), []byte("hunter2"), 0o000); err != nil { + t.Fatal(err) + } + _, err := s.Get("alice") + if err == nil || errors.Is(err, ErrNotFound) || errors.Is(err, ErrInsecureFile) || !strings.Contains(err.Error(), "secret: read") { + t.Fatalf("Get = %v, want the failed open reported", err) + } +} diff --git a/secret/prompt.go b/secret/prompt.go new file mode 100644 index 0000000..bc5a12b --- /dev/null +++ b/secret/prompt.go @@ -0,0 +1,178 @@ +package secret + +import ( + "errors" + "fmt" + "io" + "os" + "strings" + + xterm "golang.org/x/term" + + "github.com/mittwald/cli-kit/term" +) + +// Request describes one interactive question for a [PromptFunc]. +type Request struct { + // Label is the question, such as "Password" or "Password to encrypt + // the export". + Label string + // Name is the secret as the messages call it, such as "password". The + // second question of a confirmed entry asks to repeat it. + Name string + // Hint is optional text to show before the first question, such as + // where to create a token and which scopes it needs. The prompts of this + // package show the URLs in it as hyperlinks (see term.Linkify). + Hint string + // Repeat marks the second question of a confirmed entry. + Repeat bool +} + +// Prompt returns the text to put in front of the input field: "Password to +// encrypt the export: ", or "Repeat password: " for the second question of a +// confirmed entry. +func (r Request) Prompt() string { + if r.Repeat { + name := r.Name + if name == "" { + name = r.Label + } + return "Repeat " + name + ": " + } + return r.Label + ": " +} + +// PromptFunc asks the user for a secret without echoing it. It returns an +// error wrapping [ErrNoSource] when there is no terminal to ask on. +// +// [TTYPrompt] is the default. A tool with its own input widget, such as +// pick.Input from this module, turns it into a PromptFunc with +// [InputPrompt]. +type PromptFunc func(Request) (string, error) + +func (r *Resolver) ask() (string, error) { + prompt := r.Prompt + if prompt == nil { + prompt = TTYPrompt + } + req := Request{Label: r.label(), Name: r.name(), Hint: r.Hint} + value, err := prompt(req) + if err != nil { + return "", r.promptFailed(err) + } + if r.TrimSpace { + value = strings.TrimSpace(value) + } + if value == "" { + return "", fail(ErrEmpty, nil, "empty %s", r.name()) + } + if r.Confirm { + req.Repeat = true + again, err := prompt(req) + if err != nil { + return "", r.promptFailed(err) + } + if r.TrimSpace { + again = strings.TrimSpace(again) + } + if again != value { + return "", fail(ErrMismatch, nil, "%ss do not match", r.name()) + } + } + return value, nil +} + +// promptFailed words a failed prompt. A missing terminal becomes the list +// of sources the user could have offered instead. +func (r *Resolver) promptFailed(err error) error { + if !errors.Is(err, ErrNoSource) { + return fail(nil, err, "reading %s", r.name()) + } + var options []string + if r.Env != "" { + options = append(options, "set $"+r.Env) + } + if r.FileFlag != "" { + options = append(options, "pass "+r.FileFlag) + } + if !r.StdinBusy { + options = append(options, "pipe one to stdin") + } + options = append(options, "run this on a terminal") + return fail(ErrNoSource, nil, "no %s available: %s", r.name(), joinOr(options)) +} + +// TTYPrompt is the default [PromptFunc]. It asks on the controlling +// terminal, which works even when stdin and stdout are redirected, and +// reads the answer with echo turned off. Without a controlling terminal it +// returns an error wrapping [ErrNoSource]. +// +// The terminal gets its echo back when the process ends at the prompt, too. +// While TTYPrompt waits for the answer, the restoring is registered with +// live.OnRestore of this module, so it happens wherever a program lets +// package live clean up: in the signal handler of live.InstallSignalRestore +// before the signal ends the process, in live.RestoreAll, and in +// Cursor.RestoreOnPanic. Call live.RestoreAll only on the way out of the +// process: at a prompt that goes on waiting afterwards, the answer would be +// echoed. +// +// On Unix TTYPrompt also watches SIGINT (Ctrl-C), SIGTERM and SIGHUP +// itself, for programs without that handler: it restores the terminal, and +// then the signal ends the process as it does by default, also in a program +// that handles the signal in its own way, since the read of the answer +// cannot be interrupted otherwise. A signal the process ignores stays +// ignored. On other systems a process that is killed at the prompt leaves +// the console as it is, unless live's handler is installed. +func TTYPrompt(req Request) (string, error) { + tty, err := openTTY() + if err != nil { + return "", fmt.Errorf("%w: %w", ErrNoSource, err) + } + defer tty.Close() + if !term.IsTerminal(tty) { + return "", ErrNoSource + } + out, closeOut := promptOutput(tty) + defer closeOut() + if req.Hint != "" && !req.Repeat { + _, _ = fmt.Fprintln(term.Links(out), req.Hint) + } + stop := restoreOnExit(tty, out) + _, _ = io.WriteString(out, req.Prompt()) + value, err := xterm.ReadPassword(int(tty.Fd())) + stop() + // The terminal swallowed the Enter key along with the echo, so the + // cursor is still on the prompt line. + _, _ = io.WriteString(out, "\n") + if err != nil { + return "", fmt.Errorf("terminal: %w", err) + } + return string(value), nil +} + +// InputPrompt returns a [PromptFunc] that asks with input, a text field +// that draws nothing for what is typed, on in and out. With pick.Input from +// this module: +// +// prompt := secret.InputPrompt(os.Stdin, os.Stderr, +// func(in, out *os.File, prompt string) (string, error) { +// return pick.Input(in, out, pick.InputOptions{Prompt: prompt, Secret: true}) +// }) +// +// Unlike [TTYPrompt] it asks on in and out only. Where either is not a +// terminal it returns [ErrNoSource] without calling input, so a [Resolver] +// names the sources the user could offer instead. Before the first question +// of a request it writes the request's Hint to out, its URLs as hyperlinks. +// The question passed to input is [Request.Prompt]; input's errors are +// returned as they are. +func InputPrompt(in, out *os.File, input func(in, out *os.File, prompt string) (string, error)) PromptFunc { + return func(req Request) (string, error) { + if !term.Interactive(in, out) { + return "", ErrNoSource + } + if req.Hint != "" && !req.Repeat { + _, _ = fmt.Fprintln(term.Links(out), req.Hint) + } + return input(in, out, req.Prompt()) + } +} diff --git a/secret/prompt_inprocess_linux_test.go b/secret/prompt_inprocess_linux_test.go new file mode 100644 index 0000000..dd1633a --- /dev/null +++ b/secret/prompt_inprocess_linux_test.go @@ -0,0 +1,95 @@ +package secret + +import ( + "os" + "strings" + "syscall" + "testing" + "time" + + "github.com/mittwald/cli-kit/live" +) + +type promptResult struct { + value string + err error +} + +// startInProcessPrompt runs TTYPrompt in this process on a pseudo terminal +// and returns once it waits for the answer with echo turned off. Unlike +// startPrompt, it leaves the signals alone: none is sent. +func startInProcessPrompt(t *testing.T, req Request) (master, tty *os.File, shown string, result <-chan promptResult) { + t.Helper() + master, tty = openPTY(t) + if !echoes(t, tty) { + t.Skip("the pseudo terminal starts without echo") + } + t.Cleanup(func() { openTTY = defaultOpenTTY }) + // TTYPrompt closes what it opens, so it gets a file of its own. + openTTY = func() (*os.File, error) { return os.OpenFile(tty.Name(), os.O_RDWR|syscall.O_NOCTTY, 0) } + done := make(chan promptResult, 1) + go func() { + value, err := TTYPrompt(req) + done <- promptResult{value, err} + }() + for deadline := time.Now().Add(20 * time.Second); !strings.Contains(shown, req.Prompt()) || echoes(t, tty); { + if time.Now().After(deadline) { + t.Fatalf("the prompt does not wait with echo off; terminal shows %q", shown) + } + shown += readAvailable(t, master) + } + return master, tty, shown, done +} + +func await(t *testing.T, result <-chan promptResult) promptResult { + t.Helper() + select { + case r := <-result: + return r + case <-time.After(20 * time.Second): + t.Fatal("the prompt did not return") + return promptResult{} + } +} + +// The hint comes before the question, the answer is not echoed, and the +// terminal gets its echo back. +func TestTTYPromptInProcess(t *testing.T) { + master, tty, shown, result := startInProcessPrompt(t, Request{Label: "Password", Hint: "Create a token at https://example.com/tokens."}) + if !strings.Contains(shown, "Create a token at") || strings.Index(shown, "Create a token") > strings.Index(shown, "Password: ") { + t.Errorf("terminal shows %q, want the hint before the question", shown) + } + if _, err := master.WriteString("hunter2\n"); err != nil { + t.Fatal(err) + } + if r := await(t, result); r.err != nil || r.value != "hunter2" { + t.Fatalf("TTYPrompt = %q, %v", r.value, r.err) + } + if after := readAvailable(t, master); strings.Contains(after, "hunter2") { + t.Errorf("the answer was echoed: %q", after) + } + if !echoes(t, tty) { + t.Error("the terminal is left with echo off") + } +} + +// What package live restores on the way out includes the prompt's +// terminal: its echo comes back and its line is ended. Once the prompt +// returned, a later restore leaves the terminal alone. +func TestTTYPromptRestoredByLive(t *testing.T) { + master, tty, _, result := startInProcessPrompt(t, Request{Label: "Password", Repeat: true, Hint: "not shown on a repetition"}) + live.RestoreAll() + if !echoes(t, tty) { + t.Fatal("live.RestoreAll left the echo off") + } + if shown := readAvailable(t, master); !strings.Contains(shown, "\n") { + t.Errorf("terminal shows %q, want the prompt's line ended", shown) + } + if _, err := master.WriteString("hunter2\n"); err != nil { + t.Fatal(err) + } + if r := await(t, result); r.err != nil || r.value != "hunter2" { + t.Fatalf("TTYPrompt = %q, %v", r.value, r.err) + } + live.RestoreAll() // nothing registered any more +} diff --git a/secret/read.go b/secret/read.go new file mode 100644 index 0000000..2aae3c7 --- /dev/null +++ b/secret/read.go @@ -0,0 +1,94 @@ +package secret + +import ( + "bytes" + "errors" + "io" + "strings" +) + +// readFirstLine reads the first line of rd. It stops at the newline, so a +// pipe that stays open after the secret does not block, and the rest of +// stdin stays unread. A trailing CR is dropped, so a file written on +// Windows works, and so is a UTF-8 byte order mark in front; interior +// spaces are kept, because a passphrase may contain them. +// +// A line longer than MaxLen is refused with ErrTooLong rather than cut +// short, and one that is no text (UTF-16, or holding a NUL byte) with an +// error wrapping ErrNotText. Neither error carries what was read. +func (r *Resolver) readFirstLine(rd io.Reader) (string, error) { + limit := r.maxLen() + data := make([]byte, 0, min(limit, 256)) + var b [1]byte + for { + n, err := rd.Read(b[:]) + if n == 1 { + if b[0] == '\n' { + break + } + data = append(data, b[0]) + // The first bytes of a byte order mark exceed a short limit + // before they are one: they are judged once they are complete, + // or turned out to be something else. + if !startsByteOrderMark(data) && tooLong(data, limit) { + if textErr := checkText(data); textErr != nil { + return "", textErr + } + return "", ErrTooLong + } + } + if errors.Is(err, io.EOF) { + break + } + if err != nil { + return "", err + } + } + if err := checkText(data); err != nil { + return "", err + } + // A line that ended inside what could have become a byte order mark was + // not judged above. + if tooLong(data, limit) { + return "", ErrTooLong + } + line := strings.TrimSuffix(strings.TrimPrefix(string(data), utf8BOM), "\r") + if r.TrimSpace { + line = strings.TrimSpace(line) + } + return line, nil +} + +// tooLong reports whether data, the start of a line, already holds more +// than limit bytes of secret. A byte order mark in front does not count, +// and neither does a CR at the end, which may turn out to belong to the +// line ending. +func tooLong(data []byte, limit int) bool { + n := len(data) + if bytes.HasPrefix(data, []byte(utf8BOM)) { + n -= len(utf8BOM) + } + if n > 0 && data[len(data)-1] == '\r' { + n-- + } + return n > limit +} + +// startsByteOrderMark reports whether data is the beginning of a UTF-8 byte +// order mark that further bytes have yet to complete. +func startsByteOrderMark(data []byte) bool { + return len(data) < len(utf8BOM) && strings.HasPrefix(utf8BOM, string(data)) +} + +// checkText refuses a line that is not text in an encoding a secret can be +// read from: UTF-16, which starts with a byte order mark, and anything with +// a NUL byte, which UTF-16 without the mark is full of. +func checkText(data []byte) error { + switch { + case bytes.HasPrefix(data, []byte("\xff\xfe")), bytes.HasPrefix(data, []byte("\xfe\xff")): + return errUTF16 + case bytes.IndexByte(data, 0) >= 0: + return errNUL + } + return nil +} diff --git a/secret/redact.go b/secret/redact.go index a3c3665..e604876 100644 --- a/secret/redact.go +++ b/secret/redact.go @@ -1,831 +1,24 @@ package secret -import ( - "bytes" - "cmp" - "encoding/json" - "net/url" - "regexp" - "slices" - "strings" -) +import "github.com/mittwald/cli-kit/redact" // Redacted replaces a secret in text passed through [Redact]. -const Redacted = "[REDACTED]" +// +// Deprecated: Use [redact.Marker]. +const Redacted = redact.Marker // Redact returns text with every occurrence of each secret replaced by -// [Redacted]. Use it on anything that may carry a secret before it is -// logged or shown: an HTTP dump, an error from a server that echoes its -// input. Empty secrets are ignored. -// -// A secret is found as it is and in the forms it takes on its way through -// a request: escaped for a URL query or a form (with a space as "+" or as -// "%20"), escaped for a URL path, and escaped for a JSON string. All -// occurrences are looked for in text as it was passed in and removed -// together, so secrets that overlap, or contain one another, leave no part -// of either behind. +// [Redacted]. // -// Redact cannot find a secret that is part of a larger encoded value. The -// credentials of HTTP Basic authentication are the user name and the -// password encoded as one Base64 string, and a token inside a Base64 or -// compressed body looks like nothing Redact knows. Remove such headers and -// bodies before text reaches a log, or pass the encoded value as a secret -// of its own. +// Deprecated: Use [redact.Values], which does the same. func Redact(text string, secrets ...string) string { - type span struct{ start, end int } - var spans []span - seen := make(map[string]bool) - for _, s := range secrets { - for _, form := range forms(s) { - if form == "" || seen[form] { - continue - } - seen[form] = true - find := finder(form) - // One byte on from each match, so that occurrences which overlap - // themselves, such as "aa" in "aaa", are all found. - for from := 0; from < len(text); { - i, n := find(text[from:]) - if i < 0 { - break - } - spans = append(spans, span{from + i, from + i + n}) - from += i + 1 - } - } - } - if len(spans) == 0 { - return text - } - slices.SortFunc(spans, func(a, b span) int { - return cmp.Or(cmp.Compare(a.start, b.start), cmp.Compare(a.end, b.end)) - }) - var b strings.Builder - pos := 0 - current := spans[0] - flush := func() { - b.WriteString(text[pos:current.start]) - b.WriteString(Redacted) - pos = current.end - } - for _, next := range spans[1:] { - if next.start < current.end { - current.end = max(current.end, next.end) - continue - } - flush() - current = next - } - flush() - b.WriteString(text[pos:]) - return b.String() + return redact.Values(text, secrets...) } -// finder returns the function that finds form in a text: the index of its -// first occurrence and its length, or -1. The hexadecimal digits of a URL -// escape (%2F) match in either case, as both are valid; every other byte -// matches exactly, so secrets that are not UTF-8 are found too. -func finder(form string) func(string) (int, int) { - if !strings.Contains(form, "%") { - return func(text string) (int, int) { return strings.Index(text, form), len(form) } - } - // hex marks the bytes of form that are digits of a URL escape. - hex := make([]bool, len(form)) - for i := 0; i+2 < len(form); i++ { - if form[i] == '%' && isHex(form[i+1]) && isHex(form[i+2]) { - hex[i+1], hex[i+2] = true, true - i += 2 - } - } - matchAt := func(text string, at int) bool { - for j := range len(form) { - c := text[at+j] - if c == form[j] || hex[j] && lowerHex(c) == lowerHex(form[j]) { - continue - } - return false - } - return true - } - return func(text string) (int, int) { - for at := 0; at+len(form) <= len(text); at++ { - if matchAt(text, at) { - return at, len(form) - } - } - return -1, 0 - } -} - -// lowerHex returns c with an upper-case letter made lower case. -func lowerHex(c byte) byte { - if 'A' <= c && c <= 'Z' { - return c + 'a' - 'A' - } - return c -} - -// isHex reports whether c is a hexadecimal digit. -func isHex(c byte) bool { - return '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' -} - -// forms returns secret and the escaped forms Redact looks for. It returns -// nothing for an empty secret. -func forms(secret string) []string { - if secret == "" { - return nil - } - query := url.QueryEscape(secret) - return []string{ - secret, - query, - strings.ReplaceAll(query, "+", "%20"), - url.PathEscape(secret), - jsonEscape(secret, true), - jsonEscape(secret, false), - } -} - -// jsonEscape returns s as it stands between the quotes of a JSON string, -// with <, > and & written as \u escapes, as encoding/json does by default, -// or as they are. -func jsonEscape(s string, escapeHTML bool) string { - var buf bytes.Buffer - enc := json.NewEncoder(&buf) - enc.SetEscapeHTML(escapeHTML) - if err := enc.Encode(s); err != nil { - return "" - } - quoted := strings.TrimSuffix(buf.String(), "\n") - return strings.TrimSuffix(strings.TrimPrefix(quoted, `"`), `"`) -} - -// Patterns that RedactPatterns looks for. -var ( - // labelPattern is the name of a credential and what assigns it a value, - // in JSON, YAML, an environment file or a query: the name, quoted or - // not, also in the backslash-escaped quotes of JSON inside a JSON - // string (group 1 is the quote after it), then a colon or an equals - // sign, with spaces and tabs around it but no line break. The value - // that follows is read by labeledValue. - labelPattern = regexp.MustCompile(`(?i)(?:\\?["'])?(?:(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|token|secret|password|credential|authorization|auth))(\\?["'])?[ \t]*[:=][ \t]*`) - // schemePattern is the scheme of an HTTP authorization at the start of - // an unquoted value, which the credential after it belongs to. - schemePattern = regexp.MustCompile(`(?i)^(?:Basic|Bearer|Bot|Digest|Negotiate|Token)[ \t]+`) - // bearerPattern is the credential of an HTTP Bearer authorization. - bearerPattern = regexp.MustCompile(`(?i)\bBearer\s+[A-Za-z0-9._~+/=-]{8,}`) - // prefixedPattern is a token whose prefix names its issuer: OpenAI and - // Anthropic (sk-), GitHub (ghp_, gho_, ghu_, ghs_, ghr_), GitLab - // (glpat-) and an AWS access key ID (AKIA). - prefixedPattern = regexp.MustCompile(`(?i)\b(?:sk-[A-Za-z0-9_-]{8,}|gh[pousr]_[A-Za-z0-9]{8,}|glpat-[A-Za-z0-9_-]{8,}|AKIA[A-Z0-9]{16,})`) - // propertiesPattern is the tags and anchors of a YAML node in front of - // its value: !!str, !secret, a verbatim !, &name, - // followed by white space or the end of their line, below which the - // value may stand. - propertiesPattern = regexp.MustCompile(`(?m)^(?:(?:!<[^>\s]*>|[!&][^\s,\[\]{}]*)(?:[ \t]+|$))+`) - // blockPattern is the header of a YAML block scalar, | or > with its - // chomping and indentation indicators, up to the end of its line. - blockPattern = regexp.MustCompile(`^[|>][-+0-9]*[ \t]*(?:#[^\n]*)?(?:\r?\n|$)`) -) - // RedactPatterns returns text with the credentials it can recognize by -// their shape replaced by [Redacted]. Use it where the secrets are not known -// in advance, as they are for [Redact]: on what a server, a model or a log -// file says, before it is stored or shown. It replaces +// their shape replaced by [Redacted]. // -// - the value of a labeled assignment, in JSON, YAML, an environment -// file or a query string, whose name ends in api_key, access_token, -// token, secret, password, credential, authorization or auth, in any -// case and with "-" or "_" between the words; -// - the credential after "Bearer "; -// - tokens whose prefix names their issuer: sk-, ghp_, gho_, ghu_, ghs_, -// ghr_, glpat- and the AKIA of an AWS access key ID. -// -// The value of an assignment is read the way the formats write it, so that -// none of it is left behind and the text keeps its structure: -// -// - A quoted value keeps its quotes: {"api_key":"sk-…"} becomes -// {"api_key":"[REDACTED]"}. Backslash escapes and the doubled quotes -// of YAML ('it”s') are part of the value. -// - An unquoted value is replaced without quotes, DB_PASSWORD=hunter2 -// becomes DB_PASSWORD=[REDACTED], unless it is the value of a quoted -// JSON name, {"token": 12345}, which becomes {"token": "[REDACTED]"} so -// that JSON stays JSON. It runs up to white space, a comma, a -// semicolon, a closing brace or a quote, so the rest of a query string -// after a credential goes with it, and takes the scheme of an HTTP -// authorization along: "Authorization: Basic …" becomes -// "Authorization: [REDACTED]". -// - An array or an object is replaced as a whole, nested ones and -// brackets inside its strings included: {"token": ["a", "b"]} becomes -// {"token": "[REDACTED]"}. -// - An HTTP authorization with a scheme, such as "Authorization: Digest -// username=…, response=…", is replaced up to the end of its line. -// - A YAML block scalar, password: | or >, and a value on the lines -// indented below its name, are replaced with all of those lines. A -// name without a value on its line or below it, as in an empty -// PASSWORD= followed by the next setting, is left alone. -// - The value of a JSON name may stand on a later line. The tags and -// anchors of a YAML value, password: !!str hunter2, go with it, and a -// comment after the name stays while the value below it goes. -// - An assignment inside a JSON string, as in -// {"message":"token=abc def"}, is replaced inside the string, and its -// value ends at the latest where the string does. A value in the -// escaped quotes of JSON inside a JSON string keeps them. -// - A quoted value, an array or an object that is never closed, in text -// cut short, is replaced up to the end of the text, or of the JSON -// string it is in. -// -// A secret without a label or a known prefix looks like any other word and -// stays. RedactPatterns is a safety net for text from elsewhere, not a -// substitute for [Redact] with the secrets a program holds itself. +// Deprecated: Use [redact.Patterns], which does the same. func RedactPatterns(text string) string { - if text == "" { - return text - } - text = redactLabeled(text) - text = bearerPattern.ReplaceAllString(text, "Bearer "+Redacted) - return prefixedPattern.ReplaceAllString(text, Redacted) -} - -// redactLabeled replaces the value of every labeled assignment in text. -func redactLabeled(text string) string { - var ( - b strings.Builder - inStrings jsonStrings - ) - pos := 0 - for pos < len(text) { - m := labelPattern.FindStringSubmatchIndex(text[pos:]) - if m == nil { - break - } - for i := range m { - if m[i] >= 0 { - m[i] += pos - } - } - start := m[1] - jsonName := m[2] >= 0 && text[m[2]:m[3]] == `"` - end, replacement := labeledValue(text, start, m[0], inStrings.inside(text, start), jsonName) - b.WriteString(text[pos:start]) - if end == start { - // No value: nothing to replace, and the label is passed by. - pos = start - continue - } - b.WriteString(replacement) - pos = end - } - b.WriteString(text[pos:]) - return b.String() -} - -// labeledValue reads the value that starts at start, after a label that -// starts at label, and returns where it ends and what replaces it. inString -// says whether the value lies inside a JSON string, jsonName whether the -// label is a quoted JSON name. A value of nothing ends at start. -// -// The value of a JSON name may follow on a later line, after JSON white -// space, which is kept. The tags and anchors of a YAML node in front of a -// value (!!str, &name) are replaced with it. -func labeledValue(text string, start, label int, inString, jsonName bool) (int, string) { - from := start - if jsonName && !inString { - for from < len(text) && strings.IndexByte(" \t\r\n", text[from]) >= 0 { - from++ - } - // A quoted name is YAML as often as JSON. A value on a later line - // that cannot start a JSON value, such as a YAML sequence or block, - // is left to the YAML rules, which take all of it. - if strings.ContainsRune(text[start:from], '\n') && (!jsonMember(text, label) || !jsonValueStart(text[from:])) { - from = start - } - } - properties := 0 - if !inString { - if loc := propertiesPattern.FindStringIndex(text[from:]); loc != nil && loc[0] == 0 { - properties = loc[1] - } - } - comment := "" - if at := from + properties; !inString && at > 0 && (text[at-1] == ' ' || text[at-1] == '\t') && - strings.HasPrefix(text[at:], "#") { - // A YAML comment ends the line; the value may stand below it. - comment = text[at:] - if i := strings.IndexByte(comment, '\n'); i >= 0 { - comment = strings.TrimSuffix(comment[:i], "\r") - } - } - at := from + properties + len(comment) - end, replacement := valueAt(text, at, label, inString, jsonName) - if end == at { - return start, "" - } - return end, text[start:from] + comment + replacement -} - -// valueAt is labeledValue for a value that starts right at start. -func valueAt(text string, start, label int, inString, jsonName bool) (int, string) { - rest := text[start:] - switch { - case rest == "": - return start, "" - case inString && rest[0] == '"' && closesString(text, start): - // No value before the end of the JSON string the assignment is in. - return start, "" - case inString && rest[0] == '"': - // A quote that does not end the string: what looked like a JSON - // string was a stray quote, as in the YAML {note: 5" screen, - // password: "…"}, and the value is a quoted string of its own. - return quotedEnd(text, start, false), `"` + Redacted + `"` - case strings.HasPrefix(rest, `\"`): - return escapedStringEnd(text, start), `\"` + Redacted + `\"` - case rest[0] == '"' || rest[0] == '\'': - return quotedEnd(text, start, inString), rest[:1] + Redacted + rest[:1] - case rest[0] == '[' || rest[0] == '{': - return compositeEnd(text, start, inString), quoted(Redacted, jsonName) - case !inString && (rest[0] == '\n' || strings.HasPrefix(rest, "\r\n")): - // Nothing on the line of the label: the value is on the lines - // indented below it, as YAML may write it, or there is none, as in - // an empty PASSWORD= followed by the next setting. - from := start + 1 - if rest[0] == '\r' { - from++ - } - end := blockEnd(text, from, lineIndent(text, label)) - if end == from { - // YAML lets a sequence stand at the indentation of its key. - end = sequenceEnd(text, from, lineIndent(text, label)) - } - if end == from { - return start, "" - } - // The value keeps the line and indentation of its first line that - // is not blank. - value := text[from:end] - for { - line, rest, more := strings.Cut(value, "\n") - if !more || strings.TrimSpace(line) != "" { - break - } - value = rest - } - indent := value[:len(value)-len(strings.TrimLeft(value, " \t"))] - return end, text[start:from] + indent + Redacted - } - if header := blockPattern.FindString(rest); header != "" && !inString { - from := start + len(header) - end := blockEnd(text, from, lineIndent(text, label)) - if end == from { - // No lines below the header: its line break stays. - return end, Redacted + lineBreakOf(header) - } - // The line break after the last line of the block stays. - return end, Redacted - } - scheme := schemePattern.FindString(rest) - if scheme != "" { - if end := authorizationEnd(text, start+len(scheme), inString); end > start+len(scheme) { - return end, quoted(Redacted, jsonName) - } - } - // A member of a flow mapping, YAML ({password: two words}) or JSON, - // ends its plain value at a comma or a closing bracket, not at a space - // or a line break: a YAML flow scalar may have both, and a JSON number - // or literal ends there anyway. - flow := !inString && jsonMember(text, label) - end := start + len(scheme) - for end < len(text) { - c := text[end] - if c == '\\' { - // An escape, \" inside a JSON string among them, is part of - // the value. - end = min(end+2, len(text)) - continue - } - if flow { - if strings.IndexByte(`,}]`, c) >= 0 { - break - } - } else if c <= ' ' || strings.IndexByte(`,;}"'`, c) >= 0 { - break - } - end++ - } - if flow { - end = start + len(strings.TrimRight(text[start:end], " \t\r\n")) - } - if end == start+len(scheme) { - // Nothing after a scheme: the scheme word is the value, as in - // auth=Basic. Nothing at all: no value. - end = start + len(strings.TrimRight(scheme, " \t")) - if end == start { - return start, "" - } - } - if !inString && !flow && ownLine(text, label) { - end = max(end, plainScalarEnd(text, start, lineIndent(text, label))) - } - return end, quoted(Redacted, jsonName) -} - -// ownLine reports whether the label at label starts its line, white space -// and YAML sequence dashes aside, as a YAML key or a setting in a file of -// settings does. -func ownLine(text string, label int) bool { - lineStart := strings.LastIndexByte(text[:label], '\n') + 1 - return lineStart+lineIndent(text, label) == label -} - -// plainScalarEnd returns where a value that starts at start beside a label -// on its own line ends, read as a YAML plain scalar: at the end of the line -// or before a comment (" #") on it, and past the lines below that are -// indented further than indent, the indentation of the label's line, which -// continue it. -func plainScalarEnd(text string, start, indent int) int { - lineEnd := len(text) - if i := strings.IndexByte(text[start:], '\n'); i >= 0 { - lineEnd = start + i - } - line := text[start:lineEnd] - if i := strings.Index(line, " #"); i >= 0 { - line = line[:i] - } else if i := strings.Index(line, "\t#"); i >= 0 { - line = line[:i] - } - end := start + len(strings.TrimRight(line, " \t\r")) - if lineEnd < len(text) && len(line) == lineEnd-start { - if more := blockEnd(text, lineEnd+1, indent); more > lineEnd+1 { - end = more - } - } - return end -} - -// closesString reports whether the quote at i reads as the end of a JSON -// string: what follows it, after white space, is a comma, a closing bracket -// or brace, a colon, or the end of the line or of the text. -func closesString(text string, i int) bool { - for i++; i < len(text); i++ { - switch text[i] { - case ' ', '\t', '\r': - continue - case ',', '}', ']', ':', '\n': - return true - } - return false - } - return true -} - -// authorizationEnd returns where the credentials of an HTTP authorization -// that start at start end: at the end of the line, or inside a JSON string -// (inString) where that string ends, if that comes first. The parameters of -// a scheme such as Digest, username="…", nonce="…", response="…", are all -// part of them. -func authorizationEnd(text string, start int, inString bool) int { - for i := start; i < len(text); i++ { - switch text[i] { - case '\\': - i++ - case '\n': - return i - boolToInt(i > start && text[i-1] == '\r') - case '"': - if inString { - return i - } - } - } - return len(text) -} - -func boolToInt(b bool) int { - if b { - return 1 - } - return 0 -} - -// quotedEnd returns the index after the string in double or single quotes -// that starts at start. A string that is never closed ends with the text, -// or inside a JSON string (inString) where that string does. -// -// In double quotes a backslash escapes the character after it. Single -// quotes are read both ways they are written: with a backslash as an -// escape, as in Python or JavaScript, and, as in YAML and the shell, with a -// backslash as itself and a doubled quote standing for one. The string -// ends where the later of the two readings ends it, so that no reading -// leaves a part of it behind. -func quotedEnd(text string, start int, inString bool) int { - if text[start] == '\'' { - return max(stringEnd(text, start, inString, true, false), stringEnd(text, start, inString, false, true)) - } - return stringEnd(text, start, inString, true, false) -} - -// stringEnd is quotedEnd for one way of reading the string: escapes says -// whether a backslash escapes the character after it, doubled whether a -// doubled quote stands for one. -func stringEnd(text string, start int, inString, escapes, doubled bool) int { - quote := text[start] - for i := start + 1; i < len(text); i++ { - switch c := text[i]; { - case c == '\\' && (escapes || inString): - // Inside a JSON string a backslash escapes for that string, - // whatever the inner string makes of it: \" is no end there. - i++ - case c == quote && doubled && i+1 < len(text) && text[i+1] == quote: - i++ - case c == quote: - return i + 1 - case c == '"' && inString: - return i - } - } - return len(text) -} - -// escapedStringEnd returns the index after the string in the escaped quotes -// \" of JSON inside a JSON string that starts at start. Its own escaped -// quotes, \\\", are part of it. A string that is never closed ends where -// the enclosing JSON string does, or with the text. -func escapedStringEnd(text string, start int) int { - for i := start + 2; i < len(text); i++ { - switch text[i] { - case '"': - return i - case '\\': - if i+1 < len(text) && text[i+1] == '"' { - return i + 2 - } - if i+1 < len(text) && text[i+1] == '\\' { - // An escaped backslash of the enclosing string. Followed by - // \", it escapes a quote of the inner string, which is part - // of it; otherwise the character after it is read anew, so - // a quote there still ends the inner string. - if i+3 < len(text) && text[i+2] == '\\' && text[i+3] == '"' { - i += 3 - } else { - i++ - } - continue - } - i++ - } - } - return len(text) -} - -// blockEnd returns where the lines of a YAML block scalar end: before the -// line break ahead of the first line that is not blank and is indented no -// further than indent, the indentation of the line holding its key, or at -// the end of the text. from is where its first line starts. -func blockEnd(text string, from, indent int) int { - end := from - for line := from; line < len(text); { - next := strings.IndexByte(text[line:], '\n') - body := text[line:] - if next >= 0 { - body = text[line : line+next] - } - content := strings.TrimLeft(body, " \t") - if strings.TrimSpace(content) != "" && len(body)-len(content) <= indent { - break - } - end = line + len(strings.TrimRight(body, "\r")) - if next < 0 { - return len(text) - } - line += next + 1 - } - return end -} - -// sequenceEnd returns where a YAML sequence written at the indentation of its -// key ends: before the line break ahead of the first line that is not blank, -// is indented no further than indent and is not an item ("- …") at indent -// itself. from is where its first line starts; when that line is no item, -// there is no such sequence and sequenceEnd returns from. -func sequenceEnd(text string, from, indent int) int { - end := from - for line := from; line < len(text); { - next := strings.IndexByte(text[line:], '\n') - body := text[line:] - if next >= 0 { - body = text[line : line+next] - } - content := strings.TrimLeft(body, " \t") - if trimmed := strings.TrimSpace(content); trimmed != "" && len(body)-len(content) <= indent { - item := len(body)-len(content) == indent && (trimmed == "-" || strings.HasPrefix(content, "- ") || strings.HasPrefix(content, "-\t")) - if !item { - break - } - } else if end == from && trimmed != "" { - // A first line indented further is a block, not this sequence. - return from - } - end = line + len(strings.TrimRight(body, "\r")) - if next < 0 { - return len(text) - } - line += next + 1 - } - return end -} - -// lineIndent returns how far the line holding text[i] is indented, up to -// the key or setting that starts there. -func lineIndent(text string, i int) int { - lineStart := strings.LastIndexByte(text[:i], '\n') + 1 - line := text[lineStart:i] - rest := strings.TrimLeft(line, " \t") - // A key in a sequence item is indented as far as the key itself: the - // dashes in front of it are part of its indentation, as YAML counts - // it, so the item's other keys are its siblings. - for len(rest) > 1 && rest[0] == '-' && (rest[1] == ' ' || rest[1] == '\t') { - rest = strings.TrimLeft(rest[1:], " \t") - } - return len(line) - len(rest) -} - -// lineBreakOf returns the line break a block scalar header ends in. -func lineBreakOf(header string) string { - switch { - case strings.HasSuffix(header, "\r\n"): - return "\r\n" - case strings.HasSuffix(header, "\n"): - return "\n" - } - return "" -} - -// quoted returns s in double quotes when quote is set. -func quoted(s string, quote bool) string { - if quote { - return `"` + s + `"` - } - return s -} - -// jsonStrings tells whether a position of a text lies inside a JSON string, -// reading the text once from its start as positions are asked for in -// increasing order. -// -// A double quote opens or closes a JSON string, except inside single -// quotes, the strings of YAML and the shell, where it is a character like -// any other. Every line starts outside of any string: a JSON string holds -// no line break, and so a stray quote, in prose or a plain YAML value, is -// forgotten at the end of its line. -type jsonStrings struct { - pos int - in bool - single bool -} - -// inside reports whether text[i] lies inside a string in double quotes. -func (s *jsonStrings) inside(text string, i int) bool { - for ; s.pos < i && s.pos < len(text); s.pos++ { - switch c := text[s.pos]; { - case c == '\n': - s.in, s.single = false, false - case s.single: - if c == '\'' { - s.single = false - } - case c == '\\': - if s.in { - s.pos++ - } - case c == '"': - s.in = !s.in - case c == '\'' && !s.in: - s.single = true - } - } - return s.in -} - -// compositeEnd returns the index after the array or object that opens at -// start, counting nested brackets and braces and skipping over strings in -// double or single quotes, or len(text) when it is never closed. Inside a -// JSON string (inString), its strings are in escaped quotes, and it ends at -// the latest before the quote that ends the enclosing string. Strings in -// single quotes are read both ways quotedEnd reads them, and the later end -// wins. -func compositeEnd(text string, start int, inString bool) int { - if inString { - return escapedCompositeEnd(text, start) - } - return max(bracketEnd(text, start, false), bracketEnd(text, start, true)) -} - -// bracketEnd is compositeEnd outside a JSON string for one way of reading -// strings in single quotes: literal says whether a backslash in them is -// itself, with a doubled quote standing for one, or escapes the character -// after it. In double quotes a backslash always escapes. -func bracketEnd(text string, start int, literal bool) int { - depth := 0 - var quote byte - for i := start; i < len(text); i++ { - c := text[i] - switch { - case quote == '\'' && literal: - if c == '\'' { - if i+1 < len(text) && text[i+1] == '\'' { - i++ - } else { - quote = 0 - } - } - case quote != 0: - switch c { - case '\\': - i++ - case quote: - quote = 0 - } - case c == '"' || c == '\'': - quote = c - case c == '[' || c == '{': - depth++ - case c == ']' || c == '}': - depth-- - if depth == 0 { - return i + 1 - } - } - } - return len(text) -} - -// escapedCompositeEnd is compositeEnd for an array or object inside a JSON -// string, whose own strings are in the escaped quotes \". -func escapedCompositeEnd(text string, start int) int { - depth := 0 - inner, single := false, false - for i := start; i < len(text); i++ { - switch c := text[i]; { - case c == '"': - return i - case c == '\\' && i+1 < len(text) && text[i+1] == '\\': - // An escaped backslash of the enclosing string. Followed by \", - // it escapes a quote of the inner text: no delimiter. Otherwise - // the character after it is read anew. - if i+3 < len(text) && text[i+2] == '\\' && text[i+3] == '"' { - i += 3 - } else { - i++ - } - case c == '\\': - if i+1 < len(text) && text[i+1] == '"' && !single { - inner = !inner - } - i++ - case inner: - case c == '\'': - // Brackets in a single-quoted string are text, as in a - // composite outside a JSON string. - single = !single - case single: - case c == '[' || c == '{': - depth++ - case c == ']' || c == '}': - depth-- - if depth == 0 { - return i + 1 - } - } - } - return len(text) -} - -// jsonMember reports whether the name at label is a member of a JSON object: -// what stands before it, white space aside, opens the object or ends the -// member before it. -func jsonMember(text string, label int) bool { - before := strings.TrimRight(text[:label], " \t\r\n") - return before != "" && (before[len(before)-1] == '{' || before[len(before)-1] == ',') -} - -// jsonValueStart reports whether s starts with what can start a JSON value: -// a string, an object, an array, a number, true, false or null. -func jsonValueStart(s string) bool { - if s == "" { - return false - } - switch c := s[0]; { - case c == '"' || c == '{' || c == '[': - return true - case c >= '0' && c <= '9': - return true - case c == '-': - return len(s) > 1 && s[1] >= '0' && s[1] <= '9' - } - for _, word := range []string{"true", "false", "null"} { - if strings.HasPrefix(s, word) { - return true - } - } - return false + return redact.Patterns(text) } diff --git a/secret/resolve.go b/secret/resolve.go index e3b1be9..3ac81f4 100644 --- a/secret/resolve.go +++ b/secret/resolve.go @@ -1,18 +1,14 @@ package secret import ( - "bytes" "errors" "fmt" - "io" "io/fs" "os" "strings" "unicode" "unicode/utf8" - xterm "golang.org/x/term" - "github.com/mittwald/cli-kit/term" ) @@ -83,44 +79,6 @@ var ( // or stdin when MaxLen is zero. const DefaultMaxLen = 4096 -// Request describes one interactive question for a [PromptFunc]. -type Request struct { - // Label is the question, such as "Password" or "Password to encrypt - // the export". - Label string - // Name is the secret as the messages call it, such as "password". The - // second question of a confirmed entry asks to repeat it. - Name string - // Hint is optional text to show before the first question, such as - // where to create a token and which scopes it needs. The prompts of this - // package show the URLs in it as hyperlinks (see term.Linkify). - Hint string - // Repeat marks the second question of a confirmed entry. - Repeat bool -} - -// Prompt returns the text to put in front of the input field: "Password to -// encrypt the export: ", or "Repeat password: " for the second question of a -// confirmed entry. -func (r Request) Prompt() string { - if r.Repeat { - name := r.Name - if name == "" { - name = r.Label - } - return "Repeat " + name + ": " - } - return r.Label + ": " -} - -// PromptFunc asks the user for a secret without echoing it. It returns an -// error wrapping [ErrNoSource] when there is no terminal to ask on. -// -// [TTYPrompt] is the default. A tool with its own input widget, such as -// pick.Input from this module, turns it into a PromptFunc with -// [InputPrompt]. -type PromptFunc func(Request) (string, error) - // Resolver finds one secret. See the package documentation for the order // in which it tries its sources. All fields are optional; a source whose // field is empty is skipped. @@ -471,144 +429,6 @@ func (r *Resolver) stored() (string, bool, error) { return value, value != "", nil } -// readFirstLine reads the first line of rd. It stops at the newline, so a -// pipe that stays open after the secret does not block, and the rest of -// stdin stays unread. A trailing CR is dropped, so a file written on -// Windows works, and so is a UTF-8 byte order mark in front; interior -// spaces are kept, because a passphrase may contain them. -// -// A line longer than MaxLen is refused with ErrTooLong rather than cut -// short, and one that is no text (UTF-16, or holding a NUL byte) with an -// error wrapping ErrNotText. Neither error carries what was read. -func (r *Resolver) readFirstLine(rd io.Reader) (string, error) { - limit := r.maxLen() - data := make([]byte, 0, min(limit, 256)) - var b [1]byte - for { - n, err := rd.Read(b[:]) - if n == 1 { - if b[0] == '\n' { - break - } - data = append(data, b[0]) - // The first bytes of a byte order mark exceed a short limit - // before they are one: they are judged once they are complete, - // or turned out to be something else. - if !startsByteOrderMark(data) && tooLong(data, limit) { - if textErr := checkText(data); textErr != nil { - return "", textErr - } - return "", ErrTooLong - } - } - if errors.Is(err, io.EOF) { - break - } - if err != nil { - return "", err - } - } - if err := checkText(data); err != nil { - return "", err - } - // A line that ended inside what could have become a byte order mark was - // not judged above. - if tooLong(data, limit) { - return "", ErrTooLong - } - line := strings.TrimSuffix(strings.TrimPrefix(string(data), utf8BOM), "\r") - if r.TrimSpace { - line = strings.TrimSpace(line) - } - return line, nil -} - -// tooLong reports whether data, the start of a line, already holds more -// than limit bytes of secret. A byte order mark in front does not count, -// and neither does a CR at the end, which may turn out to belong to the -// line ending. -func tooLong(data []byte, limit int) bool { - n := len(data) - if bytes.HasPrefix(data, []byte(utf8BOM)) { - n -= len(utf8BOM) - } - if n > 0 && data[len(data)-1] == '\r' { - n-- - } - return n > limit -} - -// startsByteOrderMark reports whether data is the beginning of a UTF-8 byte -// order mark that further bytes have yet to complete. -func startsByteOrderMark(data []byte) bool { - return len(data) < len(utf8BOM) && strings.HasPrefix(utf8BOM, string(data)) -} - -// checkText refuses a line that is not text in an encoding a secret can be -// read from: UTF-16, which starts with a byte order mark, and anything with -// a NUL byte, which UTF-16 without the mark is full of. -func checkText(data []byte) error { - switch { - case bytes.HasPrefix(data, []byte("\xff\xfe")), bytes.HasPrefix(data, []byte("\xfe\xff")): - return errUTF16 - case bytes.IndexByte(data, 0) >= 0: - return errNUL - } - return nil -} - -func (r *Resolver) ask() (string, error) { - prompt := r.Prompt - if prompt == nil { - prompt = TTYPrompt - } - req := Request{Label: r.label(), Name: r.name(), Hint: r.Hint} - value, err := prompt(req) - if err != nil { - return "", r.promptFailed(err) - } - if r.TrimSpace { - value = strings.TrimSpace(value) - } - if value == "" { - return "", fail(ErrEmpty, nil, "empty %s", r.name()) - } - if r.Confirm { - req.Repeat = true - again, err := prompt(req) - if err != nil { - return "", r.promptFailed(err) - } - if r.TrimSpace { - again = strings.TrimSpace(again) - } - if again != value { - return "", fail(ErrMismatch, nil, "%ss do not match", r.name()) - } - } - return value, nil -} - -// promptFailed words a failed prompt. A missing terminal becomes the list -// of sources the user could have offered instead. -func (r *Resolver) promptFailed(err error) error { - if !errors.Is(err, ErrNoSource) { - return fail(nil, err, "reading %s", r.name()) - } - var options []string - if r.Env != "" { - options = append(options, "set $"+r.Env) - } - if r.FileFlag != "" { - options = append(options, "pass "+r.FileFlag) - } - if !r.StdinBusy { - options = append(options, "pipe one to stdin") - } - options = append(options, "run this on a terminal") - return fail(ErrNoSource, nil, "no %s available: %s", r.name(), joinOr(options)) -} - // resolveError is how a Resolver reports a failure: its message is meant // for the user of the command as it is, while errors.Is still finds the // sentinel error it belongs to and the cause behind it. @@ -652,78 +472,3 @@ var ( defaultOpenTTY = term.OpenTTY openTTY = defaultOpenTTY ) - -// TTYPrompt is the default [PromptFunc]. It asks on the controlling -// terminal, which works even when stdin and stdout are redirected, and -// reads the answer with echo turned off. Without a controlling terminal it -// returns an error wrapping [ErrNoSource]. -// -// The terminal gets its echo back when the process ends at the prompt, too. -// While TTYPrompt waits for the answer, the restoring is registered with -// live.OnRestore of this module, so it happens wherever a program lets -// package live clean up: in the signal handler of live.InstallSignalRestore -// before the signal ends the process, in live.RestoreAll, and in -// Cursor.RestoreOnPanic. Call live.RestoreAll only on the way out of the -// process: at a prompt that goes on waiting afterwards, the answer would be -// echoed. -// -// On Unix TTYPrompt also watches SIGINT (Ctrl-C), SIGTERM and SIGHUP -// itself, for programs without that handler: it restores the terminal, and -// then the signal ends the process as it does by default, also in a program -// that handles the signal in its own way, since the read of the answer -// cannot be interrupted otherwise. A signal the process ignores stays -// ignored. On other systems a process that is killed at the prompt leaves -// the console as it is, unless live's handler is installed. -func TTYPrompt(req Request) (string, error) { - tty, err := openTTY() - if err != nil { - return "", fmt.Errorf("%w: %w", ErrNoSource, err) - } - defer tty.Close() - if !term.IsTerminal(tty) { - return "", ErrNoSource - } - out, closeOut := promptOutput(tty) - defer closeOut() - if req.Hint != "" && !req.Repeat { - _, _ = fmt.Fprintln(term.Links(out), req.Hint) - } - stop := restoreOnExit(tty, out) - _, _ = io.WriteString(out, req.Prompt()) - value, err := xterm.ReadPassword(int(tty.Fd())) - stop() - // The terminal swallowed the Enter key along with the echo, so the - // cursor is still on the prompt line. - _, _ = io.WriteString(out, "\n") - if err != nil { - return "", fmt.Errorf("terminal: %w", err) - } - return string(value), nil -} - -// InputPrompt returns a [PromptFunc] that asks with input, a text field -// that draws nothing for what is typed, on in and out. With pick.Input from -// this module: -// -// prompt := secret.InputPrompt(os.Stdin, os.Stderr, -// func(in, out *os.File, prompt string) (string, error) { -// return pick.Input(in, out, pick.InputOptions{Prompt: prompt, Secret: true}) -// }) -// -// Unlike [TTYPrompt] it asks on in and out only. Where either is not a -// terminal it returns [ErrNoSource] without calling input, so a [Resolver] -// names the sources the user could offer instead. Before the first question -// of a request it writes the request's Hint to out, its URLs as hyperlinks. -// The question passed to input is [Request.Prompt]; input's errors are -// returned as they are. -func InputPrompt(in, out *os.File, input func(in, out *os.File, prompt string) (string, error)) PromptFunc { - return func(req Request) (string, error) { - if !term.Interactive(in, out) { - return "", ErrNoSource - } - if req.Hint != "" && !req.Repeat { - _, _ = fmt.Fprintln(term.Links(out), req.Hint) - } - return input(in, out, req.Prompt()) - } -} diff --git a/secret/store_test.go b/secret/store_test.go index c57ee56..74a089d 100644 --- a/secret/store_test.go +++ b/secret/store_test.go @@ -1,12 +1,8 @@ package secret import ( - "bytes" - "encoding/base64" - "encoding/json" "errors" "io/fs" - "net/url" "os" "path/filepath" "runtime" @@ -133,7 +129,7 @@ func TestKeyringErrorsDoNotCarryTheSecret(t *testing.T) { } func containsSecret(err error, secret string) bool { - return err != nil && Redact(err.Error(), secret) != err.Error() + return err != nil && strings.Contains(err.Error(), secret) } func TestFileStore(t *testing.T) { @@ -512,85 +508,6 @@ func TestFallbackPrefersPrimary(t *testing.T) { } } -func TestRedact(t *testing.T) { - got := Redact("token=abc123 again abc123 and abc", "abc", "abc123", "") - want := "token=[REDACTED] again [REDACTED] and [REDACTED]" - if got != want { - t.Fatalf("Redact = %q, want %q", got, want) - } - for _, tc := range []struct { - name string - text string - secrets []string - want string - }{ - {"no secrets", "plain text", nil, "plain text"}, - {"nothing found", "plain text", []string{"hunter2"}, "plain text"}, - {"only empty secrets", "plain text", []string{"", ""}, "plain text"}, - {"overlapping secrets", "abcdef", []string{"abcd", "cdef"}, "[REDACTED]"}, - {"overlap with the longer one behind", "xabcdef!", []string{"bcdef", "abc"}, "x[REDACTED]!"}, - {"a secret overlapping itself", "-aaa-", []string{"aa"}, "-[REDACTED]-"}, - {"neighbors stay apart", "abcabc", []string{"abc"}, "[REDACTED][REDACTED]"}, - {"the marker is never matched", "token=longsecret", []string{"longsecret", "RED", "[", "E"}, "token=[REDACTED]"}, - {"regular expression characters", "a.*b and axxb", []string{".*"}, "a[REDACTED]b and axxb"}, - {"at both ends", "pw and pw", []string{"pw"}, "[REDACTED] and [REDACTED]"}, - } { - if got := Redact(tc.text, tc.secrets...); got != tc.want { - t.Errorf("%s: Redact(%q, %q) = %q, want %q", tc.name, tc.text, tc.secrets, got, tc.want) - } - } -} - -// A secret is also found in the forms it takes inside a request. -func TestRedactEscapedForms(t *testing.T) { - const tricky = `p@ss w/rd"<1>&ü` - body, err := json.Marshal(map[string]string{"password": tricky}) - if err != nil { - t.Fatal(err) - } - var plain bytes.Buffer - enc := json.NewEncoder(&plain) - enc.SetEscapeHTML(false) - if err := enc.Encode(map[string]string{"password": tricky}); err != nil { - t.Fatal(err) - } - for _, tc := range []struct{ name, text, want string }{ - {"as it is", "password: " + tricky + ".", "password: [REDACTED]."}, - {"form body", "user=alice&password=" + url.QueryEscape(tricky) + "&x=1", "user=alice&password=[REDACTED]&x=1"}, - {"query with %20", "?password=" + strings.ReplaceAll(url.QueryEscape(tricky), "+", "%20") + "&x=1", "?password=[REDACTED]&x=1"}, - {"URL path", "GET /keys/" + url.PathEscape(tricky) + "/info", "GET /keys/[REDACTED]/info"}, - {"JSON", string(body), `{"password":"[REDACTED]"}`}, - {"JSON without HTML escapes", strings.TrimSpace(plain.String()), `{"password":"[REDACTED]"}`}, - {"lower-case URL escapes", "?password=" + strings.ToLower(url.QueryEscape(tricky)) + "&x=1", "?password=[REDACTED]&x=1"}, - } { - got := Redact(tc.text, tricky) - if got != tc.want { - t.Errorf("%s: Redact(%q) = %q, want %q", tc.name, tc.text, got, tc.want) - } - } - // A secret that is not UTF-8 is matched byte for byte, its URL escapes - // in either case. - if got := Redact("pw=%\xff and pw=%25%FF and %25%ff", "%\xff"); got != "pw=[REDACTED] and pw=[REDACTED] and [REDACTED]" { - t.Errorf("Redact of a non-UTF-8 secret = %q", got) - } - - // A quote at the end of a secret stays part of its JSON form. - if got := Redact(`{"password":"say \"hi\""}`, `say "hi"`); got != `{"password":"[REDACTED]"}` { - t.Errorf("Redact of a quoted secret in JSON = %q", got) - } - - // What Redact cannot find, as documented: a secret inside a larger - // encoded value. - basic := "Authorization: Basic " + base64.StdEncoding.EncodeToString([]byte("alice:"+tricky)) - if got := Redact(basic, tricky); got != basic { - t.Errorf("Redact found the password inside Basic credentials: %q; update its documentation", got) - } - encoded := base64.StdEncoding.EncodeToString([]byte("alice:" + tricky)) - if got := Redact(basic, tricky, encoded); got != "Authorization: Basic [REDACTED]" { - t.Errorf("Redact with the encoded credentials as a secret = %q", got) - } -} - func TestWriteFileReplacesPrivately(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "token-cache.json") diff --git a/selfupdate/checksum.go b/selfupdate/checksum.go index 5f89675..27916fd 100644 --- a/selfupdate/checksum.go +++ b/selfupdate/checksum.go @@ -31,10 +31,9 @@ var ( // was not corrupted, and not altered on a transport or storage hop // between the release and here. It proves nothing about who made the // file. An [Updater] fetches the checksums file from the same release as -// the archive, and the file carries no signature, so somebody who can -// write the release's files can replace both, and the pair verifies. The -// update is as trustworthy as the place the release is published in and -// the TLS connection to it, not more. +// the archive, so somebody who can write the release's files can replace +// both, and the pair verifies, unless the Updater has a [Verifier] that +// checks a signature of the checksums file. func VerifyChecksum(checksums []byte, name string, data []byte) error { want, err := findChecksum(checksums, name) if err != nil { diff --git a/selfupdate/coverage_test.go b/selfupdate/coverage_test.go new file mode 100644 index 0000000..7b7093f --- /dev/null +++ b/selfupdate/coverage_test.go @@ -0,0 +1,504 @@ +package selfupdate + +import ( + "archive/zip" + "bytes" + "context" + "errors" + "fmt" + "hash/crc32" + "io" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "runtime" + "strings" + "sync/atomic" + "testing" + "testing/iotest" +) + +// skipWithoutPermissions skips a test that needs a directory the user +// cannot write to. +func skipWithoutPermissions(t *testing.T) { + t.Helper() + if runtime.GOOS == "windows" || os.Geteuid() == 0 { + t.Skip("needs POSIX permissions and a non-root user") + } +} + +func TestPrepareRefusesAnIncompleteUpdater(t *testing.T) { + u, _, _ := newFixture(t) + u.Source = nil + if _, err := u.Update(context.Background(), false); err == nil || !strings.Contains(err.Error(), "Source is required") { + t.Errorf("Update without Source = %v", err) + } + if _, err := u.Install(context.Background(), Release{Tag: "v1.1.0"}); err == nil || !strings.Contains(err.Error(), "Source is required") { + t.Errorf("Install without Source = %v", err) + } + if _, _, err := u.Check(context.Background()); err == nil || !strings.Contains(err.Error(), "Source is required") { + t.Errorf("Check without Source = %v", err) + } +} + +func TestPrepareReportsAnExecutableThatCannotBeResolved(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("a path below a file is reported as missing on Windows") + } + u, source, exe := newFixture(t) + u.Executable = filepath.Join(exe, "below-a-file") + if _, err := u.Update(context.Background(), false); err == nil || !strings.Contains(err.Error(), "resolve") { + t.Fatalf("Update = %v, want the failed resolution reported", err) + } + if source.calls != 0 { + t.Fatal("asked the source before the executable was found") + } +} + +// Without Managed, the package managers' directories are judged; a +// temporary directory is none of them. +func TestPrepareJudgesByDefault(t *testing.T) { + u, _, exe := newFixture(t) + u.Managed = nil + if result, err := u.Update(context.Background(), false); err != nil || !result.Updated { + t.Fatalf("Update = %+v, %v", result, err) + } + if got := contents(t, exe); got != newBinary { + t.Fatalf("executable holds %q", got) + } +} + +func TestPrepareRefusesADirectoryItCannotWrite(t *testing.T) { + skipWithoutPermissions(t) + u, source, exe := newFixture(t) + dir := filepath.Dir(exe) + if err := os.Chmod(dir, 0o555); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(dir, 0o755) }) + if _, err := u.Update(context.Background(), false); err == nil || !strings.Contains(err.Error(), "no write permission") { + t.Fatalf("Update = %v, want the permission reported", err) + } + if source.calls != 0 { + t.Fatal("asked the source before checking the directory") + } +} + +func TestPrepareReportsAMissingDirectory(t *testing.T) { + u, _, exe := newFixture(t) + u.Executable = filepath.Join(filepath.Dir(exe), "missing", "tool") + if _, err := u.Update(context.Background(), false); err == nil || !strings.Contains(err.Error(), "cannot write to") { + t.Fatalf("Update = %v, want the missing directory reported", err) + } +} + +// What cannot take the new binary's place is reported, and the update did +// not happen. +func TestInstallReportsAFailedReplacement(t *testing.T) { + u, _, exe := newFixture(t) + // A directory takes no file's place, on Windows either, where the old + // file is moved aside first. + u.Executable = filepath.Join(filepath.Dir(exe), "tool-dir") + u.Binary = "tool" + if err := os.MkdirAll(filepath.Join(u.Executable, "inner"), 0o700); err != nil { + t.Fatal(err) + } + result, err := u.Update(context.Background(), false) + if err == nil || result.Updated { + t.Fatalf("Update = %+v, %v, want a failed replacement", result, err) + } + if !strings.Contains(err.Error(), "replace") { + t.Fatalf("Update = %v, want the failed replacement reported", err) + } + if _, err := os.Stat(filepath.Join(u.Executable, "inner")); err != nil { + t.Fatalf("the directory was moved or changed: %v", err) + } +} + +func TestUpdaterDefaults(t *testing.T) { + if got := (&Updater{}).platform(); got != CurrentPlatform() { + t.Errorf("platform = %+v, want the current one", got) + } + u := &Updater{Checksums: "SHA256SUMS"} + if got := u.checksums(Release{Tag: "v1.0.0"}); got != "SHA256SUMS" { + t.Errorf("checksums = %q", got) + } + // A ChecksumsFor that names nothing falls back to Checksums. + u.ChecksumsFor = func(Release) string { return "" } + if got := u.checksums(Release{Tag: "v1.0.0"}); got != "SHA256SUMS" { + t.Errorf("checksums with an empty ChecksumsFor = %q", got) + } + if got := (&Updater{}).AssetName(Release{}); got != "" { + t.Errorf("AssetName without Asset = %q", got) + } +} + +// failingSource fails reading every download after its first bytes. +type failingSource struct{ memorySource } + +var errCut = errors.New("connection reset") + +func (f *failingSource) Download(context.Context, Release, string) (io.ReadCloser, error) { + return io.NopCloser(io.MultiReader(strings.NewReader("partial"), iotest.ErrReader(errCut))), nil +} + +func TestUpdateReportsAFailedDownload(t *testing.T) { + u, source, exe := newFixture(t) + u.Source = &failingSource{memorySource: *source} + if _, err := u.Update(context.Background(), false); !errors.Is(err, errCut) || !strings.Contains(err.Error(), "download") { + t.Fatalf("Update = %v, want the download error", err) + } + if got := contents(t, exe); got != "old binary" { + t.Fatalf("executable replaced: %q", got) + } +} + +func TestReplaceExecutableInAMissingDirectory(t *testing.T) { + err := ReplaceExecutable(filepath.Join(t.TempDir(), "missing", "tool"), []byte("new")) + if err == nil || !strings.Contains(err.Error(), "stage new binary") { + t.Fatalf("ReplaceExecutable = %v", err) + } + if err := ReplaceExecutable(filepath.Join(t.TempDir(), "tool"), nil); !errors.Is(err, ErrNoBinary) { + t.Fatalf("ReplaceExecutable of nothing = %v, want ErrNoBinary", err) + } +} + +// A staged file that cannot be moved in leaves the old executable where it +// was. +func TestSwapAsideMovesBackWhenTheStagedFileIsGone(t *testing.T) { + path := filepath.Join(tempDir(t), "tool") + if err := os.WriteFile(path, []byte("old"), 0o755); err != nil { + t.Fatal(err) + } + err := swapAside(path, filepath.Join(filepath.Dir(path), "gone")) + if err == nil || !strings.Contains(err.Error(), "replace") { + t.Fatalf("swapAside = %v", err) + } + if got := contents(t, path); got != "old" { + t.Fatalf("executable holds %q", got) + } +} + +func TestSwapAsideReportsAnExecutableThatCannotMove(t *testing.T) { + skipWithoutPermissions(t) + dir := tempDir(t) + path := filepath.Join(dir, "tool") + if err := os.WriteFile(path, []byte("old"), 0o755); err != nil { + t.Fatal(err) + } + staged := stage(t, path, "new") + if err := os.Chmod(dir, 0o555); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(dir, 0o755) }) + if err := swapAside(path, staged); err == nil || !strings.Contains(err.Error(), "move") { + t.Fatalf("swapAside = %v, want the failed move reported", err) + } +} + +func TestCutDescribeEdgeCases(t *testing.T) { + for _, tc := range []struct { + in string + tag string + ahead int + }{ + {"release-gabc1234", "release-gabc1234", 0}, + {"v1.0.0-gabc1234", "v1.0.0-gabc1234", 0}, + {"gabc1234-gabc1234", "gabc1234-gabc1234", 0}, + {"v1.0.0-99999999999999999999-gabc1234", "v1.0.0-99999999999999999999-gabc1234", 0}, + {"v1.0.0-3-gabc1234-dirty", "v1.0.0", 3}, + } { + tag, ahead, _ := cutDescribe(tc.in) + if tag != tc.tag || ahead != tc.ahead { + t.Errorf("cutDescribe(%q) = %q, %d; want %q, %d", tc.in, tag, ahead, tc.tag, tc.ahead) + } + } +} + +func TestVerifyChecksumRefusesAnOverlongLine(t *testing.T) { + checksums := []byte(strings.Repeat("a", 70_000) + " tool.tar.gz\n") + if err := VerifyChecksum(checksums, "tool.tar.gz", []byte("x")); err == nil || !strings.Contains(err.Error(), "read checksums") { + t.Fatalf("VerifyChecksum = %v", err) + } +} + +// Without Executable, the running executable is the one to replace, with +// symbolic links resolved. +func TestExecutableDefaultsToTheRunningOne(t *testing.T) { + exe, err := os.Executable() + if err != nil { + t.Skip(err) + } + want, err := filepath.EvalSymlinks(exe) + if err != nil { + t.Skip(err) + } + if got, err := (&Updater{}).executable(); err != nil || got != want { + t.Errorf("executable = %q, %v; want %q", got, err, want) + } +} + +func TestCredentialWithoutATokenFunc(t *testing.T) { + if token, err := (&requester{}).credential(context.Background(), true); token != "" || err != nil { + t.Errorf("credential = %q, %v", token, err) + } +} + +func TestTitleOSOfNothing(t *testing.T) { + if got := titleOS(""); got != "" { + t.Errorf("titleOS(\"\") = %q", got) + } +} + +func TestExtractWithoutABinaryName(t *testing.T) { + archive := tarGz(t, map[string][]byte{"tool": executable(linuxAMD64, "binary"+strings.Repeat("x", MinBinarySize)), "README": []byte("r")}) + got, err := ExtractFor(linuxAMD64, "tool.tar.gz", archive, "") + if err != nil || !bytes.Contains(got, []byte("binary")) { + t.Fatalf("ExtractFor = %q, %v; want the largest file", got, err) + } +} + +func TestExtractRefusesALargestFileAboveTheLimit(t *testing.T) { + archive := tarGz(t, map[string][]byte{"big": executable(linuxAMD64, strings.Repeat("x", 100)), "README": []byte("r")}) + _, err := extract(linuxAMD64, "tool.tar.gz", archive, "tool", archiveLimits{entry: 50, total: 1 << 20, entries: 10}) + if err == nil || !strings.Contains(err.Error(), "big is larger than 50 bytes") { + t.Fatalf("extract = %v", err) + } +} + +func TestExtractBoundsTheUnpackedTotal(t *testing.T) { + archive := tarGz(t, map[string][]byte{"tool": executable(linuxAMD64, strings.Repeat("x", 4000))}) + _, err := extract(linuxAMD64, "tool.tar.gz", archive, "tool", archiveLimits{entry: 1 << 20, total: 1000, entries: 10}) + if err == nil || !strings.Contains(err.Error(), "1000 bytes") { + t.Fatalf("extract = %v, want the total bounded", err) + } +} + +// The error lists the first files of an archive without the binary, and +// counts the rest. +func TestExtractListsWhatTheArchiveHolds(t *testing.T) { + files := map[string][]byte{} + for i := range 12 { + files[fmt.Sprintf("doc%02d.txt", i)] = []byte("small") + } + _, err := ExtractFor(linuxAMD64, "tool.tar.gz", tarGz(t, files), "tool") + if !errors.Is(err, ErrNoBinary) || !strings.Contains(err.Error(), "and 2 more") { + t.Fatalf("ExtractFor = %v", err) + } +} + +func TestCappedReader(t *testing.T) { + // An archive that ends right at the limit is complete. + c := &cappedReader{r: strings.NewReader("abc"), limit: 3, left: 3} + if data, err := io.ReadAll(c); err != nil || string(data) != "abc" { + t.Errorf("ReadAll at the limit = %q, %v", data, err) + } + c = &cappedReader{r: strings.NewReader("abcd"), limit: 3, left: 3} + if _, err := io.ReadAll(c); err == nil { + t.Error("ReadAll beyond the limit succeeded") + } +} + +func TestExtractRefusesABrokenZip(t *testing.T) { + if _, err := Extract("tool.zip", []byte("not a zip archive"), "tool"); err == nil || !strings.Contains(err.Error(), "read zip archive") { + t.Errorf("Extract = %v", err) + } + + // An entry compressed in a way the reader does not know. + var buf bytes.Buffer + zw := zip.NewWriter(&buf) + content := executable(linuxAMD64, "binary") + w, err := zw.CreateRaw(&zip.FileHeader{Name: "tool", Method: 99, CRC32: crc32.ChecksumIEEE(content), + CompressedSize64: uint64(len(content)), UncompressedSize64: uint64(len(content))}) + if err != nil { + t.Fatal(err) + } + if _, err := w.Write(content); err != nil { + t.Fatal(err) + } + if err := zw.Close(); err != nil { + t.Fatal(err) + } + if _, err := ExtractFor(linuxAMD64, "tool.zip", buf.Bytes(), "tool"); err == nil || !strings.Contains(err.Error(), "read zip entry") { + t.Errorf("ExtractFor of an unknown compression = %v", err) + } + + // An entry whose content does not match its checksum. + buf.Reset() + zw = zip.NewWriter(&buf) + w, err = zw.CreateHeader(&zip.FileHeader{Name: "tool", Method: zip.Store}) + if err != nil { + t.Fatal(err) + } + if _, err := w.Write(content); err != nil { + t.Fatal(err) + } + if err := zw.Close(); err != nil { + t.Fatal(err) + } + broken := bytes.Replace(buf.Bytes(), []byte("binary"), []byte("binarz"), 1) + if _, err := ExtractFor(linuxAMD64, "tool.zip", broken, "tool"); !errors.Is(err, zip.ErrChecksum) { + t.Errorf("ExtractFor of a corrupted entry = %v, want zip.ErrChecksum", err) + } +} + +func TestWithinOrigin(t *testing.T) { + r := &requester{origin: "https://gitlab.example.com/api/v4"} + for _, tc := range []struct { + url string + want bool + }{ + {"https://gitlab.example.com:443/api/v4/projects", true}, + {"https://GITLAB.example.com/x", true}, + {"http://gitlab.example.com/x", false}, + {"https://storage.example.com/x", false}, + {"https://gitlab.example.com:8443/x", false}, + {"https://[::1", false}, + } { + if got := r.withinOrigin(tc.url); got != tc.want { + t.Errorf("withinOrigin(%q) = %v, want %v", tc.url, got, tc.want) + } + } + if !(&requester{}).withinOrigin("https://anywhere.example.com") { + t.Error("a requester without an origin refused a URL") + } + if (&requester{origin: "https://[::1"}).withinOrigin("https://example.com") { + t.Error("a malformed origin matched") + } +} + +func TestHostPortOfAnotherScheme(t *testing.T) { + u, err := url.Parse("ftp://example.com/x") + if err != nil { + t.Fatal(err) + } + if got := hostPort(u); got != "example.com:" { + t.Errorf("hostPort = %q", got) + } +} + +func TestRequestErrors(t *testing.T) { + errNoToken := errors.New("no token") + r := &requester{token: func(context.Context, bool) (string, error) { return "", errNoToken }, authHeader: "PRIVATE-TOKEN"} + if _, err := r.get(context.Background(), "https://example.com/x", "", ErrAssetNotFound); !errors.Is(err, errNoToken) { + t.Errorf("get with a failing TokenFunc = %v", err) + } + // A URL no request can be made of, with the default client and with + // the caller's. + for _, client := range []*http.Client{nil, http.DefaultClient} { + r := &requester{client: client} + if _, err := r.get(context.Background(), "https://[::1", "", ErrAssetNotFound); err == nil || !strings.HasPrefix(err.Error(), "selfupdate:") { + t.Errorf("client %v: get = %v", client, err) + } + } +} + +// A TokenFunc that fails when asked again after a rejection ends the +// request with its error. +func TestRetryWithAFailingTokenFunc(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + http.Error(w, "unauthorized", http.StatusUnauthorized) + })) + defer srv.Close() + errGone := errors.New("credential store gone") + g := &GitLab{BaseURL: srv.URL, Project: "example/tool", Token: func(_ context.Context, retry bool) (string, error) { + if retry { + return "", errGone + } + return "tok", nil + }} + _, err := g.Latest(context.Background()) + if !errors.Is(err, errGone) { + t.Fatalf("Latest = %v, want the TokenFunc's error", err) + } +} + +// A server that redirects without end is given up on. +func TestRedirectLoop(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, "/again", http.StatusFound) + })) + defer srv.Close() + g := &GitLab{BaseURL: srv.URL, Project: "example/tool", Token: func(context.Context, bool) (string, error) { return "tok", nil }} + if _, err := g.Latest(context.Background()); err == nil || !strings.Contains(err.Error(), "10 redirects") { + t.Fatalf("Latest = %v, want the redirects bounded", err) + } +} + +func TestSourcesRefuseMalformedAnswers(t *testing.T) { + var answer string + status := http.StatusOK + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(status) + _, _ = io.WriteString(w, answer) + })) + defer srv.Close() + ctx := context.Background() + gh := &GitHub{Owner: "example", Repo: "tool", APIURL: srv.URL} + gl := &GitLab{BaseURL: srv.URL, Project: "example%2Ftool", Package: "tool"} + + answer = "{not json" + if _, err := gh.Latest(ctx); err == nil || !strings.Contains(err.Error(), "decode latest release") { + t.Errorf("GitHub.Latest of bad JSON = %v", err) + } + if _, err := gl.Latest(ctx); err == nil || !strings.Contains(err.Error(), "decode releases") { + t.Errorf("GitLab.Latest of bad JSON = %v", err) + } + answer = `{"tag_name":""}` + if _, err := gh.Latest(ctx); !errors.Is(err, ErrNoRelease) { + t.Errorf("GitHub.Latest without a tag = %v, want ErrNoRelease", err) + } + + status = http.StatusInternalServerError + if _, err := gl.Download(ctx, Release{Tag: "v1.0.0"}, "tool.tar.gz"); err == nil || errors.Is(err, ErrAssetNotFound) { + t.Errorf("GitLab.Download from a failing server = %v, want the failure, not a missing asset", err) + } +} + +func TestGitLabDownloadNeedsItsSettings(t *testing.T) { + ctx := context.Background() + if _, err := (&GitLab{}).Download(ctx, Release{Tag: "v1"}, "x"); err == nil || !strings.Contains(err.Error(), "required") { + t.Errorf("Download without BaseURL = %v", err) + } + g := &GitLab{BaseURL: "https://gitlab.example.com", Project: "example/tool"} + if _, err := g.Download(ctx, Release{Tag: "v1"}, "x"); err == nil || !strings.Contains(err.Error(), "Package is required") { + t.Errorf("Download without Package = %v", err) + } +} + +// A project path that is already escaped is used as it is. +func TestGitLabProjectAlreadyEscaped(t *testing.T) { + for _, tc := range []struct{ project, want string }{ + {"example%2Ftool", "example%2Ftool"}, + {"/example/tool/", "example%2Ftool"}, + {"42", "42"}, + } { + if got := (&GitLab{Project: tc.project}).project(); got != tc.want { + t.Errorf("project(%q) = %q, want %q", tc.project, got, tc.want) + } + } +} + +// A retry that fails to reach the server reports that failure. +func TestRetryThatFailsToConnect(t *testing.T) { + var requests atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + if requests.Add(1) == 1 { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + conn, _, err := http.NewResponseController(w).Hijack() + if err == nil { + _ = conn.Close() + } + })) + defer srv.Close() + g := &GitLab{BaseURL: srv.URL, Project: "example/tool", Token: func(context.Context, bool) (string, error) { return "tok", nil }} + _, err := g.Latest(context.Background()) + // The HTTP client may itself try a GET again on a closed connection. + if err == nil || errors.Is(err, ErrUnauthorized) || requests.Load() < 2 { + t.Fatalf("Latest = %v after %d requests, want the failed retry reported", err, requests.Load()) + } +} diff --git a/selfupdate/doc.go b/selfupdate/doc.go index 54aa6b9..e2e5437 100644 --- a/selfupdate/doc.go +++ b/selfupdate/doc.go @@ -17,14 +17,34 @@ // # What the checksum proves // // The checksum detects a download that was corrupted, or altered on a -// transport or storage hop between the release and the user. It does not -// protect against somebody who can write the release's files: the -// checksums file comes from the same release as the archive and carries no -// signature, so whoever can replace the one can replace the other. An +// transport or storage hop between the release and the user. On its own it +// does not protect against somebody who can write the release's files: the +// checksums file comes from the same release as the archive, so whoever +// can replace the one can replace the other. Without a signature, an // update is as trustworthy as the account, tokens and CI jobs that may -// publish to the release, and the TLS connection to it. A tool that needs -// more verifies a signature of its own before it calls -// [ReplaceExecutable]. +// publish to the release, and the TLS connection to it. +// +// # Signatures +// +// An Updater with a [Verifier] also downloads a signature of the checksums +// file and installs nothing unless it verifies. The key that signs stays +// out of the release, so writing to the release is no longer enough to +// ship a binary. [Minisign] verifies minisign signatures; a tool with +// another scheme implements Verifier. To sign with GoReleaser, create a +// key pair with "minisign -G -W" (no password, for CI), keep the secret +// key in a CI secret, embed the public key in the tool, and sign the +// checksums file: +// +// signs: +// - artifacts: checksum +// cmd: minisign +// args: ["-S", "-s", "{{ .Env.MINISIGN_SECRET_KEY_FILE }}", "-m", "${artifact}", "-x", "${signature}"] +// signature: "${artifact}.minisig" +// +// The checksums file names every archive, so its one signature covers +// them all. Verification proves who signed, not that what they signed is +// harmless: a signed release is as trustworthy as the place the secret key +// is kept. // // What is extracted has to be an executable for the platform (ELF, Mach-O // or PE), so a file that merely has the binary's name or size is never diff --git a/selfupdate/fuzz_test.go b/selfupdate/fuzz_test.go new file mode 100644 index 0000000..0e41fd8 --- /dev/null +++ b/selfupdate/fuzz_test.go @@ -0,0 +1,150 @@ +package selfupdate + +import ( + "archive/tar" + "archive/zip" + "bytes" + "compress/gzip" + "crypto/ed25519" + "crypto/sha256" + "encoding/hex" + "testing" +) + +// Compare is an order: a version equals itself, and swapping the +// arguments flips the result. +func FuzzCompare(f *testing.F) { + for _, seed := range [][2]string{ + {"v1.2.3", "1.2.3"}, {"1.0.0-rc.1", "1.0.0"}, {"v1.2.3-5-gabc1234", "v1.2.3"}, + {"dev", "v0.0.1"}, {"1.0.0-alpha.1", "1.0.0-alpha.beta"}, {"v99999999999999999999.0.0", "v1.0.0"}, + } { + f.Add(seed[0], seed[1]) + } + f.Fuzz(func(t *testing.T, a, b string) { + if got := Compare(a, a); got != 0 { + t.Fatalf("Compare(%q, %q) = %d", a, a, got) + } + if ab, ba := Compare(a, b), Compare(b, a); ab != -ba { + t.Fatalf("Compare(%q, %q) = %d but Compare(%q, %q) = %d", a, b, ab, b, a, ba) + } + }) +} + +// fuzzArchives returns a tar.gz and a zip that each hold an ELF binary +// called tool, as seeds. +func fuzzArchives(f *testing.F) (tgz, zipped []byte) { + f.Helper() + binary := []byte("\x7fELF\x02\x01\x01 binary") + var buf bytes.Buffer + gz := gzip.NewWriter(&buf) + tw := tar.NewWriter(gz) + if err := tw.WriteHeader(&tar.Header{Name: "tool", Size: int64(len(binary)), Mode: 0o755, Typeflag: tar.TypeReg}); err != nil { + f.Fatal(err) + } + if _, err := tw.Write(binary); err != nil { + f.Fatal(err) + } + if err := tw.Close(); err != nil { + f.Fatal(err) + } + if err := gz.Close(); err != nil { + f.Fatal(err) + } + tgz = bytes.Clone(buf.Bytes()) + buf.Reset() + zw := zip.NewWriter(&buf) + w, err := zw.Create("tool.exe") + if err != nil { + f.Fatal(err) + } + if _, err := w.Write([]byte("MZ binary")); err != nil { + f.Fatal(err) + } + if err := zw.Close(); err != nil { + f.Fatal(err) + } + return tgz, buf.Bytes() +} + +// An archive from a release is untrusted until it is verified, and +// ExtractFor reads it anyway when SkipChecksum is set: whatever it holds, +// extracting fails cleanly or returns an executable for the platform. +func FuzzExtract(f *testing.F) { + tgz, zipped := fuzzArchives(f) + f.Add(tgz, false) + f.Add(zipped, true) + f.Fuzz(func(t *testing.T, archive []byte, windows bool) { + p, name := Platform{OS: "linux", Arch: "amd64"}, "tool.tar.gz" + if windows { + p, name = Platform{OS: "windows", Arch: "amd64"}, "tool.zip" + } + binary, err := ExtractFor(p, name, archive, "tool") + if err != nil { + return + } + magic := "\x7fELF" + if windows { + magic = "MZ" + } + if !bytes.HasPrefix(binary, []byte(magic)) { + t.Fatalf("ExtractFor returned %q, which is no %s executable", binary, p.OS) + } + }) +} + +// A signature that was not made with the trusted key never verifies, and +// nothing in a signature file makes Verify panic. +func FuzzMinisignVerify(f *testing.F) { + seed := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{7}, ed25519.SeedSize)) + signer := &minisigner{id: [8]byte{1, 2, 3, 4, 5, 6, 7, 8}, priv: seed, pub: seed.Public().(ed25519.PublicKey)} + message := []byte("abc tool.tar.gz\n") + m, err := NewMinisign(signer.publicKey()) + if err != nil { + f.Fatal(err) + } + good := signer.sign(message, false) + f.Add(message, good) + f.Add(message, signer.sign(message, true)) + f.Add([]byte("other"), good) + f.Fuzz(func(t *testing.T, msg, signature []byte) { + if m.Verify(msg, signature) != nil { + return + } + // Ed25519 signatures are deterministic, and Verify accepts only + // the canonical one, so an accepted signature is the one the key + // makes for msg, with whatever comments around it. + sig, err := parseMinisignSignature(signature) + if err != nil { + t.Fatalf("Verify accepted %q, which does not parse: %v", signature, err) + } + want, err := parseMinisignSignature(signer.sign(msg, !sig.prehashed)) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(sig.signature, want.signature) { + t.Fatalf("Verify accepted %q for %q, not the key's signature", signature, msg) + } + }) +} + +// A checksums file from elsewhere never makes VerifyChecksum panic, and it +// accepts only data whose SHA-256 the file names. +func FuzzVerifyChecksum(f *testing.F) { + data := []byte("archive") + f.Add([]byte("ee5c1aaa0e0bd2c0f2b6ec6ee5fd4e2d5d0b8e6f4b1a6c8d2e9f0a1b2c3d4e5f tool.tar.gz\n"), data) + f.Add(checksumsFor(map[string][]byte{"tool.tar.gz": data}), data) + f.Add([]byte("zz tool.tar.gz\n*"), []byte{}) + f.Fuzz(func(t *testing.T, checksums, data []byte) { + if VerifyChecksum(checksums, "tool.tar.gz", data) != nil { + return + } + if !bytes.Contains(bytes.ToLower(checksums), []byte(sha256Hex(data))) { + t.Fatalf("VerifyChecksum accepted %q for data whose SHA-256 it does not hold", checksums) + } + }) +} + +func sha256Hex(data []byte) string { + sum := sha256.Sum256(data) + return hex.EncodeToString(sum[:]) +} diff --git a/selfupdate/replace.go b/selfupdate/replace.go index ca6d7ac..aea6add 100644 --- a/selfupdate/replace.go +++ b/selfupdate/replace.go @@ -113,6 +113,11 @@ func ReplaceExecutable(path string, binary []byte) error { dir := filepath.Dir(path) mode := fs.FileMode(0o755) if info, err := os.Stat(path); err == nil { + // Only a file is replaced. On Windows the old one is moved aside + // first, which would carry off a directory as well. + if !info.Mode().IsRegular() { + return fmt.Errorf("selfupdate: replace %s: not a regular file", path) + } mode = info.Mode().Perm() | 0o100 } // The replacement must be on the same file system as path, so the diff --git a/selfupdate/signature.go b/selfupdate/signature.go new file mode 100644 index 0000000..c29a963 --- /dev/null +++ b/selfupdate/signature.go @@ -0,0 +1,187 @@ +package selfupdate + +import ( + "crypto/ed25519" + "encoding/base64" + "errors" + "fmt" + "slices" + "strings" + + "golang.org/x/crypto/blake2b" +) + +// ErrSignature reports that the checksums file of a release carries no +// valid signature by a trusted key: the signature is malformed, was made +// with another key, or does not match the file. +var ErrSignature = errors.New("selfupdate: bad signature") + +// maxSignatureSize bounds the signature file download. +const maxSignatureSize = 64 << 10 + +// Verifier checks the signature of a release's checksums file. Set one as +// Updater.Verifier to install only what a trusted key signed; see +// [Minisign]. +type Verifier interface { + // SignatureName names the signature file of the checksums file called + // checksums, as it is published beside it in the release. + SignatureName(checksums string) string + // Verify returns nil when signature is a valid signature of message + // by a trusted key, and an error wrapping [ErrSignature] otherwise. + Verify(message, signature []byte) error +} + +// Minisign verifies signatures made with minisign +// (https://jedisct1.github.io/minisign/) or a tool compatible with it, +// such as rsign2 or the minisign packages for Go. It accepts the +// pre-hashed signatures minisign makes by default (algorithm "ED") and the +// legacy ones (algorithm "Ed"), and requires a valid trusted comment +// signature, as minisign does. +// +// The zero value trusts no key. Use [NewMinisign]. +type Minisign struct { + keys []minisignKey +} + +type minisignKey struct { + id [8]byte + key ed25519.PublicKey +} + +// NewMinisign returns a Minisign that trusts each of publicKeys. A key is +// the Base64 line minisign prints ("RWQ…") or the whole public key file, +// its untrusted comment line included. More than one key lets a release +// signed with a new key verify while the old one is being retired. +func NewMinisign(publicKeys ...string) (*Minisign, error) { + if len(publicKeys) == 0 { + return nil, errors.New("selfupdate: no minisign public key given") + } + m := &Minisign{} + for _, text := range publicKeys { + key, err := parseMinisignKey(text) + if err != nil { + return nil, err + } + m.keys = append(m.keys, key) + } + return m, nil +} + +// parseMinisignKey reads a public key: an algorithm ("Ed"), an 8-byte key +// ID and a 32-byte Ed25519 key, Base64-encoded, alone or below the +// untrusted comment of a minisign public key file. +func parseMinisignKey(text string) (minisignKey, error) { + line := "" + for l := range strings.Lines(text) { + l = strings.TrimSpace(l) + if l == "" || strings.HasPrefix(l, "untrusted comment:") { + continue + } + if line != "" { + return minisignKey{}, errors.New("selfupdate: minisign public key has more than one key line") + } + line = l + } + raw, err := base64.StdEncoding.DecodeString(line) + if err != nil || len(raw) != 2+8+ed25519.PublicKeySize || string(raw[:2]) != "Ed" { + return minisignKey{}, errors.New("selfupdate: malformed minisign public key") + } + var key minisignKey + copy(key.id[:], raw[2:10]) + key.key = ed25519.PublicKey(slices.Clone(raw[10:])) + return key, nil +} + +// SignatureName returns checksums with ".minisig" appended, the name +// minisign gives a signature by default. +func (m *Minisign) SignatureName(checksums string) string { + return checksums + ".minisig" +} + +// Verify checks signature, the contents of a minisign signature file, +// against message. The signature has to be made by one of the trusted +// keys, and its trusted comment has to be signed by the same key. +func (m *Minisign) Verify(message, signature []byte) error { + sig, err := parseMinisignSignature(signature) + if err != nil { + return err + } + i := slices.IndexFunc(m.keys, func(k minisignKey) bool { return k.id == sig.keyID }) + if i < 0 { + return fmt.Errorf("%w: made with key %s, which is not trusted", ErrSignature, keyIDString(sig.keyID)) + } + key := m.keys[i].key + signed := message + if sig.prehashed { + sum := blake2b.Sum512(message) + signed = sum[:] + } + if !ed25519.Verify(key, signed, sig.signature) { + return fmt.Errorf("%w: the signature does not match the file", ErrSignature) + } + global := append(slices.Clone(sig.signature), sig.trustedComment...) + if !ed25519.Verify(key, global, sig.globalSignature) { + return fmt.Errorf("%w: the trusted comment is not signed", ErrSignature) + } + return nil +} + +type minisignSignature struct { + prehashed bool + keyID [8]byte + signature []byte + trustedComment []byte + globalSignature []byte +} + +// parseMinisignSignature reads the four lines of a signature file: an +// untrusted comment, the signature (algorithm, key ID, Ed25519 +// signature), the trusted comment, and the signature of the signature and +// the trusted comment together. +func parseMinisignSignature(data []byte) (minisignSignature, error) { + malformed := func(what string) (minisignSignature, error) { + return minisignSignature{}, fmt.Errorf("%w: malformed minisign signature: %s", ErrSignature, what) + } + lines := strings.Split(strings.TrimRight(string(data), "\r\n"), "\n") + for i := range lines { + lines[i] = strings.TrimSuffix(lines[i], "\r") + } + if len(lines) != 4 { + return malformed("want 4 lines") + } + if !strings.HasPrefix(lines[0], "untrusted comment:") { + return malformed("no untrusted comment") + } + raw, err := base64.StdEncoding.DecodeString(lines[1]) + if err != nil || len(raw) != 2+8+ed25519.SignatureSize { + return malformed("bad signature line") + } + var sig minisignSignature + switch string(raw[:2]) { + case "ED": + sig.prehashed = true + case "Ed": + default: + return malformed("unknown algorithm") + } + copy(sig.keyID[:], raw[2:10]) + sig.signature = raw[10:] + comment, ok := strings.CutPrefix(lines[2], "trusted comment: ") + if !ok { + return malformed("no trusted comment") + } + sig.trustedComment = []byte(comment) + sig.globalSignature, err = base64.StdEncoding.DecodeString(lines[3]) + if err != nil || len(sig.globalSignature) != ed25519.SignatureSize { + return malformed("bad trusted comment signature") + } + return sig, nil +} + +// keyIDString formats a key ID the way minisign prints it: as the +// hexadecimal number its little-endian bytes make. +func keyIDString(id [8]byte) string { + reversed := id + slices.Reverse(reversed[:]) + return fmt.Sprintf("%X", reversed[:]) +} diff --git a/selfupdate/signature_test.go b/selfupdate/signature_test.go new file mode 100644 index 0000000..d87bce0 --- /dev/null +++ b/selfupdate/signature_test.go @@ -0,0 +1,241 @@ +package selfupdate + +import ( + "context" + "crypto/ed25519" + "encoding/base64" + "errors" + "os" + "path/filepath" + "strings" + "testing" + + "golang.org/x/crypto/blake2b" +) + +// minisigner signs the way minisign does, for tests. +type minisigner struct { + id [8]byte + priv ed25519.PrivateKey + pub ed25519.PublicKey +} + +func newMinisigner(t *testing.T, id byte) *minisigner { + t.Helper() + pub, priv, err := ed25519.GenerateKey(nil) + if err != nil { + t.Fatal(err) + } + return &minisigner{id: [8]byte{id, 2, 3, 4, 5, 6, 7, 8}, priv: priv, pub: pub} +} + +// publicKey returns the public key file minisign writes. +func (s *minisigner) publicKey() string { + raw := append(append([]byte("Ed"), s.id[:]...), s.pub...) + return "untrusted comment: minisign public key\n" + base64.StdEncoding.EncodeToString(raw) + "\n" +} + +// sign returns the signature file of message, pre-hashed unless legacy. +func (s *minisigner) sign(message []byte, legacy bool) []byte { + alg, signed := "ED", message + if legacy { + alg = "Ed" + } else { + sum := blake2b.Sum512(message) + signed = sum[:] + } + sig := ed25519.Sign(s.priv, signed) + const comment = "timestamp:1700000000\tfile:checksums.txt\thashed" + global := ed25519.Sign(s.priv, append(append([]byte{}, sig...), comment...)) + line := append(append([]byte(alg), s.id[:]...), sig...) + return []byte("untrusted comment: signature from minisign secret key\n" + + base64.StdEncoding.EncodeToString(line) + "\n" + + "trusted comment: " + comment + "\n" + + base64.StdEncoding.EncodeToString(global) + "\n") +} + +func TestMinisignVerifies(t *testing.T) { + signer := newMinisigner(t, 1) + message := []byte("abc tool.tar.gz\n") + for _, legacy := range []bool{false, true} { + m, err := NewMinisign(signer.publicKey()) + if err != nil { + t.Fatal(err) + } + if err := m.Verify(message, signer.sign(message, legacy)); err != nil { + t.Errorf("legacy=%v: Verify = %v", legacy, err) + } + } + // The Base64 line alone is a key too, and CRLF line ends are read. + line := strings.Split(signer.publicKey(), "\n")[1] + m, err := NewMinisign(line) + if err != nil { + t.Fatal(err) + } + crlf := strings.ReplaceAll(string(signer.sign(message, false)), "\n", "\r\n") + if err := m.Verify(message, []byte(crlf)); err != nil { + t.Errorf("Verify with CRLF = %v", err) + } +} + +func TestMinisignRejects(t *testing.T) { + signer := newMinisigner(t, 1) + other := newMinisigner(t, 2) + impostor := newMinisigner(t, 1) // the trusted key's ID, another key + message := []byte("abc tool.tar.gz\n") + m, err := NewMinisign(signer.publicKey()) + if err != nil { + t.Fatal(err) + } + good := string(signer.sign(message, false)) + lines := strings.Split(good, "\n") + for _, tc := range []struct { + name string + message string + signature string + want string + }{ + {"changed file", "abd tool.tar.gz\n", good, "does not match"}, + {"untrusted key", string(message), string(other.sign(message, false)), "0807060504030202, which is not trusted"}, + {"same key ID, other key", string(message), string(impostor.sign(message, false)), "does not match"}, + {"changed trusted comment", string(message), strings.Replace(good, "hashed", "hushed", 1), "trusted comment is not signed"}, + {"empty", string(message), "", "want 4 lines"}, + {"no untrusted comment", string(message), strings.Replace(good, "untrusted comment:", "x:", 1), "no untrusted comment"}, + {"no trusted comment", string(message), strings.Replace(good, "trusted comment: t", "comment: t", 1), "no trusted comment"}, + {"bad signature line", string(message), strings.Replace(good, lines[1], "!!", 1), "bad signature line"}, + {"bad global signature", string(message), strings.Replace(good, lines[3], "AAAA", 1), "bad trusted comment signature"}, + {"unknown algorithm", string(message), strings.Replace(good, lines[1], base64.StdEncoding.EncodeToString(append([]byte("XX"), make([]byte, 72)...)), 1), "unknown algorithm"}, + } { + err := m.Verify([]byte(tc.message), []byte(tc.signature)) + if !errors.Is(err, ErrSignature) || !strings.Contains(err.Error(), tc.want) { + t.Errorf("%s: Verify = %v, want ErrSignature with %q", tc.name, err, tc.want) + } + } + if err := (&Minisign{}).Verify(message, []byte(good)); !errors.Is(err, ErrSignature) { + t.Errorf("zero Minisign: Verify = %v, want ErrSignature", err) + } +} + +func TestMinisignTrustsEveryKeyGiven(t *testing.T) { + old, current := newMinisigner(t, 1), newMinisigner(t, 2) + m, err := NewMinisign(old.publicKey(), current.publicKey()) + if err != nil { + t.Fatal(err) + } + message := []byte("abc tool.tar.gz\n") + for _, s := range []*minisigner{old, current} { + if err := m.Verify(message, s.sign(message, false)); err != nil { + t.Errorf("key %x: Verify = %v", s.id, err) + } + } +} + +func TestNewMinisignRejectsBadKeys(t *testing.T) { + signer := newMinisigner(t, 1) + line := strings.Split(signer.publicKey(), "\n")[1] + for _, key := range []string{ + "", + "untrusted comment: nothing else\n", + "not base64!", + base64.StdEncoding.EncodeToString([]byte("Ed short")), + strings.Replace(line, line[:2], "RX", 1), // another algorithm + line + "\n" + line, + } { + if _, err := NewMinisign(key); err == nil { + t.Errorf("NewMinisign(%q) accepted a bad key", key) + } + } + if _, err := NewMinisign(); err == nil { + t.Error("NewMinisign() accepted no key") + } + if got := (&Minisign{}).SignatureName("checksums.txt"); got != "checksums.txt.minisig" { + t.Errorf("SignatureName = %q", got) + } +} + +func signedFixture(t *testing.T) (*Updater, *memorySource, string, *minisigner) { + t.Helper() + u, source, exe := newFixture(t) + signer := newMinisigner(t, 1) + source.files["checksums.txt.minisig"] = signer.sign(source.files["checksums.txt"], false) + verifier, err := NewMinisign(signer.publicKey()) + if err != nil { + t.Fatal(err) + } + u.Verifier = verifier + return u, source, exe, signer +} + +func TestUpdateVerifiesTheSignature(t *testing.T) { + u, _, exe, _ := signedFixture(t) + if result, err := u.Update(context.Background(), false); err != nil || !result.Updated { + t.Fatalf("Update = %+v, %v", result, err) + } + if got := contents(t, exe); got != newBinary { + t.Fatalf("executable holds %q", got) + } +} + +func TestUpdateRefusesAnUnsignedOrForgedRelease(t *testing.T) { + // Somebody who can write the release replaces archive and checksums + // file together; the signature they cannot make gives them away. + u, source, exe, _ := signedFixture(t) + archive := tarGz(t, map[string][]byte{"tool": []byte("\x7fELF evil")}) + source.files["tool_Linux_x86_64.tar.gz"] = archive + source.files["checksums.txt"] = checksumsFor(map[string][]byte{"tool_Linux_x86_64.tar.gz": archive}) + if _, err := u.Update(context.Background(), false); !errors.Is(err, ErrSignature) { + t.Fatalf("Update of a forged release = %v, want ErrSignature", err) + } + // Signed with their own key. + source.files["checksums.txt.minisig"] = newMinisigner(t, 9).sign(source.files["checksums.txt"], false) + if _, err := u.Update(context.Background(), false); !errors.Is(err, ErrSignature) { + t.Fatalf("Update signed by another key = %v, want ErrSignature", err) + } + // No signature at all. + delete(source.files, "checksums.txt.minisig") + if _, err := u.Update(context.Background(), false); !errors.Is(err, ErrAssetNotFound) || !strings.Contains(err.Error(), "fetch signature") { + t.Fatalf("Update without a signature = %v, want the missing signature reported", err) + } + if got := contents(t, exe); got != "old binary" { + t.Fatalf("executable replaced: %q", got) + } +} + +func TestVerifierExcludesSkipChecksum(t *testing.T) { + u, source, _, _ := signedFixture(t) + u.SkipChecksum = true + if _, err := u.Update(context.Background(), false); err == nil || !strings.Contains(err.Error(), "SkipChecksum") { + t.Fatalf("Update = %v, want Verifier and SkipChecksum refused", err) + } + if source.calls != 0 { + t.Fatal("asked the source before refusing the configuration") + } +} + +// TestMinisignVerifiesAnotherImplementation checks the verifier against a +// key and signature made by aead.dev/minisign, an implementation written +// apart from this one, so a misreading of the format shared by the test +// signer above and the verifier cannot pass unnoticed. +func TestMinisignVerifiesAnotherImplementation(t *testing.T) { + read := func(name string) []byte { + t.Helper() + data, err := os.ReadFile(filepath.Join("testdata", "minisign", name)) + if err != nil { + t.Fatal(err) + } + return data + } + m, err := NewMinisign(string(read("minisign.pub"))) + if err != nil { + t.Fatal(err) + } + message, signature := read("checksums.txt"), read("checksums.txt.minisig") + if err := m.Verify(message, signature); err != nil { + t.Fatalf("Verify = %v", err) + } + changed := append([]byte{}, message...) + changed[0] ^= 1 + if err := m.Verify(changed, signature); !errors.Is(err, ErrSignature) { + t.Errorf("Verify of a changed file = %v, want ErrSignature", err) + } +} diff --git a/selfupdate/testdata/minisign/checksums.txt b/selfupdate/testdata/minisign/checksums.txt new file mode 100644 index 0000000..d224fcf --- /dev/null +++ b/selfupdate/testdata/minisign/checksums.txt @@ -0,0 +1 @@ +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 tool_1.2.3_linux_amd64.tar.gz diff --git a/selfupdate/testdata/minisign/checksums.txt.minisig b/selfupdate/testdata/minisign/checksums.txt.minisig new file mode 100644 index 0000000..ac6b549 --- /dev/null +++ b/selfupdate/testdata/minisign/checksums.txt.minisig @@ -0,0 +1,4 @@ +untrusted comment: signature from minisign secret key +RWSc1gigrhV6LTfFxnbQCaUcVLC0X6wrUB9iFg1vwWI3OV+TM3fjzVQSYbBNJ+uoXWsKNIJ9AE1Ip6Z+93rnfiL5d+HQ6zH72QU= +trusted comment: timestamp:1763380000 file:checksums.txt hashed +I/Z7IIFiMZCWbgHl/T6HbhauyHFnb9fGrIWBKb0qzcDEuAIKRcUY2+Lab4j/mQ42ROqYilXmH903D8fVUfd2Cg== diff --git a/selfupdate/testdata/minisign/minisign.pub b/selfupdate/testdata/minisign/minisign.pub new file mode 100644 index 0000000..d08b707 --- /dev/null +++ b/selfupdate/testdata/minisign/minisign.pub @@ -0,0 +1,2 @@ +untrusted comment: minisign public key: 2D7A15AEA008D69C +RWSc1gigrhV6LVkSlU/B0Q0EqEJ1PnJCiK5dxpyyK7sHKknsWBrjuVFz diff --git a/selfupdate/update.go b/selfupdate/update.go index b66c4af..dce429f 100644 --- a/selfupdate/update.go +++ b/selfupdate/update.go @@ -52,8 +52,14 @@ type Updater struct { // SkipChecksum installs the archive without verifying it, for a source // that publishes no checksums file. What is lost is the detection of a // download that was corrupted or altered on its way; the checksum never - // proved more than that (see [VerifyChecksum]). + // proved more than that (see [VerifyChecksum]). It cannot be combined + // with Verifier. SkipChecksum bool + // Verifier, when set, requires the checksums file to carry a valid + // signature by a trusted key, published beside it under the name + // Verifier.SignatureName gives. The archive is then installed only when + // it matches a checksums file the key holder signed; see [Minisign]. + Verifier Verifier // Binary is the file name of the binary inside the archive, without // ".exe"; empty means the running executable's own name. When no file // has that name, the largest file is taken. Either way the file has to @@ -135,6 +141,7 @@ func (u *Updater) Update(ctx context.Context, force bool) (Result, error) { // manager owns, and fails early when the executable's directory is not // writable. The archive is verified against the release's checksums file // unless SkipChecksum is set; see [VerifyChecksum] for what that proves. +// With a Verifier, the checksums file has to carry a valid signature too. func (u *Updater) Install(ctx context.Context, rel Release) (Result, error) { result, err := u.prepare() if err != nil { @@ -162,6 +169,9 @@ func (u *Updater) prepare() (Result, error) { if u.Source == nil { return Result{}, errors.New("selfupdate: Updater.Source is required") } + if u.Verifier != nil && u.SkipChecksum { + return Result{}, errors.New("selfupdate: Updater.Verifier needs the checksums file that SkipChecksum skips") + } path, err := u.executable() if err != nil { return Result{}, err @@ -197,6 +207,16 @@ func (u *Updater) install(ctx context.Context, result Result) (Result, error) { if err != nil { return result, fmt.Errorf("selfupdate: fetch checksums to verify %s: %w", plain(name), err) } + if u.Verifier != nil { + signatureName := u.Verifier.SignatureName(checksumsName) + signature, err := u.download(ctx, rel, signatureName, maxSignatureSize) + if err != nil { + return result, fmt.Errorf("selfupdate: fetch signature to verify %s: %w", plain(checksumsName), err) + } + if err := u.Verifier.Verify(checksums, signature); err != nil { + return result, fmt.Errorf("%s: %w", plain(checksumsName), err) + } + } if err := VerifyChecksum(checksums, name, archive); err != nil { return result, err } diff --git a/term/fuzz_test.go b/term/fuzz_test.go new file mode 100644 index 0000000..5f2ef62 --- /dev/null +++ b/term/fuzz_test.go @@ -0,0 +1,47 @@ +package term + +import ( + "strings" + "testing" + "unicode/utf8" +) + +// Truncate and TruncateMiddle never leave a line wider than asked for. +func FuzzTruncate(f *testing.F) { + for _, seed := range []string{"feature/very-long-branch-name", "\x1b[31m日本語のテキスト\x1b[0m", "a\tb\tc", "e\u0301e\u0301e\u0301", "line one\nline two is longer", "\x1b]8;;https://x\x1b\\link\x1b]8;;\x1b\\"} { + f.Add(seed, 5) + } + f.Fuzz(func(t *testing.T, s string, width int) { + if width < 1 || width > 200 { + return + } + s = Sanitize(s) // the functions measure text a terminal may be shown + for name, cut := range map[string]func(string, int) string{"Truncate": Truncate, "TruncateMiddle": TruncateMiddle} { + got := cut(s, width) + for line := range strings.SplitSeq(got, "\n") { + if w := VisibleWidth(line); w > max(width, cells(Ellipsis)) { + t.Fatalf("%s(%q, %d) = %q, a line %d cells wide", name, s, width, got, w) + } + } + } + }) +} + +// PlainLine leaves one line of text: no escape sequence, no control, no +// line break, no bidirectional control and no white space at either end. +func FuzzPlainLine(f *testing.F) { + for _, seed := range []string{"invoice\u202efdp.exe", "a\r\nb\u2028c", "\x1b[31mred\x1b]0;t\x07", " \u00a0x\t", "\u009b2J"} { + f.Add(seed) + } + f.Fuzz(func(t *testing.T, s string) { + got := PlainLine(s) + if !utf8.ValidString(got) || strings.TrimSpace(got) != got { + t.Fatalf("PlainLine(%q) = %q", s, got) + } + for _, r := range got { + if control(r) || lineBreak(r) || bidiControl(r) || r == '\t' { + t.Fatalf("PlainLine(%q) = %q keeps %U", s, got, r) + } + } + }) +} diff --git a/theme/doc.go b/theme/doc.go index 5f6d2cb..2b94280 100644 --- a/theme/doc.go +++ b/theme/doc.go @@ -21,5 +21,6 @@ // // [Hashed] gives a name a style of its own that stays the same across rows // and runs, such as a color per author, picked from [NamePalette] or a -// palette of the caller's. +// palette of the caller's. [Theme.Hashed] does the same for output painted +// with a theme, and stays plain where the theme is [Plain]. package theme diff --git a/theme/fuzz_test.go b/theme/fuzz_test.go new file mode 100644 index 0000000..ef2633f --- /dev/null +++ b/theme/fuzz_test.go @@ -0,0 +1,30 @@ +package theme + +import ( + "testing" + + "github.com/mittwald/cli-kit/term" +) + +// A style a user wrote, whatever it says, only ever colors text: painting +// with it adds escape sequences and nothing else, so taking them out gives +// the text back. +func FuzzParseStyle(f *testing.F) { + for _, seed := range []string{"245", "160:bold", "fg=white:bg=#aa0000:underline", "0x1f2", "bg=300", "::", "red:;31m"} { + f.Add(seed) + } + f.Fuzz(func(t *testing.T, spec string) { + style, ok := ParseStyle(spec) + if !ok { + return + } + const text = "text" + painted := style.Paint(text) + if got := term.StripANSI(painted); got != text { + t.Fatalf("ParseStyle(%q) = %q paints %q, which shows as %q", spec, style, painted, got) + } + if term.Sanitize(painted) == "" { + t.Fatalf("ParseStyle(%q) = %q paints nothing visible", spec, style) + } + }) +} diff --git a/theme/hash.go b/theme/hash.go index a101399..660fdd5 100644 --- a/theme/hash.go +++ b/theme/hash.go @@ -43,3 +43,19 @@ func Hashed(name string, palette []Style) Style { _, _ = digest.Write([]byte(folded)) return palette[uint64(digest.Sum32())%uint64(len(palette))] } + +// Hashed is [Hashed] for output painted with t: the zero Style where t is +// [Plain], such as what [Theme.For] returns for a pipe or a file, so a name +// colored this way stays plain wherever the rest of t does: +// +// th := theme.Active().For(os.Stdout) +// fmt.Println(th.Hashed(author).Paint(author), th.Muted.Paint(date)) +// +// An empty palette means [NamePalette]. The package-level Hashed paints +// wherever its result is used; call [Style.For] on it, or use this method. +func (t Theme) Hashed(name string, palette ...Style) Style { + if t == Plain { + return "" + } + return Hashed(name, palette) +} diff --git a/theme/hash_test.go b/theme/hash_test.go index 89bb656..f4c349e 100644 --- a/theme/hash_test.go +++ b/theme/hash_test.go @@ -1,6 +1,7 @@ package theme import ( + "bytes" "slices" "testing" ) @@ -48,3 +49,22 @@ func TestHashedOwnPalette(t *testing.T) { t.Errorf("Hashed with a palette of one = %q, want it", got) } } + +// A theme's Hashed paints nothing where the theme paints nothing, and +// otherwise picks what the package-level Hashed picks. +func TestThemeHashed(t *testing.T) { + if got := Plain.Hashed("alice"); got != "" { + t.Errorf("Plain.Hashed = %q, want the zero Style", got) + } + var out bytes.Buffer + if got := Default.For(&out).Hashed("alice"); got != "" { + t.Errorf("Default.For(buffer).Hashed = %q, want the zero Style", got) + } + if got, want := Default.Hashed("alice"), Hashed("alice", nil); got != want || got == "" { + t.Errorf("Default.Hashed = %q, want %q", got, want) + } + palette := []Style{Bold} + if got := Default.Hashed("alice", palette...); got != Bold { + t.Errorf("Default.Hashed with a palette = %q, want %q", got, Bold) + } +}