Skip to content

Commit e50737a

Browse files
TMHSDigitalclaude
andcommitted
Share passive-source fetching across CLI, TUI and library (#355)
The CLI's passiveNames, the TUI's fetchSources and pkg/subenum's withSourceNames each had their own copy of the "ask every source at once, sort a Truncated from an error, keep the names" loop. It now lives once in internal/passive: Gather does the fan-out, FetchAll runs it over the built-in sources, and Lookup is the shared result (the CLI's targetSource is an alias, the TUI's sourceLookup embeds it). passive.UserAgent and passive.AddedLine replace the three hand-built User-Agent strings and the two copies of the "N names under T, M of them new candidates" line. Output is unchanged, including the CLI's and TUI's differently worded failure notes; pkg/subenum's API is unchanged. Fixes #355 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 80acb01 commit e50737a

12 files changed

Lines changed: 195 additions & 123 deletions

File tree

‎docs/ARCHITECTURE.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ Every package under `internal/` and `pkg/`, summarized from its `// Package` com
3939
| `internal/diff` | Compares two runs' results: new and missing names, changed records (shared by `-diff` and `pkg/subenum`'s `Diff`) |
4040
| `internal/cliargs` | Parses command lines whose flags may follow positional arguments, shared by subenum and wordlist-gen |
4141
| `internal/ct` | Looks up subdomain names in Certificate Transparency logs through crt.sh |
42-
| `internal/passive` | The `Source` interface behind `-sources`, the source registry, the merge of source names into candidates (shared by the CLI and `pkg/subenum`), and the Wayback Machine source |
42+
| `internal/passive` | The `Source` interface behind `-sources`, the source registry, the fan-out that asks every source at once and the merge of source names into candidates (shared by the CLI, the TUI and `pkg/subenum`), and the Wayback Machine source |
4343
| `internal/axfr` | Zone transfer attempts and the DNSSEC denial probe within fixed bounds (shared by `-axfr` and `pkg/subenum`'s `ProbeZone`) |
4444
| `internal/labzone` | Parses `-simulate-zone` scenario files for lab mode |
4545
| `internal/mcp` | Minimal Model Context Protocol server (JSON-RPC over stdio, tools only) behind `subenum mcp` |
@@ -103,6 +103,7 @@ internal/candidates/candidates.go - Set (New, Add, SourcesOf), RelativeSeeds, Pe
103103
internal/diff/diff.go - Name, RecordsChanged: the comparison behind -diff-records and subenum.Diff
104104
internal/ct/ct.go - Client.Names: crt.sh lookup
105105
internal/passive/passive.go - Source, Known, ParseList, New: the -sources registry; Merge: source names into candidates
106+
internal/passive/fetch.go - Gather, FetchAll, Lookup: the source fan-out the CLI, TUI and pkg/subenum share
106107
internal/passive/wayback.go - Wayback.Names: hostnames from the Wayback Machine's CDX index
107108
internal/mcp/mcp.go - Server.Serve: MCP over stdio (initialize, ping, tools/list, tools/call, cancellation)
108109
pkg/subenum/sources.go - Source, CertificateTransparency, WaybackMachine: Config.Sources
@@ -341,7 +342,7 @@ With `-permute` (or `-seeds`, which implies it), each target that finished gets
341342

342343
### 5.5. Certificate Transparency Seeding
343344

344-
With `-ct`, `ct.Client.Names` makes one HTTPS request per target to crt.sh (no API key) and returns the names its certificates cover, relative to the target. `passiveNames` gathers the names, and `passive.Merge` appends those not already in the wordlist after the wordlist entries, so wordlist resume positions stay put. They are only candidates and are resolved like any other; those that resolve also seed `-permute`. A failed lookup is a warning, not a failed scan. A resumed run reuses the saved CT names so its candidate list is the same.
345+
With `-ct`, `ct.Client.Names` makes one HTTPS request per target to crt.sh (no API key) and returns the names its certificates cover, relative to the target. `passiveNames` gathers the names through `passive.FetchAll`, and `passive.Merge` appends those not already in the wordlist after the wordlist entries, so wordlist resume positions stay put. They are only candidates and are resolved like any other; those that resolve also seed `-permute`. A failed lookup is a warning, not a failed scan. A resumed run reuses the saved CT names so its candidate list is the same.
345346

346347
### 5.6. Lab Mode
347348

‎internal/cli/ct.go‎

Lines changed: 15 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -2,23 +2,13 @@ package cli
22

33
import (
44
"context"
5-
"errors"
6-
"sync"
75

86
"github.com/TMHSDigital/subenum/internal/output"
97
"github.com/TMHSDigital/subenum/internal/passive"
108
)
119

1210
// targetSource is one passive source's lookup for a target (#130, #193).
13-
type targetSource struct {
14-
source string // -sources name: ct, wayback
15-
names []string // relative to the target
16-
fetched bool // the lookup succeeded (names may still be empty)
17-
err string
18-
// truncated says why a source that succeeded stopped at one of its
19-
// limits, so some hosts may be missing (#272).
20-
truncated string
21-
}
11+
type targetSource = passive.Lookup
2212

2313
// passiveNames asks every source for target's names at once (#271): the
2414
// ones a resumed run saved, so its candidate list matches the interrupted
@@ -30,47 +20,34 @@ func passiveNames(ctx context.Context, sources []string, target string, saved *r
3020
return nil
3121
}
3222
opts := passive.Options{
33-
UserAgent: ProgramName + "/" + resolveVersion() + " (+https://github.com/TMHSDigital/subenum)",
23+
UserAgent: passive.UserAgent(ProgramName + "/" + resolveVersion()),
3424
BaseURLs: baseURLs,
3525
}
3626
res := make([]targetSource, len(sources))
37-
var wg sync.WaitGroup
27+
var fetch []string // the sources to ask (ParseList admitted only known names)
28+
var at []int // their places in res
3829
for i, name := range sources {
39-
res[i].source = name
30+
res[i].Source = name
4031
if names, ok := saved.sourceNames(name); ok {
41-
res[i].names, res[i].fetched = names, true
32+
res[i].Names, res[i].Fetched = names, true
4233
continue
4334
}
4435
if saved != nil && saved.Done {
4536
// The target is not scanned again, so its candidates are not
4637
// needed: no lookup (#315).
4738
continue
4839
}
49-
src, err := passive.New(name, opts)
50-
if err != nil { // ParseList admitted only known names
51-
res[i].err = err.Error()
52-
continue
53-
}
54-
wg.Go(func() {
55-
names, err := src.Names(ctx, target)
56-
var tr *passive.Truncated
57-
switch {
58-
case errors.As(err, &tr):
59-
res[i].truncated = tr.Error()
60-
case err != nil:
61-
res[i].err = err.Error()
62-
return
63-
}
64-
res[i].names, res[i].fetched = names, true
65-
})
40+
fetch, at = append(fetch, name), append(at, i)
41+
}
42+
for j, l := range passive.FetchAll(ctx, fetch, opts, target) {
43+
res[at[j]] = l
6644
}
67-
wg.Wait()
6845
for _, r := range res {
6946
switch {
70-
case !r.fetched && r.err != "":
71-
out.Info("Warning: %s; scanning %s without %s names", r.err, target, passive.Labels[r.source])
72-
case r.truncated != "":
73-
out.Info("Note: %s (%s, %d names)", r.truncated, target, len(r.names))
47+
case !r.Fetched && r.Err != "":
48+
out.Info("Warning: %s; scanning %s without %s names", r.Err, target, passive.Labels[r.Source])
49+
case r.Truncated != "":
50+
out.Info("Note: %s (%s, %d names)", r.Truncated, target, len(r.Names))
7451
}
7552
}
7653
return res
@@ -94,7 +71,7 @@ func (t *resumeTarget) sourceNames(source string) ([]string, bool) {
9471
// sourceByName returns the lookup of one source, if it ran.
9572
func sourceByName(sources []targetSource, name string) targetSource {
9673
for _, s := range sources {
97-
if s.source == name {
74+
if s.Source == name {
9875
return s
9976
}
10077
}

‎internal/cli/resume.go‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -488,10 +488,10 @@ func savedSources(sources []targetSource, scanned bool) map[string][]string {
488488
saved := make(map[string][]string, len(sources))
489489
for _, src := range sources {
490490
switch {
491-
case src.fetched:
492-
saved[src.source] = src.names
491+
case src.Fetched:
492+
saved[src.Source] = src.Names
493493
case scanned:
494-
saved[src.source] = []string{}
494+
saved[src.Source] = []string{}
495495
}
496496
}
497497
if len(saved) == 0 {
@@ -535,7 +535,7 @@ func saveResumeState(s *session) bool {
535535
// final and the resumed run tries it again (#299). A transfer the
536536
// earlier state had already settled stays settled.
537537
scanned := res.done || (saved != nil && saved.RootDone > 0)
538-
t := resumeTarget{Domain: domain, Results: s.runs[i].results(), Entries: s.entryDigests[i], CT: ct.names, CTFetched: ct.fetched,
538+
t := resumeTarget{Domain: domain, Results: s.runs[i].results(), Entries: s.entryDigests[i], CT: ct.Names, CTFetched: ct.Fetched,
539539
Sources: savedSources(res.sources, scanned)}
540540
if res.axfr.done && (scanned || (saved != nil && saved.AXFRDone)) {
541541
t.AXFR, t.AXFRServers, t.AXFRDone, t.Denial = res.axfr.names, res.axfr.allowed, true, string(res.axfr.denial)

‎internal/cli/resume_test.go‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -839,8 +839,8 @@ func TestSaveResumeStateKeepsFailedSources(t *testing.T) {
839839
status: []report.Status{report.StatusInterrupted},
840840
entryDigests: []string{"d1"},
841841
results: []targetResult{{done: true, sources: []targetSource{
842-
{source: "ct", err: "crt.sh: 502 Bad Gateway"},
843-
{source: "wayback", names: []string{"old-shop"}, fetched: true},
842+
{Source: "ct", Err: "crt.sh: 502 Bad Gateway"},
843+
{Source: "wayback", Names: []string{"old-shop"}, Fetched: true},
844844
}}},
845845
runs: []resultLog{{}},
846846
})
@@ -870,8 +870,8 @@ func TestSaveResumeStateKeepsFailedSources(t *testing.T) {
870870
// this run or the one it resumed, it stays as saved (#237).
871871
func TestSaveResumeStateRetriesLookupsCutShort(t *testing.T) {
872872
sources := []targetSource{
873-
{source: "ct", err: "crt.sh: context canceled"},
874-
{source: "wayback", names: []string{"old-shop"}, fetched: true},
873+
{Source: "ct", Err: "crt.sh: context canceled"},
874+
{Source: "wayback", Names: []string{"old-shop"}, Fetched: true},
875875
}
876876
axfr := targetAXFR{done: true}
877877
for name, tc := range map[string]struct {

‎internal/cli/session.go‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -685,9 +685,9 @@ func (s *session) scanOneTarget(ctx context.Context, i int, target string) (next
685685
s.cands, s.foundBy = cands, map[string]int{}
686686
sourceInfo := passiveNames(ctx, s.in.sources, target, saved, out, s.a.sourceURLs)
687687
for _, src := range sourceInfo {
688-
added := cands.Add(src.source, src.names)
689-
if src.fetched {
690-
out.Info("%s: %d names under %s, %d of them new candidates", passive.Labels[src.source], len(src.names), target, added)
688+
added := cands.Add(src.Source, src.Names)
689+
if src.Fetched {
690+
out.Info("%s", passive.AddedLine(passive.Labels[src.Source], len(src.Names), target, added))
691691
}
692692
}
693693
var axfrInfo targetAXFR
@@ -697,7 +697,7 @@ func (s *session) scanOneTarget(ctx context.Context, i int, target string) (next
697697
axfrInfo = zoneTransfer(ctx, s.f, s.a.transferPort(), target, saved, out)
698698
added := cands.Add(candidates.AXFR, axfrInfo.names)
699699
if len(axfrInfo.allowed) > 0 {
700-
out.Info("Zone transfer: %d names under %s, %d of them new candidates", len(axfrInfo.names), target, added)
700+
out.Info("%s", passive.AddedLine("Zone transfer", len(axfrInfo.names), target, added))
701701
}
702702
}
703703
entries, seeds := cands.Entries(), cands.Seeds()

‎internal/cli/summary.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,9 @@ func buildSummary(s *session, elapsed time.Duration) output.Summary {
3636
func targetSummary(domain string, status report.Status, res targetResult) output.TargetSummary {
3737
t := report.Target(domain, status, res.err, res.done, res.final, scan.FlagName)
3838
ct := sourceByName(res.sources, "ct")
39-
t.CTNames, t.CTError = len(ct.names), ct.err
39+
t.CTNames, t.CTError = len(ct.Names), ct.Err
4040
for _, src := range res.sources {
41-
t.Sources = append(t.Sources, output.SourceSummary{Name: src.source, Names: len(src.names), Found: res.foundBy[src.source], Error: src.err, Truncated: src.truncated != ""})
41+
t.Sources = append(t.Sources, output.SourceSummary{Name: src.Source, Names: len(src.Names), Found: res.foundBy[src.Source], Error: src.Err, Truncated: src.Truncated != ""})
4242
}
4343
t.AXFRAllowed, t.AXFRNames, t.AXFRError = res.axfr.allowed, len(res.axfr.names), res.axfr.err
4444
t.AXFRFound = res.foundBy[candidates.AXFR]

‎internal/passive/fetch.go‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
package passive
2+
3+
import (
4+
"context"
5+
"errors"
6+
"fmt"
7+
"sync"
8+
)
9+
10+
// UserAgent is the User-Agent the sources send for product, such as
11+
// "subenum/v1.2.3" or "subenum-library" (#355).
12+
func UserAgent(product string) string {
13+
return product + " (+https://github.com/TMHSDigital/subenum)"
14+
}
15+
16+
// Lookup is one source's answer for a domain (#130, #193). The CLI, the TUI
17+
// and pkg/subenum all sort answers this way (#355).
18+
type Lookup struct {
19+
Source string // -sources name: ct, wayback
20+
Names []string // relative to the domain
21+
Fetched bool // the lookup succeeded (Names may still be empty)
22+
Err string
23+
// Truncated says why a source that succeeded stopped at one of its
24+
// limits, so some hosts may be missing (#272).
25+
Truncated string
26+
}
27+
28+
// Gather calls ask(i) for every i below n at once (#271) and sorts each
29+
// answer: names that come with a *Truncated are kept and the reason noted
30+
// (#272); any other error drops them. The results keep the order of i.
31+
func Gather(n int, ask func(i int) ([]string, error)) []Lookup {
32+
res := make([]Lookup, n)
33+
var wg sync.WaitGroup
34+
for i := range n {
35+
wg.Go(func() {
36+
names, err := ask(i)
37+
var tr *Truncated
38+
switch {
39+
case errors.As(err, &tr):
40+
res[i].Truncated = err.Error()
41+
case err != nil:
42+
res[i].Err = err.Error()
43+
return
44+
}
45+
res[i].Names, res[i].Fetched = names, true
46+
})
47+
}
48+
wg.Wait()
49+
return res
50+
}
51+
52+
// FetchAll asks the built-in sources called names for domain's names at
53+
// once, in the order of names.
54+
func FetchAll(ctx context.Context, names []string, opts Options, domain string) []Lookup {
55+
res := Gather(len(names), func(i int) ([]string, error) {
56+
src, err := New(names[i], opts)
57+
if err != nil { // callers admit only known names
58+
return nil, err
59+
}
60+
return src.Names(ctx, domain)
61+
})
62+
for i := range res {
63+
res[i].Source = names[i]
64+
}
65+
return res
66+
}
67+
68+
// AddedLine reports what a source proposed for target and how many of its
69+
// names were not candidates already; the CLI and the TUI print the same line.
70+
func AddedLine(label string, names int, target string, added int) string {
71+
return fmt.Sprintf("%s: %d names under %s, %d of them new candidates", label, names, target, added)
72+
}

‎internal/passive/fetch_test.go‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package passive
2+
3+
import (
4+
"errors"
5+
"fmt"
6+
"reflect"
7+
"testing"
8+
)
9+
10+
// TestGather covers #355: the one fan-out the CLI, the TUI and pkg/subenum
11+
// share sorts every answer the same way, in the order asked.
12+
func TestGather(t *testing.T) {
13+
tr := &Truncated{Source: "ct", Why: "read limit"}
14+
answers := []struct {
15+
names []string
16+
err error
17+
}{
18+
{[]string{"a", "b"}, nil},
19+
{[]string{"c"}, tr},
20+
{[]string{"ignored"}, errors.New("502 Bad Gateway")},
21+
{nil, nil},
22+
{[]string{"d"}, fmt.Errorf("wrapped: %w", tr)},
23+
}
24+
got := Gather(len(answers), func(i int) ([]string, error) {
25+
return answers[i].names, answers[i].err
26+
})
27+
want := []Lookup{
28+
{Names: []string{"a", "b"}, Fetched: true},
29+
{Names: []string{"c"}, Fetched: true, Truncated: tr.Error()},
30+
{Err: "502 Bad Gateway"},
31+
{Fetched: true},
32+
{Names: []string{"d"}, Fetched: true, Truncated: "wrapped: " + tr.Error()},
33+
}
34+
if !reflect.DeepEqual(got, want) {
35+
t.Errorf("Gather = %+v\nwant %+v", got, want)
36+
}
37+
if got := Gather(0, nil); len(got) != 0 {
38+
t.Errorf("Gather(0) = %v, want none", got)
39+
}
40+
}
41+
42+
func TestFetchAllUnknownSource(t *testing.T) {
43+
got := FetchAll(t.Context(), []string{"nope"}, Options{}, "example.com")
44+
if len(got) != 1 || got[0].Source != "nope" || got[0].Fetched || got[0].Err != `unknown source "nope"` {
45+
t.Errorf("FetchAll = %+v, want one failed lookup named nope", got)
46+
}
47+
}
48+
49+
func TestMessages(t *testing.T) {
50+
if got, want := UserAgent("subenum/v1.0.0"), "subenum/v1.0.0 (+https://github.com/TMHSDigital/subenum)"; got != want {
51+
t.Errorf("UserAgent = %q, want %q", got, want)
52+
}
53+
if got, want := AddedLine("Wayback Machine", 2, "example.com", 1), "Wayback Machine: 2 names under example.com, 1 of them new candidates"; got != want {
54+
t.Errorf("AddedLine = %q, want %q", got, want)
55+
}
56+
}

‎internal/tui/model.go‎

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,7 @@ func loadWordlistCmd(vals formValues, o Options) tea.Cmd {
199199
// The same candidate set as the command line's (#347).
200200
msg.cands = candidates.New(vals.Domain, entries, nil)
201201
for i := range msg.lookups {
202-
msg.lookups[i].added = msg.cands.Add(msg.lookups[i].name, msg.lookups[i].names)
202+
msg.lookups[i].added = msg.cands.Add(msg.lookups[i].Source, msg.lookups[i].Names)
203203
}
204204
msg.entries = msg.cands.Entries()
205205
}
@@ -291,15 +291,15 @@ func (m Model) beginScan(loaded wordlistLoadedMsg) (tea.Model, tea.Cmd) {
291291
// Same lines as the CLI's: what each source gave, or why the scan runs
292292
// without its names (#274).
293293
for _, l := range m.lookups {
294-
label := passive.Labels[l.name]
294+
label := passive.Labels[l.Source]
295295
switch {
296-
case !l.fetched:
297-
m.scanView.addMessage(wildcardStyle.Render(fmt.Sprintf("⚠ %s; scanning without %s names", l.err, label)))
296+
case !l.Fetched:
297+
m.scanView.addMessage(wildcardStyle.Render(fmt.Sprintf("⚠ %s; scanning without %s names", l.Err, label)))
298298
continue
299-
case l.truncated != "":
300-
m.scanView.addMessage(wildcardStyle.Render("⚠ " + l.truncated))
299+
case l.Truncated != "":
300+
m.scanView.addMessage(wildcardStyle.Render("⚠ " + l.Truncated))
301301
}
302-
m.scanView.addMessage(dimStyle.Render(fmt.Sprintf("%s: %d names under %s, %d of them new candidates", label, len(l.names), vals.Domain, l.added)))
302+
m.scanView.addMessage(dimStyle.Render(passive.AddedLine(label, len(l.Names), vals.Domain, l.added)))
303303
}
304304

305305
// Same notice as the CLI's, so the TUI user knows which list ran (#288).
@@ -650,9 +650,9 @@ func (m *Model) summary(final scan.Event) output.Summary {
650650
}
651651
t := report.Target(m.vals.Domain, status, "", true, final, settingLabel)
652652
for _, l := range m.lookups {
653-
t.Sources = append(t.Sources, output.SourceSummary{Name: l.name, Names: len(l.names), Found: m.foundBy[l.name], Error: l.err, Truncated: l.truncated != ""})
654-
if l.name == "ct" {
655-
t.CTNames, t.CTError = len(l.names), l.err
653+
t.Sources = append(t.Sources, output.SourceSummary{Name: l.Source, Names: len(l.Names), Found: m.foundBy[l.Source], Error: l.Err, Truncated: l.Truncated != ""})
654+
if l.Source == "ct" {
655+
t.CTNames, t.CTError = len(l.Names), l.Err
656656
}
657657
}
658658
m.scanView.perm.summarize(&t, m.scanView.aborted, m.scanView.errText)

0 commit comments

Comments
 (0)