Skip to content

Commit 61b8157

Browse files
TMHSDigitalclaude
andcommitted
refactor(scan): always end with exactly one EventDone
scan.Run returned without EventDone on five early-exit paths and when cancelled during preflight or the wildcard probe, so the CLI, the TUI and pkg/subenum each handled a channel that could close without a final event. It now always sends one EventDone, with Stopped set (and the checks' query count) when nothing was scanned. The CLI treats Stopped as not done, the TUI maps it to stoppedMsg, and pkg/subenum drops its synthesized KindDone and exposes Event.Stopped. EventError's doc no longer calls it non-fatal. A test covers every early-exit path. Fixes #99 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 607e7e7 commit 61b8157

10 files changed

Lines changed: 149 additions & 33 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
77

88
## [Unreleased]
99

10+
### Changed
11+
- The scan engine always ends with exactly one done event, marked `Stopped` when the scan ended before testing any candidate (out of scope, recursion ceiling, failed preflight or wildcard check, a wildcard zone without `-force`, or Ctrl+C during those checks), so the CLI, the TUI and `pkg/subenum` handle one shape of ending instead of a channel that sometimes closes without one. `pkg/subenum`'s `Event` gains `Stopped`, and a stopped scan's `Stats` now include the queries its checks sent (#99).
12+
1013
### Fixed
1114
- `tools/wordlist-gen` parses flags that appear after a positional the same way `subenum` does, instead of silently ignoring both: a leftover argument is now a usage error (2) that points at `-domain`, and an invalid `-combine` value or an empty `-o` exits 2 instead of 1 (#120).
1215

‎internal/scan/runner.go‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -343,8 +343,12 @@ const (
343343
EventResult EventKind = iota
344344
EventProgress // progress update
345345
EventNotice // informational notice; see Event.Notice
346-
EventError // non-fatal error message
347-
EventDone // scan finished
346+
// EventError reports a problem. Usually the scan then stops and its
347+
// EventDone has Stopped set; after the reliability guard (with NoAbort)
348+
// the scan goes on.
349+
EventError
350+
// EventDone is always the last event, sent exactly once (#99).
351+
EventDone
348352
)
349353

350354
// NoticeKind says what an EventNotice is about, so consumers can style or
@@ -388,6 +392,11 @@ type Event struct {
388392
Found int64 // EventProgress / EventDone
389393
Message string // EventError / EventNotice
390394
Stats Stats // EventDone: per-outcome counters
395+
// Stopped is set on EventDone when the scan ended before testing any
396+
// candidate: after an EventError (out of scope, recursion ceiling, failed
397+
// preflight or wildcard check, wildcard zone without Force) or when ctx
398+
// was cancelled during those checks. Its Stats cover only the checks.
399+
Stopped bool
391400
}
392401

393402
// Run executes the subdomain scan, sending events to the provided channel.
@@ -427,6 +436,14 @@ func Run(ctx context.Context, cfg Config, events chan<- Event) {
427436
}
428437
var queriesSent atomic.Int64
429438
ctx = dns.WithQueryCounter(ctx, &queriesSent)
439+
// Every scan ends with exactly one EventDone (#99): one that stops before
440+
// the candidates sends it here, with Stopped set, before close(events).
441+
doneSent := false
442+
defer func() {
443+
if !doneSent {
444+
events <- Event{Kind: EventDone, Stopped: true, Total: int64(len(cfg.Entries)), Stats: Stats{QueriesSent: queriesSent.Load()}}
445+
}
446+
}()
430447
wildcardRoot := false
431448

432449
// Out-of-scope names are never queried (#87). A target that is itself
@@ -745,6 +762,7 @@ func Run(ctx context.Context, cfg Config, events chan<- Event) {
745762
// wait for it after cancel, so this send must not be select-guarded on
746763
// ctx.Done(): once ctx is cancelled that select is a coin-flip drop.
747764
// Contract: consumers drain until close. See #23.
765+
doneSent = true
748766
events <- Event{
749767
Kind: EventDone,
750768
Processed: atomic.LoadInt64(&processed),

‎internal/scan/runner_test.go‎

Lines changed: 68 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -521,8 +521,8 @@ func TestRunRecursionCeilingRefuse(t *testing.T) {
521521
if !strings.Contains(errs[0].Message, "refusing to start") {
522522
t.Errorf("message %q", errs[0].Message)
523523
}
524-
if done != nil {
525-
t.Error("refused scan should not emit EventDone")
524+
if done == nil || !done.Stopped {
525+
t.Errorf("refused scan: final event %+v, want EventDone with Stopped (#99)", done)
526526
}
527527
}
528528

@@ -609,8 +609,8 @@ func TestRunPreflightFailsOnBlackHole(t *testing.T) {
609609
if !strings.Contains(errs[0].Message, "preflight") || !strings.Contains(errs[0].Message, addr) {
610610
t.Errorf("message %q: want preflight and resolver addr", errs[0].Message)
611611
}
612-
if done != nil {
613-
t.Error("failed preflight should not emit EventDone")
612+
if done == nil || !done.Stopped {
613+
t.Errorf("failed preflight: final event %+v, want EventDone with Stopped (#99)", done)
614614
}
615615
}
616616

@@ -1161,3 +1161,67 @@ func TestNoticesCarryKind(t *testing.T) {
11611161
}
11621162
}
11631163
}
1164+
1165+
// TestRunAlwaysEndsWithOneDone covers #99: every early exit ends with
1166+
// exactly one EventDone, marked Stopped, as the last event.
1167+
func TestRunAlwaysEndsWithOneDone(t *testing.T) {
1168+
drop, stopDrop := startUDPDNSAction(t, func(string) dnsAction { return dnsAction{drop: true} })
1169+
defer stopDrop()
1170+
wildcard, stopWild := startUDPDNSAction(t, func(string) dnsAction { return dnsAction{ip: [4]byte{192, 0, 2, 1}, hit: true} })
1171+
defer stopWild()
1172+
flakyProbes, stopFlaky := startUDPDNSAction(t, func(name string) dnsAction {
1173+
if name == "example.com" {
1174+
return dnsAction{ip: [4]byte{192, 0, 2, 1}, hit: true}
1175+
}
1176+
return dnsAction{servFail: true}
1177+
})
1178+
defer stopFlaky()
1179+
live := func(server string) Config {
1180+
return Config{Domain: "example.com", Entries: makeEntries(5), Concurrency: 2, Timeout: 100 * time.Millisecond,
1181+
Attempts: 1, Types: []string{"A"}, DNSServer: server, Resolver: dns.NewResolver(100*time.Millisecond, server)}
1182+
}
1183+
cases := map[string]struct {
1184+
cfg Config
1185+
cancelIn time.Duration
1186+
wantError bool
1187+
}{
1188+
"out of scope": {cfg: Config{Domain: "example.com", Entries: makeEntries(5), Simulate: true, HitRate: 50, Exclude: []string{"example.com"}}, wantError: true},
1189+
"recursion ceiling": {cfg: Config{Domain: "example.com", Entries: makeEntries(1000), Simulate: true, HitRate: 50, Recursive: true, Depth: 4}, wantError: true},
1190+
"failed preflight": {cfg: live(drop), wantError: true},
1191+
"wildcard check": {cfg: live(flakyProbes), wantError: true},
1192+
"wildcard zone": {cfg: live(wildcard), wantError: true},
1193+
"cancelled": {cfg: func() Config {
1194+
c := live(drop)
1195+
c.Timeout, c.Resolver = 5*time.Second, dns.NewResolver(5*time.Second, drop)
1196+
return c
1197+
}(), cancelIn: 50 * time.Millisecond},
1198+
}
1199+
for name, c := range cases {
1200+
t.Run(name, func(t *testing.T) {
1201+
ctx, cancel := context.WithCancel(context.Background())
1202+
defer cancel()
1203+
if c.cancelIn > 0 {
1204+
time.AfterFunc(c.cancelIn, cancel)
1205+
}
1206+
events := make(chan Event, 64)
1207+
go Run(ctx, c.cfg, events)
1208+
var all []Event
1209+
for ev := range events {
1210+
all = append(all, ev)
1211+
}
1212+
dones := 0
1213+
sawError := false
1214+
for _, ev := range all {
1215+
dones += map[bool]int{true: 1}[ev.Kind == EventDone]
1216+
sawError = sawError || ev.Kind == EventError
1217+
}
1218+
last := all[len(all)-1]
1219+
if dones != 1 || last.Kind != EventDone || !last.Stopped {
1220+
t.Fatalf("%d EventDone, last event %+v; want exactly one, last, with Stopped", dones, last)
1221+
}
1222+
if sawError != c.wantError {
1223+
t.Errorf("EventError seen %v, want %v", sawError, c.wantError)
1224+
}
1225+
})
1226+
}
1227+
}

‎internal/tui/model.go‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -270,10 +270,10 @@ func (m Model) updateScan(msg tea.Msg) (tea.Model, tea.Cmd) {
270270
}
271271
m.reportOutputErr(m.finalizeOutput(true))
272272
return m, svCmd
273-
case abortedMsg:
274-
// Channel closed without EventDone (early error such as wildcard without
275-
// -force): close the file without finalizing, mirroring the CLI which
276-
// skips Finish on the error path to avoid an empty JSON array.
273+
case stoppedMsg:
274+
// The scan stopped before testing candidates (an early error such as a
275+
// wildcard zone without Force, #99): close the file without finalizing,
276+
// mirroring the CLI, which skips Finish so no empty JSON array is written.
277277
m.reportOutputErr(m.finalizeOutput(false))
278278
return m, svCmd
279279
}
@@ -355,7 +355,9 @@ func listenForEvents(events <-chan scan.Event) tea.Cmd {
355355
return func() tea.Msg {
356356
ev, ok := <-events
357357
if !ok {
358-
return abortedMsg{}
358+
// scan.Run always sends EventDone before closing (#99), and the
359+
// listener is not re-armed after it; a closed channel is defensive.
360+
return stoppedMsg{}
359361
}
360362
switch ev.Kind {
361363
case scan.EventResult:
@@ -367,6 +369,9 @@ func listenForEvents(events <-chan scan.Event) tea.Cmd {
367369
case scan.EventError:
368370
return errorMsg{text: ev.Message}
369371
case scan.EventDone:
372+
if ev.Stopped {
373+
return stoppedMsg{}
374+
}
370375
return doneMsg{processed: ev.Processed, total: ev.Total, found: ev.Found, stats: ev.Stats}
371376
}
372377
return nil

‎internal/tui/model_test.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import (
1515
// TestFinalizeOutputGatesStructuredOutput locks in the TUI's replication of the
1616
// CLI contract: structured output is finalized only on the success path
1717
// (doneMsg -> finalizeOutput(true)). The early-error path
18-
// (abortedMsg -> finalizeOutput(false)) must not emit an empty JSON array, the
18+
// (stoppedMsg -> finalizeOutput(false)) must not emit an empty JSON array, the
1919
// bug fixed once for the CLI in main.run, and must leave an existing results
2020
// file untouched (#52).
2121
func TestFinalizeOutputGatesStructuredOutput(t *testing.T) {
@@ -185,7 +185,7 @@ func TestScanFailureStatusAndExitCode(t *testing.T) {
185185
}
186186

187187
// Preflight failure: error, then the channel closes without EventDone.
188-
sv := update(newScanViewModel(120, 40, false), errorMsg{text: "resolver failed preflight"}, abortedMsg{})
188+
sv := update(newScanViewModel(120, 40, false), errorMsg{text: "resolver failed preflight"}, stoppedMsg{})
189189
if !sv.failed() || !strings.Contains(sv.View(), "Failed: resolver failed preflight") || strings.Contains(sv.View(), "Aborted") {
190190
t.Errorf("preflight failure not shown as Failed:\n%s", sv.View())
191191
}

‎internal/tui/output_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ func runTUIScan(t *testing.T, format output.Format, formatName string, types []s
4040
if _, done := msg.(doneMsg); done {
4141
break
4242
}
43-
if _, aborted := msg.(abortedMsg); aborted {
43+
if _, aborted := msg.(stoppedMsg); aborted {
4444
t.Fatal("scan ended without a final event")
4545
}
4646
}

‎internal/tui/scan_view.go‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ type scanViewModel struct {
5252
stats scan.Stats
5353
done bool
5454
aborted bool // the user pressed ctrl+c
55-
closed bool // the scan ended without EventDone (preflight, wildcard abort)
55+
stopped bool // the scan stopped before testing candidates (preflight, wildcard abort, #99)
5656
errText string // first scan error; the reason shown for a failed scan
5757
noAbort bool // -no-abort: an error with a finished scan is only a warning
5858
width int
@@ -179,8 +179,8 @@ func (m scanViewModel) Update(msg tea.Msg) (scanViewModel, tea.Cmd) {
179179
m.stats = msg.stats
180180
m.refresh()
181181

182-
case abortedMsg:
183-
m.closed = true
182+
case stoppedMsg:
183+
m.stopped = true
184184
m.done = true
185185
m.refresh()
186186
}
@@ -225,7 +225,7 @@ func (m scanViewModel) View() string {
225225
m.processed, m.total, m.found, m.stats.NXDomain, m.stats.Timeout, m.stats.Refused, m.stats.Other, m.stats.WildcardFiltered,
226226
)) + "\n")
227227
b.WriteString(hintStyle.Render(" r new scan • q quit"))
228-
case m.done && (m.aborted || m.closed):
228+
case m.done && (m.aborted || m.stopped):
229229
b.WriteString(dimStyle.Render(fmt.Sprintf(
230230
"Aborted - processed %d/%d - found %d - nxdomain %d - timeout %d - refused %d - other %d - wildcard-filtered %d",
231231
m.processed, m.total, m.found, m.stats.NXDomain, m.stats.Timeout, m.stats.Refused, m.stats.Other, m.stats.WildcardFiltered,
@@ -253,7 +253,7 @@ func (m scanViewModel) View() string {
253253
// that ended without EventDone after an error (preflight failure, wildcard
254254
// abort) is a failure, not a user abort (#55).
255255
func (m scanViewModel) failed() bool {
256-
return m.done && m.errText != "" && (m.closed || !m.noAbort)
256+
return m.done && m.errText != "" && (m.stopped || !m.noAbort)
257257
}
258258

259259
// Event message types for Bubble Tea.
@@ -269,7 +269,7 @@ type doneMsg struct {
269269
processed, total, found int64
270270
stats scan.Stats
271271
}
272-
type abortedMsg struct{}
272+
type stoppedMsg struct{}
273273
type wordlistLoadedMsg struct {
274274
cfg formValues
275275
entries []string

‎main.go‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1138,11 +1138,16 @@ func scanTarget(ctx context.Context, f cliFlags, domain string, entries []string
11381138
}
11391139
sawError = true
11401140
finishProgress()
1141-
// Keep draining so EventDone (and Stats) can still arrive after a
1142-
// reliability abort. Early errors such as wildcard detection close
1143-
// the channel without EventDone.
1141+
// Keep draining: EventDone always follows (#99), Stopped after an
1142+
// early error such as wildcard detection, with Stats after a
1143+
// reliability abort.
11441144
case scan.EventDone:
11451145
finishProgress()
1146+
if ev.Stopped {
1147+
// Nothing was scanned: the run failed (or was interrupted)
1148+
// before the candidates, so it does not count as done.
1149+
break
1150+
}
11461151
res.done = true
11471152
res.final = ev
11481153
logScanBreakdown(domain, ev, out)

‎pkg/subenum/subenum.go‎

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -296,6 +296,12 @@ type Event struct {
296296

297297
// Stats is the final accounting, on KindDone.
298298
Stats Stats
299+
300+
// Stopped is set on KindDone when the scan ended before testing any
301+
// candidate, after a KindError (the domain is out of scope, a wildcard
302+
// zone without Force, a failed resolver check) or because ctx was
303+
// cancelled during those checks. Stats then covers only the checks.
304+
Stopped bool
299305
}
300306

301307
// DefaultWords returns the bundled wordlist: the most common subdomain labels,
@@ -350,17 +356,10 @@ func Run(ctx context.Context, cfg Config) (<-chan Event, error) {
350356
out := make(chan Event, 64)
351357
go func() {
352358
defer close(out)
353-
done := false
359+
// scan.Run always ends with exactly one EventDone (#99), so the
360+
// channel ends with exactly one KindDone too.
354361
for ev := range in {
355-
translated := translate(ev)
356-
done = done || translated.Kind == KindDone
357-
forward(ctx, out, translated)
358-
}
359-
// The engine returns without a final event when a scan never gets
360-
// to start, such as a wildcard zone without Force. Report the same
361-
// terminal event anyway, so consumers need only one shape.
362-
if !done {
363-
forward(ctx, out, Event{Kind: KindDone})
362+
forward(ctx, out, translate(ev))
364363
}
365364
}()
366365
return out, nil
@@ -620,6 +619,7 @@ func translate(ev scan.Event) Event {
620619
case scan.EventDone:
621620
out.Kind = KindDone
622621
out.Stats = stats(ev.Stats)
622+
out.Stopped = ev.Stopped
623623
}
624624
return out
625625
}

‎pkg/subenum/subenum_test.go‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -446,3 +446,24 @@ func TestSubMillisecondTimeoutRoundsUp(t *testing.T) {
446446
t.Errorf("Timeout 500µs: %v", err)
447447
}
448448
}
449+
450+
// TestStoppedScanEndsWithOneDone covers #99: a scan refused before it starts
451+
// (here, an out-of-scope domain) still ends with exactly one KindDone, marked
452+
// Stopped, after the KindError.
453+
func TestStoppedScanEndsWithOneDone(t *testing.T) {
454+
events, err := subenum.Run(context.Background(), subenum.Config{
455+
Domain: "example.com", Words: []string{"www"}, Simulate: true, Exclude: []string{"example.com"},
456+
})
457+
if err != nil {
458+
t.Fatal(err)
459+
}
460+
var kinds []subenum.Kind
461+
var last subenum.Event
462+
for ev := range events {
463+
kinds = append(kinds, ev.Kind)
464+
last = ev
465+
}
466+
if len(kinds) != 2 || kinds[0] != subenum.KindError || last.Kind != subenum.KindDone || !last.Stopped {
467+
t.Errorf("events %v, last %+v; want an error, then one done with Stopped", kinds, last)
468+
}
469+
}

0 commit comments

Comments
 (0)