Skip to content

Commit f1e4d8c

Browse files
authored
fix: keep verbose and TUI diagnostics accurate (#336)
1 parent bed3367 commit f1e4d8c

8 files changed

Lines changed: 100 additions & 19 deletions

File tree

‎internal/dns/resolver.go‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -473,10 +473,19 @@ func StderrLogf(format string, args ...any) {
473473
// by the CLI, returning the resolved records for the requested types.
474474
func (l Lookup) resolveWithLog(ctx context.Context, domain string) ([]Record, time.Duration, error) {
475475
records, elapsed, err := l.ResolveTypes(ctx, domain)
476-
if l.Logf != nil && len(records) > 0 {
477-
l.Logf("Resolved: %s (%s: %s) in %s", domain, records[0].Type, records[0].Value, elapsed)
478-
} else if l.Logf != nil {
479-
l.Logf("Failed to resolve: %s (Error: %v) in %s", domain, err, elapsed)
476+
if l.Logf != nil {
477+
switch {
478+
case len(records) > 0:
479+
l.Logf("Resolved: %s (%s: %s) in %s", domain, records[0].Type, records[0].Value, elapsed)
480+
case err == nil:
481+
types := l.Types
482+
if len(types) == 0 {
483+
types = DefaultTypes
484+
}
485+
l.Logf("No records: %s (%s) in %s", domain, strings.Join(types, ","), elapsed)
486+
default:
487+
l.Logf("Failed to resolve: %s (Error: %v) in %s", domain, err, elapsed)
488+
}
480489
}
481490
return records, elapsed, err
482491
}

‎internal/dns/resolver_test.go‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"fmt"
77
"net"
88
"os"
9+
"strings"
910
"testing"
1011
"time"
1112
)
@@ -227,6 +228,43 @@ func TestResolveDomainWithRetryCNAMENoData(t *testing.T) {
227228
}
228229
}
229230

231+
func TestResolveVerboseNoData(t *testing.T) {
232+
srv := startTestDNS(t, map[string]testReply{
233+
"www.example.com": {A: "192.0.2.10"},
234+
"alias.example.com": {CNAME: "www.example.com"},
235+
})
236+
for _, tc := range []struct {
237+
domain string
238+
prefix string
239+
outcome Outcome
240+
}{
241+
{"www.example.com", "No records: www.example.com (CNAME) in ", OutcomeNXDomain},
242+
{"alias.example.com", "Resolved: alias.example.com (CNAME: www.example.com) in ", OutcomeFound},
243+
{"missing.example.com", "Failed to resolve: missing.example.com (Error: ", OutcomeNXDomain},
244+
} {
245+
t.Run(tc.domain, func(t *testing.T) {
246+
var lines []string
247+
lookup := Lookup{
248+
Resolver: srv.Resolver(time.Second), Timeout: time.Second,
249+
Attempts: 1, Types: []string{"CNAME"},
250+
Logf: func(format string, args ...any) {
251+
lines = append(lines, fmt.Sprintf(format, args...))
252+
},
253+
}
254+
_, outcome := lookup.Resolve(context.Background(), tc.domain)
255+
if outcome != tc.outcome {
256+
t.Errorf("outcome = %v, want %v", outcome, tc.outcome)
257+
}
258+
if len(lines) != 1 || !strings.HasPrefix(lines[0], tc.prefix) {
259+
t.Fatalf("verbose lines = %q, want one beginning %q", lines, tc.prefix)
260+
}
261+
if strings.Contains(lines[0], "Error: <nil>") {
262+
t.Errorf("successful NODATA lookup logged a nil error: %q", lines[0])
263+
}
264+
})
265+
}
266+
}
267+
230268
// TestCheckWildcardCNAMEFingerprint covers the second half of #28: with
231269
// -type CNAME the wildcard fingerprint must carry the CNAME target, otherwise
232270
// recordsSubset can never filter CNAME-wildcard answers under -force.

‎internal/output/writer.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ type Format int
2525
const (
2626
// FormatText is the default human-friendly streaming output.
2727
FormatText Format = iota
28-
// FormatJSON buffers results and emits a single JSON array at completion.
28+
// FormatJSON streams results as array elements; Finish closes the array.
2929
FormatJSON
3030
// FormatCSV streams "subdomain,type,value" rows with a header.
3131
FormatCSV

‎internal/tui/model.go‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -348,8 +348,8 @@ func (m Model) updateScan(msg tea.Msg) (tea.Model, tea.Cmd) {
348348
return m, svCmd
349349
case ev.Kind == scan.EventDone:
350350
// Successful completion (including user abort, which still drains and
351-
// emits EventDone): finalize structured output so buffered JSON/CSV is
352-
// written and partial results are flushed. A JSONL file ends with the
351+
// emits EventDone): finalize structured output to close the streamed JSON
352+
// array and flush CSV and partial results. A JSONL file ends with the
353353
// run-quality summary, as the CLI's does (#118).
354354
if m.out != nil {
355355
m.out.Summary(m.summary(ev.Event))
@@ -365,7 +365,7 @@ func (m Model) updateScan(msg tea.Msg) (tea.Model, tea.Cmd) {
365365
}
366366

367367
// finalizeOutput closes the optional output file. When finish is true the
368-
// structured writer is finalized first (buffered JSON array emitted, CSV
368+
// structured writer is finalized first (streamed JSON array closed, CSV
369369
// flushed) and the file replaces any existing one; when false it is discarded
370370
// and an existing results file is left untouched (#52).
371371
// Safe to call when no output file is configured.

‎main.go‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -300,10 +300,9 @@ func validateArgs(f cliFlags, positionals []string, fs *flag.FlagSet, out *outpu
300300
return true
301301
}
302302

303+
// validateFlags checks options after validateArgs has checked the domain
304+
// arguments. configure does that before reading any input files.
303305
func validateFlags(f cliFlags, in *runtimeInputs, positionals []string, fs *flag.FlagSet, out *output.Writer) (string, bool) {
304-
if !validateArgs(f, positionals, fs, out) {
305-
return "", false
306-
}
307306
if f.wordlists.readsStdin() && f.domainList == wordlist.Stdin {
308307
out.Error("-w and -dL cannot both read standard input")
309308
return "", false

‎main_logformat_test.go‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,11 @@ package main
33
import (
44
"bytes"
55
"encoding/json"
6+
"path/filepath"
67
"strings"
78
"testing"
9+
10+
"github.com/TMHSDigital/subenum/internal/output"
811
)
912

1013
// runCLIStreams runs the CLI with stdout and stderr captured apart.
@@ -178,3 +181,34 @@ func TestE2ELogFormatJSONProgress(t *testing.T) {
178181
}
179182
parseLogLines(t, stderr)
180183
}
184+
185+
func TestTUIOptionsJSONWarnings(t *testing.T) {
186+
d := &defaultsLoader{path: filepath.Join(t.TempDir(), "none.json"), getenv: func(string) string { return "" }}
187+
f, pos, fs, err := parseFlagsWith([]string{
188+
"-tui", "-log-format", "json", "-w", "first.txt", "-w", "extra.txt",
189+
"-stats", "stats.json", "example.com", "other.example.com",
190+
}, d.apply, nil)
191+
if err != nil {
192+
t.Fatal(err)
193+
}
194+
var stderr bytes.Buffer
195+
diag := output.New(nil, false, output.FormatText)
196+
diag.SetStderr(&stderr)
197+
diag.SetLogFormat(output.LogJSON)
198+
opts := tuiOptions(f, fs, pos, d, diag)
199+
if opts.Domain != "example.com" || opts.Settings["w"] != "first.txt" {
200+
t.Fatalf("TUI options = %+v", opts)
201+
}
202+
lines := parseLogLines(t, stderr.String())
203+
if len(lines) != 2 {
204+
t.Fatalf("diagnostics = %+v, want two warnings", lines)
205+
}
206+
for i, want := range []string{
207+
"the TUI takes one wordlist; using first.txt",
208+
"-tui has no form field for -log-format -stats other.example.com; ignored",
209+
} {
210+
if lines[i].Level != "warn" || lines[i].Kind != "message" || lines[i].Message != want {
211+
t.Errorf("diagnostic %d = %+v, want a JSON warning with message %q", i, lines[i], want)
212+
}
213+
}
214+
}

‎main_session.go‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import (
77
"errors"
88
"flag"
99
"fmt"
10-
"io"
1110
"math/rand/v2"
1211
"os"
1312
"os/signal"
@@ -189,7 +188,7 @@ func (s *session) parse() (code int, done bool) {
189188
// -tui counts only as a real flag, not as the value of another flag
190189
// (-o -tui) or an argument after "--" (#58).
191190
if f.tui {
192-
return tui.Start(tuiOptions(f, fs, positionals, defaults, a.stderr)), true
191+
return tui.Start(tuiOptions(f, fs, positionals, defaults, diag)), true
193192
}
194193

195194
if f.printConfig {
@@ -209,7 +208,7 @@ func (s *session) parse() (code int, done bool) {
209208
// argument and every flag the form has a field for, over SUBENUM_* and config
210209
// file values. Flags the form has no field for are named in a warning, as are
211210
// extra domain arguments and extra -w files (the form takes one wordlist).
212-
func tuiOptions(f cliFlags, fs *flag.FlagSet, positionals []string, defaults *defaultsLoader, stderr io.Writer) tui.Options {
211+
func tuiOptions(f cliFlags, fs *flag.FlagSet, positionals []string, defaults *defaultsLoader, diag *output.Writer) tui.Options {
213212
settings := defaults.settings(fs)
214213
wired := map[string]bool{}
215214
for _, name := range tui.Flags() {
@@ -227,7 +226,7 @@ func tuiOptions(f cliFlags, fs *flag.FlagSet, positionals []string, defaults *de
227226
})
228227
if len(f.wordlists.paths) > 1 {
229228
settings["w"] = f.wordlists.paths[0]
230-
_, _ = fmt.Fprintf(stderr, "Warning: the TUI takes one wordlist; using %s\n", f.wordlists.paths[0])
229+
diag.Notice("Warning: the TUI takes one wordlist; using %s", f.wordlists.paths[0])
231230
}
232231
opts := tui.Options{Version: resolveVersion(), Settings: settings}
233232
if len(positionals) > 0 {
@@ -237,7 +236,7 @@ func tuiOptions(f cliFlags, fs *flag.FlagSet, positionals []string, defaults *de
237236
ignored = append(ignored, positionals[1:]...)
238237
}
239238
if len(ignored) > 0 {
240-
_, _ = fmt.Fprintf(stderr, "Warning: -tui has no form field for %s; ignored\n", strings.Join(ignored, " "))
239+
diag.Notice("Warning: -tui has no form field for %s; ignored", strings.Join(ignored, " "))
241240
}
242241
return opts
243242
}

‎main_test.go‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ func TestValidateFlagsDomainListConflicts(t *testing.T) {
9393

9494
f := base()
9595
f.domainList = "d.txt"
96-
if _, ok := validateFlags(f, &runtimeInputs{maxAttempts: 1}, []string{"example.com"}, fs, out); ok {
96+
if validateArgs(f, []string{"example.com"}, fs, out) {
9797
t.Error("domain argument plus -dL should be rejected")
9898
}
9999
f.wordlists.paths, f.domainList = []string{"-"}, "-"
@@ -335,7 +335,9 @@ func TestTUIOptionsFromFlags(t *testing.T) {
335335
t.Fatal(err)
336336
}
337337
var stderr bytes.Buffer
338-
opts := tuiOptions(f, fs, pos, d, &stderr)
338+
diag := output.New(nil, false, output.FormatText)
339+
diag.SetStderr(&stderr)
340+
opts := tuiOptions(f, fs, pos, d, diag)
339341
if opts.Domain != "example.com" {
340342
t.Errorf("Domain = %q, want example.com", opts.Domain)
341343
}
@@ -352,7 +354,7 @@ func TestTUIOptionsFromFlags(t *testing.T) {
352354
// A bare -tui warns about nothing.
353355
f, pos, fs, _ = parseFlagsWith([]string{"-tui"}, d.apply, nil)
354356
stderr.Reset()
355-
if opts := tuiOptions(f, fs, pos, d, &stderr); opts.Domain != "" || stderr.Len() != 0 {
357+
if opts := tuiOptions(f, fs, pos, d, diag); opts.Domain != "" || stderr.Len() != 0 {
356358
t.Errorf("bare -tui: Domain %q, stderr %q", opts.Domain, stderr.String())
357359
}
358360
}

0 commit comments

Comments
 (0)