fix: stop cleanly on Ctrl-C, SIGTERM, and SIGHUP (#668)

A signal killed the process mid-run and left the snapshot's copies of browser files in the temp dir.
The run now stops at its next step, removes them, and ends by the same signal, so the exit status and
calling scripts see what they did before. RFC-012 also keeps the list goldens in cmd.
This commit is contained in:
Roger authored and GitHub committed 2026-10-29 15:12:30 +08:00
1 parent a794674bd7
commit c0a03769f1
18 files changed
+288 -15

No files matched your search

+3 -1
View File
@@ -56,6 +56,8 @@ func runDump(ctx context.Context, f app.Flags) error {
return nil
}
summary, err := app.Execute(ctx, app.NewPlan(d, req), req)
report(summary)
if ctx.Err() == nil {
report(summary)
}
return err
}
+4 -1
View File
@@ -27,7 +27,10 @@ func dumpKeysCmd() *cobra.Command {
if err != nil {
return err
}
dump := app.DumpKeys(cmd.Context(), app.Discover(req), req)
dump, err := app.DumpKeys(cmd.Context(), app.Discover(req), req)
if err != nil {
return err
}
log.Infof("Exported keys for %d vault(s)", len(dump.Vaults))
if outputPath == "" {
+53 -1
View File
@@ -1,7 +1,11 @@
package main
import (
"context"
"errors"
"os"
"os/signal"
"syscall"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
@@ -46,12 +50,60 @@ GitHub: https://github.com/moonD4rk/HackBrowserData`,
}
})
for _, c := range root.Commands() {
quietWhenStopped(c)
}
quietWhenStopped(root)
return root
}
// quietWhenStopped keeps a stopped run's error and usage off the screen; main then ends the process by the signal.
func quietWhenStopped(c *cobra.Command) {
run := c.RunE
if run == nil {
return
}
c.RunE = func(cmd *cobra.Command, args []string) error {
err := run(cmd, args)
if err != nil && cmd.Context().Err() != nil {
cmd.SilenceErrors, cmd.SilenceUsage = true, true
}
return err
}
}
// stopSignals end the process by default; each first cancels the run, so its temporary copies are removed.
var stopSignals = []os.Signal{os.Interrupt, syscall.SIGTERM, syscall.SIGHUP}
type stopError struct{ sig os.Signal }
func (e stopError) Error() string { return "stopped by " + e.sig.String() }
func main() {
configureDoubleClickMode()
if err := rootCmd().Execute(); err != nil {
ctx, cancel := context.WithCancelCause(context.Background())
signals := make(chan os.Signal, 1)
for _, sig := range stopSignals {
if !signal.Ignored(sig) { // nohup and background jobs keep ignoring what they ignore today
signal.Notify(signals, sig)
}
}
go func() {
sig := <-signals
signal.Stop(signals) // a second signal ends the process at once
if sig == os.Interrupt {
log.Warnf("Interrupted; cleaning up (press Ctrl-C again to quit at once)")
} else {
log.Warnf("Stopping; cleaning up")
}
cancel(stopError{sig})
}()
err := rootCmd().ExecuteContext(ctx)
var stop stopError
if errors.As(context.Cause(ctx), &stop) {
exitBy(stop.sig)
}
if err != nil {
os.Exit(1)
}
}
+16
View File
@@ -2,4 +2,20 @@
package main
import (
"os"
"os/signal"
"syscall"
"time"
)
func configureDoubleClickMode() {}
// exitBy ends the process by sig itself, as the signal would have, so a calling shell or script sees it was stopped.
func exitBy(sig os.Signal) {
signal.Reset(sig)
if s, ok := sig.(syscall.Signal); ok && syscall.Kill(syscall.Getpid(), s) == nil {
time.Sleep(time.Second) // the signal ends the process first unless it was ignored at start
}
os.Exit(1)
}
+20
View File
@@ -0,0 +1,20 @@
//go:build !windows
package main
import (
"os"
"syscall"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func assertEndedByInterrupt(t *testing.T, ps *os.ProcessState) {
t.Helper()
status, ok := ps.Sys().(syscall.WaitStatus)
require.True(t, ok)
assert.True(t, status.Signaled(), "ended by the signal, not by an exit code")
assert.Equal(t, syscall.SIGINT, status.Signal())
}
+62
View File
@@ -0,0 +1,62 @@
package main
import (
"bytes"
"context"
"os"
"os/exec"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestStoppedRunPrintsNoErrorOrUsage(t *testing.T) {
home := t.TempDir()
setHome(t, home)
chromiumFixtureUserData(t, userDataDirOf(t, home, "chrome"), "chrome")
for _, tc := range []struct {
name, browser string
stop bool
}{
{name: "stopped", browser: "chrome", stop: true},
{name: "failed", browser: "nosuch"},
} {
tc := tc
t.Run(tc.name, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if tc.stop {
cancel()
}
var screen bytes.Buffer
root := rootCmd()
root.SetOut(&screen)
root.SetErr(&screen)
root.SetArgs([]string{"-b", tc.browser, "-d", filepath.Join(t.TempDir(), "results")})
err := root.ExecuteContext(ctx)
require.Error(t, err)
if tc.stop {
require.ErrorIs(t, err, context.Canceled)
assert.Empty(t, screen.String())
} else {
assert.Contains(t, screen.String(), "Error: ")
}
})
}
}
func TestExitByEndsTheProcessAsTheSignalWould(t *testing.T) {
if os.Getenv("HBD_TEST_EXIT_BY") == "1" {
exitBy(os.Interrupt)
return
}
cmd := exec.Command(os.Args[0], "-test.run=^TestExitByEndsTheProcessAsTheSignalWould$")
cmd.Env = append(os.Environ(), "HBD_TEST_EXIT_BY=1")
var exitErr *exec.ExitError
require.ErrorAs(t, cmd.Run(), &exitErr)
assertEndedByInterrupt(t, exitErr.ProcessState)
}
+9
View File
@@ -3,8 +3,11 @@
package main
import (
"os"
"github.com/inconshreveable/mousetrap"
"github.com/spf13/cobra"
"golang.org/x/sys/windows"
"github.com/moond4rk/hackbrowserdata/internal/winapi"
)
@@ -19,3 +22,9 @@ func configureDoubleClickMode() {
cobra.MousetrapHelpText = ""
winapi.HideConsoleWindow()
}
// exitBy ends the process with the status Windows gives a console process that Ctrl-C or closing the console ends.
func exitBy(os.Signal) {
status := uint32(windows.STATUS_CONTROL_C_EXIT)
os.Exit(int(int32(status)))
}
@@ -0,0 +1,16 @@
//go:build windows
package main
import (
"os"
"testing"
"github.com/stretchr/testify/assert"
"golang.org/x/sys/windows"
)
func assertEndedByInterrupt(t *testing.T, ps *os.ProcessState) {
t.Helper()
assert.Equal(t, uint32(windows.STATUS_CONTROL_C_EXIT), uint32(ps.ExitCode()))
}
+3 -1
View File
@@ -62,7 +62,9 @@ func runRestore(ctx context.Context, f app.RestoreFlags) error {
}
req.Keys = keys
summary, err := app.Execute(ctx, app.NewPlan(d, req), req)
report(summary)
if ctx.Err() == nil {
report(summary)
}
return err
}