Harden scan robustness and tests

This commit is contained in:
ZacharyZcR
2026-06-13 07:55:37 +08:00
parent 1595c92aed
commit 15a7670ba2
100 changed files with 4483 additions and 412 deletions
+63
View File
@@ -2,6 +2,7 @@ package parsers
import (
"context"
"errors"
"os"
"reflect"
"strings"
@@ -103,3 +104,65 @@ func TestHostIteratorReadsLongHostFileLine(t *testing.T) {
t.Fatalf("batch = %#v, want long host", batch)
}
}
func TestMultiHostSourceAndMatcherCIDR(t *testing.T) {
src := &multiHostSource{sources: []hostSource{
&singleHostSource{host: "192.168.1.1"},
&singleHostSource{host: "192.168.1.2"},
}}
host, ok, err := src.Next()
if err != nil || !ok || host != "192.168.1.1" {
t.Fatalf("first Next = %q/%v/%v", host, ok, err)
}
host, ok, err = src.Next()
if err != nil || !ok || host != "192.168.1.2" {
t.Fatalf("second Next = %q/%v/%v", host, ok, err)
}
host, ok, err = src.Next()
if err != nil || ok || host != "" {
t.Fatalf("exhausted Next = %q/%v/%v", host, ok, err)
}
if err := src.Close(); err != nil {
t.Fatalf("Close error = %v", err)
}
matcher := newHostMatcher()
if err := matcher.add("192.168.1.0/30,example.com"); err != nil {
t.Fatalf("matcher add error = %v", err)
}
if !matcher.match("192.168.1.1") || !matcher.match("192.168.1.2") || !matcher.match("example.com") {
t.Fatal("matcher should match CIDR hosts and exact host")
}
if matcher.match("192.168.1.3") || matcher.match("nope.example") {
t.Fatal("matcher matched hosts outside its rules")
}
if err := matcher.add("2001:db8::/126"); err == nil {
t.Fatal("IPv6 CIDR should be rejected by IPv4-only matcher")
}
}
func TestCloseHostSourcesIgnoresCloseErrors(t *testing.T) {
first := &closeTrackingSource{err: errors.New("close failed")}
second := &closeTrackingSource{}
closeHostSources([]hostSource{first, second})
if !first.closed || !second.closed {
t.Fatalf("sources closed = %v/%v, want both true", first.closed, second.closed)
}
}
type closeTrackingSource struct {
closed bool
err error
}
func (s *closeTrackingSource) Next() (string, bool, error) {
return "", false, nil
}
func (s *closeTrackingSource) Close() error {
s.closed = true
return s.err
}