diff --git a/SPEC.md b/SPEC.md index 08fc2b6..d0c4620 100644 --- a/SPEC.md +++ b/SPEC.md @@ -69,7 +69,8 @@ never as a time. that command's settings, and runs `internal/rproxy` until `SIGTERM` or `SIGINT` (see "`rproxy`"). `sww healthcheck` is the image's health check. With no command, or one it does not know, the binary prints the commands - and exits with status 2. `internal/sww` is the only package that imports + and exits with status 2. `sww help` and `sww --help` print them and exit + with status 0. `internal/sww` is the only package that imports `go.uber.org/fx`. fx builds the parts of `waf` and `rproxy`, and starts and stops their background work. - `internal/config`: reads the settings, the one place they are read. @@ -126,6 +127,7 @@ never as a time. - `github.com/fsnotify/fsnotify` to notice edited files; - `github.com/prometheus/client_golang` for the metrics; - `github.com/spf13/viper` to read the settings from the environment; + - `github.com/spf13/cobra` for the commands and their help text; - `github.com/maxmind/mmdbwriter`, in the tests, to write lookup databases; - remote log sending written in this project, since the standard library's `log/syslog` is frozen and writes only the older syslog format. diff --git a/go.mod b/go.mod index b0d5138..83fb386 100644 --- a/go.mod +++ b/go.mod @@ -11,6 +11,7 @@ require ( github.com/maxmind/mmdbwriter v1.2.0 github.com/oschwald/maxminddb-golang/v2 v2.7.0 github.com/prometheus/client_golang v1.24.1 + github.com/spf13/cobra v1.10.2 github.com/spf13/viper v1.21.0 go.uber.org/fx v1.24.0 golang.org/x/net v0.60.0 @@ -26,6 +27,7 @@ require ( github.com/goccy/go-yaml v1.19.2 // indirect github.com/gotnospirit/makeplural v0.0.0-20180622080156-a5f48d94d976 // indirect github.com/gotnospirit/messageformat v0.0.0-20221001023931-dfe49f1eb092 // indirect + github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/kaptinlin/go-i18n v0.1.4 // indirect github.com/kaptinlin/jsonschema v0.4.6 // indirect github.com/kylelemons/godebug v1.1.0 // indirect diff --git a/go.sum b/go.sum index f9328ba..0c4a10a 100644 --- a/go.sum +++ b/go.sum @@ -14,6 +14,7 @@ github.com/corazawaf/coraza/v3 v3.8.2-0.20261022102553-d028be399c68 h1:KLEjvBBSw github.com/corazawaf/coraza/v3 v3.8.2-0.20261022102553-d028be399c68/go.mod h1:9XocblQEwK6EYylRth7PrPIifF2l0iSoYo4FAXhXU/8= github.com/corazawaf/libinjection-go v0.3.4 h1:jX2Tit2xZxYJJyVryNXucYBZtQqS7473x9Nc6lgRRbk= github.com/corazawaf/libinjection-go v0.3.4/go.mod h1:Ik/+w3UmTWH9yn366RgS9D95K3y7Atb5m/H/gXzzPCk= +github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/foxcpp/go-mockdns v1.2.0 h1:omK3OrHRD1IWJz1FuFBCFquhXslXoF17OvBS6JPzZF0= github.com/foxcpp/go-mockdns v1.2.0/go.mod h1:IhLeSFGed3mJIAXPH2aiRQB+kqz7oqu8ld2qVbOu7Wk= github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= @@ -34,6 +35,8 @@ github.com/gotnospirit/messageformat v0.0.0-20221001023931-dfe49f1eb092 h1:c7gcN github.com/gotnospirit/messageformat v0.0.0-20221001023931-dfe49f1eb092/go.mod h1:ZZAN4fkkful3l1lpJwF8JbW41ZiG9TwJ2ZlqzQovBNU= github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/jcchavezs/mergefs v0.1.1 h1:D45R17m6dHnSVZefnhynoeZvcK2Uw0oTrRfoUOQ0S5Y= github.com/jcchavezs/mergefs v0.1.1/go.mod h1:eRLTrsA+vFwQZ48hj8p8gki/5v9C2bFtHH5Mnn4bcGk= github.com/kaptinlin/go-i18n v0.1.4 h1:wCiwAn1LOcvymvWIVAM4m5dUAMiHunTdEubLDk4hTGs= @@ -72,6 +75,7 @@ github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+ github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY= github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc= github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik= github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw= @@ -80,6 +84,9 @@ github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I= github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg= github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY= github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= +github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= +github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= +github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU= @@ -109,6 +116,7 @@ go.uber.org/zap v1.26.0 h1:sI7k6L95XOKS281NhVKOFCUNIvv9e0w4BF8N3u+tCRo= go.uber.org/zap v1.26.0/go.mod h1:dtElttAiwGvoJ/vj4IwHBS/gXsEu/pZ50mUIRWuG0so= go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ= go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= go4.org/netipx v0.0.0-20231129151722-fdeea329fbba h1:0b9z3AuHCjxk0x/opv64kcgZLBseWJUpBw5I82+2U4M= @@ -127,6 +135,7 @@ golang.org/x/tools v0.50.0 h1:c2ifzfcuY7L90lZ2aKd8S4K2NpASF08SZx9ZuJkHmSU= golang.org/x/tools v0.50.0/go.mod h1:7ulVMw3831Mwi5EZD6RomGyffr4VFjuNYXf2BbCEAV0= google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= rsc.io/binaryregexp v0.2.0 h1:HfqmD5MEmC0zvwBuF187nq9mdnXjXsSivRiXN7SmRkE= diff --git a/internal/sww/sww.go b/internal/sww/sww.go index c526ec9..e70f73f 100644 --- a/internal/sww/sww.go +++ b/internal/sww/sww.go @@ -10,13 +10,14 @@ package sww import ( "context" - "fmt" + "errors" "io" "os" "os/signal" "syscall" "time" + "github.com/spf13/cobra" "github.com/spf13/viper" "sneak.berlin/go/smallwebwaf/internal/config" @@ -26,14 +27,7 @@ import ( // know. const usageStatus = 2 -// usage is what sww prints then. -const usage = `usage: sww - -commands: - rproxy the reverse proxy in front of one app - waf decides for rproxy, and keeps bans, counters and history - healthcheck the container's health check -` +var errNoCommand = errors.New("no command given") // Params are what RunWAF and RunRProxy need from the process. type Params struct { @@ -51,14 +45,9 @@ type Params struct { // Main runs the command os.Args names, and returns the process's exit status. // `sww rproxy` and `sww waf` run until SIGTERM or SIGINT. -// With no command, or one it does not know, it prints the commands and returns -// usageStatus. +// With no command, or one it does not know, cobra prints the error and the +// commands to stderr, and Main returns usageStatus. func Main(version string) int { - args := os.Args[1:] - if len(args) == 0 { - return printUsage(os.Stderr) - } - ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt) defer stop() @@ -69,21 +58,54 @@ func Main(version string) int { Stdout: os.Stdout, } - switch args[0] { - case "rproxy": - return RunRProxy(ctx, params) - case "waf": - return RunWAF(ctx, params) - case "healthcheck": - return HealthCheck(ctx, args[1:], params.Viper, os.Stderr) - default: - return printUsage(os.Stderr) + // status is what the command that ran returns. + status := 0 + + root := &cobra.Command{ + Use: "sww", + Short: "a web application firewall", + Args: cobra.NoArgs, + RunE: func(*cobra.Command, []string) error { + return errNoCommand + }, } -} + root.CompletionOptions.DisableDefaultCmd = true -// printUsage writes the commands to w, and returns usageStatus. -func printUsage(w io.Writer) int { - _, _ = fmt.Fprint(w, usage) + root.AddCommand( + &cobra.Command{ + Use: "rproxy", + Short: "the reverse proxy in front of one app", + Run: func(cmd *cobra.Command, _ []string) { + status = RunRProxy(cmd.Context(), params) + }, + }, + &cobra.Command{ + Use: "waf", + Short: "decides for rproxy, and keeps bans, counters and history", + Run: func(cmd *cobra.Command, _ []string) { + status = RunWAF(cmd.Context(), params) + }, + }, + &cobra.Command{ + Use: "healthcheck", + Short: "the container's health check", + // HealthCheck refuses every argument itself, flags included. + DisableFlagParsing: true, + Run: func(cmd *cobra.Command, args []string) { + status = HealthCheck( + cmd.Context(), + args, + params.Viper, + cmd.ErrOrStderr(), + ) + }, + }, + ) - return usageStatus + err := root.ExecuteContext(ctx) + if err != nil { + return usageStatus + } + + return status } diff --git a/internal/sww/waf_test.go b/internal/sww/waf_test.go index 8ad703c..340e84c 100644 --- a/internal/sww/waf_test.go +++ b/internal/sww/waf_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "crypto/rand" + "errors" "io" "net/http" "os" @@ -164,46 +165,104 @@ func wantUTC(t *testing.T, where string, value any) { func TestMainWithoutACommandItKnowsPrintsTheCommands(t *testing.T) { t.Parallel() + // completion is cobra's own command, which sww turns off. + for _, command := range []string{"", "serve", "completion"} { + t.Run("command "+command, func(t *testing.T) { + t.Parallel() + + code, stdout, stderr := runMain(t, command) + + if code != 2 { + t.Errorf("exit status %d, want 2", code) + } + + wantTheCommands(t, "stderr", stderr) + + if stdout != "" { + t.Errorf("stdout %q, want nothing", stdout) + } + }) + } +} + +func TestMainHelpPrintsTheCommands(t *testing.T) { + t.Parallel() + + for _, command := range []string{"help", "--help"} { + t.Run("command "+command, func(t *testing.T) { + t.Parallel() + + code, stdout, _ := runMain(t, command) + + if code != 0 { + t.Errorf("exit status %d, want 0", code) + } + + wantTheCommands(t, "stdout", stdout) + }) + } +} + +// wantTheCommands checks that text, what Main wrote to where, names each +// command. +func wantTheCommands(t *testing.T, where, text string) { + t.Helper() + + for _, name := range []string{"rproxy", wafCommand, "healthcheck"} { + if !strings.Contains(text, name) { + t.Errorf("%s %q does not name %s", where, text, name) + } + } +} + +func TestMainHealthCheckRefusesAnArgument(t *testing.T) { + t.Parallel() + + for _, argument := range []string{"now", "--x", "-h"} { + t.Run("argument "+argument, func(t *testing.T) { + t.Parallel() + + code, stdout, stderr := runMain(t, "healthcheck "+argument) + + want := "sww healthcheck: unexpected argument \"" + + argument + "\"\n" + if code != 1 || stderr != want || stdout != "" { + t.Errorf("exit status %d, stdout %q and stderr %q, "+ + "want 1, nothing and %q", code, stdout, stderr, want) + } + }) + } +} + +// runMain runs Main with command in a process of its own, and returns its +// exit status and what it wrote to stdout and stderr. +func runMain(t *testing.T, command string) (int, string, string) { + t.Helper() + binary, err := os.Executable() if err != nil { t.Fatalf("find the test binary: %v", err) } - for _, command := range []string{"", "serve"} { - t.Run("command "+command, func(t *testing.T) { - t.Parallel() + ctx, cancel := context.WithTimeout(t.Context(), waitLimit) + defer cancel() - ctx, cancel := context.WithTimeout(t.Context(), waitLimit) - defer cancel() + var stdout, stderr bytes.Buffer - var stdout, stderr bytes.Buffer + //nolint:gosec // this test binary + cmd := exec.CommandContext(ctx, binary) + cmd.Stdout, cmd.Stderr = &stdout, &stderr - cmd := exec.CommandContext(ctx, binary) - cmd.Stdout, cmd.Stderr = &stdout, &stderr + cmd.Env = append(os.Environ(), commandForMain+"="+command) - cmd.Env = append(os.Environ(), commandForMain+"="+command) + err = cmd.Run() - err := cmd.Run() - - if code := cmd.ProcessState.ExitCode(); code != 2 { - t.Errorf("exit status %d (%v), want 2", code, err) - } - - for _, name := range []string{"rproxy", wafCommand, "healthcheck"} { - if !strings.Contains(stderr.String(), name) { - t.Errorf( - "stderr %q does not name %s", - stderr.String(), - name, - ) - } - } - - if stdout.Len() != 0 { - t.Errorf("stdout %q, want nothing", stdout.String()) - } - }) + var exitErr *exec.ExitError + if err != nil && !errors.As(err, &exitErr) { + t.Fatalf("run: %v", err) } + + return cmd.ProcessState.ExitCode(), stdout.String(), stderr.String() } // ask sends waf at addr rproxy's question about a request for path from