Skip to content

Commit 57d9258

Browse files
TMHSDigitalclaude
andcommitted
refactor(scan): name settings with tokens, not CLI flags, in engine messages
Engine messages said "Use -force" or "(-t)" whatever the front end. They now use scan.Setting tokens ({force}, {max_queries}, ...) and each front end renders them: the CLI via scan.FlagName (output unchanged), the TUI via its form labels, pkg/subenum via Config field names, replacing the regexp that guessed flags out of message text. report.Target takes the renderer for verdict reasons. Tests check every Setting has a name in each front end and that no engine string literal names a flag. Fixes #100 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 61b8157 commit 57d9258

16 files changed

Lines changed: 226 additions & 117 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
88
## [Unreleased]
99

1010
### Changed
11+
- Engine messages no longer hard-code command-line flags. They name settings with neutral tokens (`scan.Setting`), and each front end renders them in its own terms: the CLI as flags (unchanged output), the TUI as its form labels ("Use Force to scan anyway", "invalid Exclude pattern"), and `pkg/subenum` as `Config` fields, replacing its regexp that guessed flags out of message text. A test fails if an engine message names a flag or uses an unknown token (#100).
1112
- 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).
1213

1314
### Fixed

‎internal/report/report.go‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,15 @@ func New(r Run) output.Summary {
4747

4848
// Target summarizes one domain's scan. status is "ok", "failed",
4949
// "interrupted", "skipped" or "" (never run); done reports whether the scan
50-
// sent its final event, final.
51-
func Target(domain, status, errMsg string, done bool, final scan.Event) output.TargetSummary {
50+
// finished, with final as its last event. name renders the settings the
51+
// verdict reason refers to, in the caller's terms (#100).
52+
func Target(domain, status, errMsg string, done bool, final scan.Event, name func(scan.Setting) string) output.TargetSummary {
53+
t := target(domain, status, errMsg, done, final)
54+
t.Reason = scan.Render(t.Reason, name)
55+
return t
56+
}
57+
58+
func target(domain, status, errMsg string, done bool, final scan.Event) output.TargetSummary {
5259
t := output.TargetSummary{Domain: domain, Status: status, Error: errMsg}
5360
switch {
5461
case status == "" || status == "skipped":

‎internal/scan/options.go‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -38,24 +38,24 @@ type Options struct {
3838
}
3939

4040
// Validate checks the numeric ranges and the resolver address. Messages name
41-
// the CLI flag too, so they read well in both front ends. The resolver is
41+
// each setting as a {token} that the front end renders (#100). The resolver is
4242
// not checked in simulation mode, which sends no DNS traffic.
4343
func (o Options) Validate() error {
4444
switch {
4545
case o.Concurrency < 1:
46-
return fmt.Errorf("concurrency (-t) must be at least 1, got %d", o.Concurrency)
46+
return fmt.Errorf("concurrency ({concurrency}) must be at least 1, got %d", o.Concurrency)
4747
case o.TimeoutMs < 1:
48-
return fmt.Errorf("timeout (-timeout) must be at least 1 ms, got %d", o.TimeoutMs)
48+
return fmt.Errorf("timeout ({timeout}) must be at least 1 ms, got %d", o.TimeoutMs)
4949
case o.Attempts < 1:
50-
return fmt.Errorf("attempts (-attempts) must be at least 1, got %d", o.Attempts)
50+
return fmt.Errorf("attempts ({attempts}) must be at least 1, got %d", o.Attempts)
5151
case o.Simulate && (o.HitRate < 1 || o.HitRate > 100):
52-
return fmt.Errorf("hit rate (-hit-rate) must be 1-100, got %d", o.HitRate)
52+
return fmt.Errorf("hit rate ({hit_rate}) must be 1-100, got %d", o.HitRate)
5353
case o.Depth < 1:
54-
return fmt.Errorf("depth (-depth) must be at least 1, got %d", o.Depth)
54+
return fmt.Errorf("depth ({depth}) must be at least 1, got %d", o.Depth)
5555
case o.Rate < 0:
56-
return fmt.Errorf("rate (-rate) must be 0 (unlimited) or a positive integer, got %d", o.Rate)
56+
return fmt.Errorf("rate ({rate}) must be 0 (unlimited) or a positive integer, got %d", o.Rate)
5757
case o.MaxQueries < 0:
58-
return fmt.Errorf("max queries (-max-queries) must be 0 (unlimited) or a positive integer, got %d", o.MaxQueries)
58+
return fmt.Errorf("max queries ({max_queries}) must be 0 (unlimited) or a positive integer, got %d", o.MaxQueries)
5959
}
6060
if !o.Simulate {
6161
if err := validate.DNSServer(o.DNSServer); err != nil {

‎internal/scan/runner.go‎

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -452,24 +452,24 @@ func Run(ctx context.Context, cfg Config, events chan<- Event) {
452452
cfg.scope = sc
453453
cfg.takeover = &dns.TakeoverCache{}
454454
if sc.excluded(cfg.Domain) || sc.subtreeExcluded(cfg.Domain) {
455-
events <- Event{Kind: EventError, Message: "refusing to scan " + cfg.Domain + ": it is out of scope (-exclude)"}
455+
events <- Event{Kind: EventError, Message: "refusing to scan " + cfg.Domain + ": it is out of scope ({exclude})"}
456456
return
457457
}
458458

459459
if cfg.Recursive {
460460
ceiling := RecursionCeiling(len(cfg.Entries), maxDepth)
461461
if ceiling > recursionRefuseCeiling && cfg.MaxQueries == 0 && !cfg.Force {
462462
events <- Event{Kind: EventError, Message: fmt.Sprintf(
463-
"refusing to start: -recursive -depth %d with %d entries can generate up to %.1e queries; set -max-queries or -force",
463+
"refusing to start: {recursive} {depth} %d with %d entries can generate up to %.1e queries; set {max_queries} or {force}",
464464
maxDepth, len(cfg.Entries), ceiling)}
465465
return
466466
}
467-
consider := "Consider -max-queries."
467+
consider := "Consider {max_queries}."
468468
if maxDepth > 1 {
469-
consider = fmt.Sprintf("Consider -depth %d or -max-queries.", maxDepth-1)
469+
consider = fmt.Sprintf("Consider {depth} %d or {max_queries}.", maxDepth-1)
470470
}
471471
events <- Event{Kind: EventNotice, Notice: NoticeCeiling, Message: fmt.Sprintf(
472-
"Warning: -recursive -depth %d with %d entries can generate up to %.1e queries.\n%s",
472+
"Warning: {recursive} {depth} %d with %d entries can generate up to %.1e queries.\n%s",
473473
maxDepth, len(cfg.Entries), ceiling, consider)}
474474
}
475475

@@ -506,19 +506,19 @@ func Run(ctx context.Context, cfg Config, events chan<- Event) {
506506
// every candidate would resolve and flood the results (#47). -force
507507
// scans anyway, but without a fingerprint to filter with.
508508
if err != nil && !cfg.Force {
509-
events <- Event{Kind: EventError, Message: "wildcard detection failed: " + err.Error() + "; results could not be filtered. Use -force to scan anyway."}
509+
events <- Event{Kind: EventError, Message: "wildcard detection failed: " + err.Error() + "; results could not be filtered. Use {force} to scan anyway."}
510510
return
511511
}
512512
if err != nil {
513-
events <- Event{Kind: EventNotice, Notice: NoticeWildcard, Message: "WARNING: wildcard detection failed (" + err.Error() + "); scanning without wildcard filtering because of -force"}
513+
events <- Event{Kind: EventNotice, Notice: NoticeWildcard, Message: "WARNING: wildcard detection failed (" + err.Error() + "); scanning without wildcard filtering because of {force}"}
514514
}
515515
fingerprint.add(fp)
516516
if isWildcard {
517517
wildcardRoot = true
518518
msg := "WARNING: Wildcard DNS detected - all subdomains resolve for " + cfg.Domain
519519
events <- Event{Kind: EventNotice, Notice: NoticeWildcard, Message: msg}
520520
if !cfg.Force {
521-
events <- Event{Kind: EventError, Message: "Results would be meaningless. Use -force to scan anyway."}
521+
events <- Event{Kind: EventError, Message: "Results would be meaningless. Use {force} to scan anyway."}
522522
return
523523
}
524524
}
@@ -680,7 +680,7 @@ func Run(ctx context.Context, cfg Config, events chan<- Event) {
680680
if skipped > 0 {
681681
select {
682682
case events <- Event{Kind: EventNotice, Notice: NoticeCap, Message: fmt.Sprintf(
683-
"query cap reached (-max-queries %d); skipped %d additional jobs", cfg.MaxQueries, skipped)}:
683+
"query cap reached ({max_queries} %d); skipped %d additional jobs", cfg.MaxQueries, skipped)}:
684684
case <-ctx.Done():
685685
}
686686
}
@@ -910,7 +910,7 @@ func checkReliability(cfg Config, processed int64, st *counters, events chan<- E
910910
if cfg.NoAbort {
911911
verb = "warning"
912912
}
913-
msg := fmt.Sprintf("%s: %.0f%% of %d queries failed (timeout/refused/other); likely resolver rate-limiting at -t %d and -rate %d",
913+
msg := fmt.Sprintf("%s: %.0f%% of %d queries failed (timeout/refused/other); likely resolver rate-limiting at {concurrency} %d and {rate} %d",
914914
verb, rate, processed, cfg.Concurrency, cfg.Rate)
915915
events <- Event{Kind: EventError, Message: msg}
916916
if !cfg.NoAbort {

‎internal/scan/runner_test.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -396,8 +396,8 @@ func TestRunReliabilityGuardAborts(t *testing.T) {
396396
if !strings.Contains(msg, "timeout/refused/other") {
397397
t.Errorf("error message %q: want failure classes", msg)
398398
}
399-
if !strings.Contains(msg, "-t 4") || !strings.Contains(msg, "-rate 0") {
400-
t.Errorf("error message %q: want configured -t and -rate", msg)
399+
if got := Render(msg, FlagName); !strings.Contains(got, "-t 4") || !strings.Contains(got, "-rate 0") {
400+
t.Errorf("error message %q: want configured -t and -rate once rendered for the CLI", got)
401401
}
402402
if done == nil {
403403
t.Fatal("no EventDone received after abort")

‎internal/scan/scope.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ func ValidateExcludes(patterns []string) error {
2424
for _, p := range patterns {
2525
n := normalizePattern(p)
2626
if err := validate.Domain(strings.TrimPrefix(n, "*.")); err != nil {
27-
return fmt.Errorf("invalid -exclude pattern %q: %w", p, err)
27+
return fmt.Errorf("invalid {exclude} pattern %q: %w", p, err)
2828
}
2929
}
3030
return nil

‎internal/scan/settings.go‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package scan
2+
3+
import (
4+
"regexp"
5+
"strings"
6+
)
7+
8+
// Setting names a scan setting inside an engine message (#100). The engine
9+
// has no idea whether it runs under the CLI (flags), the TUI (form fields) or
10+
// pkg/subenum (Config fields), so messages carry a setting as a {token}, and
11+
// each front end renders tokens in its own terms with Render.
12+
type Setting string
13+
14+
// Settings the engine refers to in messages.
15+
const (
16+
SettingConcurrency Setting = "concurrency"
17+
SettingTimeout Setting = "timeout"
18+
SettingAttempts Setting = "attempts"
19+
SettingHitRate Setting = "hit_rate"
20+
SettingDepth Setting = "depth"
21+
SettingRate Setting = "rate"
22+
SettingMaxQueries Setting = "max_queries"
23+
SettingExclude Setting = "exclude"
24+
SettingRecursive Setting = "recursive"
25+
SettingForce Setting = "force"
26+
)
27+
28+
// Settings lists every Setting, for front ends to check their name tables.
29+
var Settings = []Setting{
30+
SettingConcurrency, SettingTimeout, SettingAttempts, SettingHitRate, SettingDepth,
31+
SettingRate, SettingMaxQueries, SettingExclude, SettingRecursive, SettingForce,
32+
}
33+
34+
// Ref is the setting's token, to put in a message.
35+
func (s Setting) Ref() string { return "{" + string(s) + "}" }
36+
37+
var settingToken = regexp.MustCompile(`\{([a-z_]+)\}`)
38+
39+
// Render replaces every setting token in msg with name(setting). A token for
40+
// an unknown setting, or one name returns "" for, is left as it is.
41+
func Render(msg string, name func(Setting) string) string {
42+
if !strings.Contains(msg, "{") {
43+
return msg
44+
}
45+
return settingToken.ReplaceAllStringFunc(msg, func(tok string) string {
46+
if n := name(Setting(tok[1 : len(tok)-1])); n != "" {
47+
return n
48+
}
49+
return tok
50+
})
51+
}
52+
53+
// FlagName names a setting as the command-line flag that sets it, or ""
54+
// for a setting it does not know, which Render then leaves as a token.
55+
func FlagName(s Setting) string {
56+
switch s {
57+
case SettingConcurrency:
58+
return "-t"
59+
case SettingHitRate:
60+
return "-hit-rate"
61+
case SettingMaxQueries:
62+
return "-max-queries"
63+
case SettingTimeout, SettingAttempts, SettingDepth, SettingRate, SettingExclude, SettingRecursive, SettingForce:
64+
return "-" + string(s)
65+
}
66+
return ""
67+
}

‎internal/scan/settings_test.go‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package scan
2+
3+
import (
4+
"os"
5+
"path/filepath"
6+
"regexp"
7+
"strings"
8+
"testing"
9+
)
10+
11+
func TestRender(t *testing.T) {
12+
msg := "set {max_queries} or {force}; ({concurrency}, {hit_rate}) {unknown} -x"
13+
if got, want := Render(msg, FlagName), "set -max-queries or -force; (-t, -hit-rate) {unknown} -x"; got != want {
14+
t.Errorf("Render = %q, want %q", got, want)
15+
}
16+
if got := Render("no tokens", FlagName); got != "no tokens" {
17+
t.Errorf("Render changed a message without tokens: %q", got)
18+
}
19+
for _, s := range Settings {
20+
if FlagName(s) == "" {
21+
t.Errorf("setting %q has no flag name", s)
22+
}
23+
}
24+
}
25+
26+
// TestEngineMessagesUseSettingTokens covers #100: no string literal in the
27+
// engine names a command-line flag, and every token one uses is a Setting.
28+
func TestEngineMessagesUseSettingTokens(t *testing.T) {
29+
literal := regexp.MustCompile(`"(?:[^"\\\n]|\\.)*"`)
30+
flag := regexp.MustCompile(`(?:^|[\s("])-(?:t|timeout|attempts|hit-rate|depth|rate|max-queries|exclude|recursive|force|no-abort|dns-server|type)\b`)
31+
token := regexp.MustCompile(`\{([a-z_]+)\}`)
32+
known := map[string]bool{}
33+
for _, s := range Settings {
34+
known[string(s)] = true
35+
}
36+
files, err := filepath.Glob("*.go")
37+
if err != nil {
38+
t.Fatal(err)
39+
}
40+
for _, f := range files {
41+
// settings.go is where the CLI's flag names live (FlagName).
42+
if strings.HasSuffix(f, "_test.go") || f == "settings.go" {
43+
continue
44+
}
45+
data, err := os.ReadFile(f)
46+
if err != nil {
47+
t.Fatal(err)
48+
}
49+
for _, lit := range literal.FindAllString(string(data), -1) {
50+
if flag.MatchString(lit) {
51+
t.Errorf("%s: message names a flag: %s", f, lit)
52+
}
53+
for _, m := range token.FindAllStringSubmatch(lit, -1) {
54+
if !known[m[1]] {
55+
t.Errorf("%s: token %s is not a Setting", f, m[0])
56+
}
57+
}
58+
}
59+
}
60+
}

‎internal/scan/verdict.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ func (s Stats) Verdict(interrupted bool) (verdict, reason string) {
4242
case fails > 0 && fails*100 >= processed*degradedFailPercent:
4343
return VerdictDegraded, detail
4444
case s.Skipped > 0:
45-
return VerdictDegraded, fmt.Sprintf("-max-queries reached; %d candidates not tested", s.Skipped)
45+
return VerdictDegraded, fmt.Sprintf("{max_queries} reached; %d candidates not tested", s.Skipped)
4646
case fails > 0:
4747
return VerdictComplete, detail + ", under 1%"
4848
}

‎internal/tui/form.go‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -461,7 +461,7 @@ func (m *formModel) validate() (formValues, string) {
461461
force: m.toggles[1],
462462
}
463463
if err := v.options(nil, 0).Validate(); err != nil {
464-
return formValues{}, err.Error()
464+
return formValues{}, scan.Render(err.Error(), settingLabel)
465465
}
466466
return v, ""
467467
}
@@ -490,6 +490,22 @@ func (v formValues) options(entries []string, seed uint64) scan.Options {
490490
}
491491
}
492492

493+
// settingLabel names an engine setting as its form field (#100).
494+
func settingLabel(s scan.Setting) string {
495+
return map[scan.Setting]string{
496+
scan.SettingConcurrency: "Concurrency",
497+
scan.SettingTimeout: "Timeout (ms)",
498+
scan.SettingAttempts: "Attempts",
499+
scan.SettingHitRate: "Hit Rate (%)",
500+
scan.SettingDepth: "Depth",
501+
scan.SettingRate: "Rate (qps)",
502+
scan.SettingMaxQueries: "Max Names",
503+
scan.SettingExclude: "Exclude",
504+
scan.SettingRecursive: "Recursive",
505+
scan.SettingForce: "Force",
506+
}[s]
507+
}
508+
493509
type formValues struct {
494510
domain string
495511
wordlist string

0 commit comments

Comments
 (0)