Accept empty RDAP 404 bodies and clean up domain audit

Co-authored-by: Loyalsoldier <10487845+Loyalsoldier@users.noreply.github.com>
This commit is contained in:
copilot-swe-agent[bot]andLoyalsoldier authored and GitHub committed 2026-11-07 15:08:33 +00:00
1 parent 050dc112d8
commit c15b37cac7
10 files changed
+314 -281

No files matched your search

+40 -200
View File
@@ -2,34 +2,41 @@ package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
)
const bootstrapURL = "https://data.iana.org/rdap/dns.json"
const (
bootstrapURL = "https://data.iana.org/rdap/dns.json"
maxJSONBytes = 2 * 1024 * 1024
statusRegistered = "registered"
statusPossiblyUnregistered = "possibly_unregistered"
statusPossiblyReregistered = "possibly_reregistered"
statusUnknown = "unknown"
statusUnsupported = "unsupported"
)
var errRedirectPolicy = errors.New("redirect refused")
// DNS RR type and response codes used by the JSON DNS-over-HTTPS APIs.
const (
dnsTypeNS = 2
dnsRcodeNoError = 0
dnsRcodeNXDomain = 3
)
type checkResult struct {
*domainEntry
Status string `json:"status"`
RDAPURL string `json:"rdap_url,omitempty"`
HTTPStatus int `json:"http_status,omitempty"`
Registered time.Time `json:"registered"`
DNS []string `json:"dns,omitempty"`
RegistryHold []string `json:"registry_status,omitempty"`
Detail string `json:"detail,omitempty"`
Status string `json:"status"`
RDAPURL string `json:"rdap_url,omitempty"`
HTTPStatus int `json:"http_status,omitempty"`
Registered time.Time `json:"registered,omitzero"`
DNS []string `json:"dns,omitempty"`
RegistryStatus []string `json:"registry_status,omitempty"`
Detail string `json:"detail,omitempty"`
}
type rdapResponse struct {
@@ -43,38 +50,6 @@ type rdapResponse struct {
} `json:"events"`
}
type hostLimiter struct {
mu sync.Mutex
next time.Time
}
func (limiter *hostLimiter) wait(ctx context.Context, interval time.Duration) error {
for {
if err := ctx.Err(); err != nil {
return err
}
limiter.mu.Lock()
delay := time.Until(limiter.next)
if delay <= 0 {
limiter.next = time.Now().Add(interval)
limiter.mu.Unlock()
return nil
}
limiter.mu.Unlock()
if err := pause(ctx, delay); err != nil {
return err
}
}
}
func (limiter *hostLimiter) deferUntil(until time.Time) {
limiter.mu.Lock()
defer limiter.mu.Unlock()
if until.After(limiter.next) {
limiter.next = until
}
}
type checker struct {
client *http.Client
services map[string]string
@@ -83,11 +58,6 @@ type checker struct {
resolvers []string
}
func (checker *checker) limiterFor(host string) *hostLimiter {
value, _ := checker.limiters.LoadOrStore(host, &hostLimiter{})
return value.(*hostLimiter)
}
func newChecker(ctx context.Context, client *http.Client, interval time.Duration) (*checker, error) {
result := &checker{
client: client, interval: interval, services: make(map[string]string),
@@ -96,7 +66,7 @@ func newChecker(ctx context.Context, client *http.Client, interval time.Duration
var bootstrap struct {
Services [][][]string `json:"services"`
}
status, err := result.getJSON(ctx, bootstrapURL, &bootstrap)
status, err := result.getJSON(ctx, bootstrapURL, acceptJSON, &bootstrap)
if err != nil {
return nil, err
}
@@ -124,140 +94,6 @@ func newChecker(ctx context.Context, client *http.Client, interval time.Duration
return result, nil
}
func pause(ctx context.Context, delay time.Duration) error {
timer := time.NewTimer(delay)
defer timer.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-timer.C:
return nil
}
}
func retryDelay(value string, attempt int) time.Duration {
if seconds, err := strconv.Atoi(value); err == nil && seconds >= 0 {
return time.Duration(seconds) * time.Second
}
if date, err := http.ParseTime(value); err == nil && time.Until(date) > 0 {
return time.Until(date)
}
return time.Duration(1<<attempt) * time.Second
}
func (checker *checker) get(ctx context.Context, endpoint string) (*http.Response, error) {
request, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return nil, err
}
accept := "application/rdap+json, application/json"
if request.URL.Query().Get("type") == "NS" {
accept = "application/dns-json"
}
client := *checker.client
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
request.Header.Set("Accept", accept)
request.Header.Set("User-Agent", "domain-list-community-domain-audit/1.0 (+https://github.com/v2fly/domain-list-community)")
var previous []*http.Request
for {
// Start each network timeout only after this hop's pacing delay has elapsed.
if err := checker.limiterFor(request.URL.Host).wait(ctx, checker.interval); err != nil {
return nil, err
}
response, err := client.Do(request)
if err != nil {
return nil, err
}
if response.Request == nil {
response.Request = request
}
switch response.StatusCode {
case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect:
if response.Header.Get("Location") == "" {
return response, nil
}
default:
return response, nil
}
location, err := response.Location()
if err != nil {
_ = response.Body.Close()
return nil, fmt.Errorf("%w: %v", errRedirectPolicy, err)
}
previous = append(previous, request)
if len(previous) >= 10 || location.Scheme != "https" {
_ = response.Body.Close()
return nil, fmt.Errorf("%w: excessive redirects or an insecure redirect", errRedirectPolicy)
}
// Create fresh headers so cookies or sensitive headers cannot leak across hosts.
next, err := http.NewRequestWithContext(ctx, http.MethodGet, location.String(), nil)
if err != nil {
_ = response.Body.Close()
return nil, err
}
next.Header.Set("Accept", accept)
next.Header.Set("User-Agent", request.Header.Get("User-Agent"))
if checker.client.CheckRedirect != nil {
if err := checker.client.CheckRedirect(next, previous); err != nil {
if errors.Is(err, http.ErrUseLastResponse) {
return response, nil
}
_ = response.Body.Close()
return nil, fmt.Errorf("%w: %v", errRedirectPolicy, err)
}
}
_ = response.Body.Close()
request = next
}
}
func (checker *checker) getJSON(ctx context.Context, endpoint string, target any) (int, error) {
parsed, err := url.Parse(endpoint)
if err != nil {
return 0, err
}
limiter := checker.limiterFor(parsed.Host)
for attempt := 0; attempt < 3; attempt++ {
response, requestErr := checker.get(ctx, endpoint)
if requestErr != nil {
if attempt < 2 && ctx.Err() == nil && !errors.Is(requestErr, errRedirectPolicy) {
limiter.deferUntil(time.Now().Add(retryDelay("", attempt)))
continue
}
return 0, requestErr
}
status := response.StatusCode
if status == http.StatusTooManyRequests || status >= 500 {
_ = response.Body.Close()
until := time.Now().Add(retryDelay(response.Header.Get("Retry-After"), attempt))
limiter.deferUntil(until)
checker.limiterFor(response.Request.URL.Host).deferUntil(until)
if attempt < 2 {
continue
}
return status, fmt.Errorf("HTTP %d after three attempts", status)
}
// A bare proxy/web-server 404 is not evidence of a missing RDAP object.
if status != http.StatusOK && status != http.StatusNotFound {
_ = response.Body.Close()
return status, fmt.Errorf("HTTP %d", status)
}
body, readErr := io.ReadAll(io.LimitReader(response.Body, maxJSONBytes+1))
closeErr := response.Body.Close()
if readErr != nil {
return status, fmt.Errorf("read JSON response: %w", readErr)
}
if closeErr != nil {
return status, fmt.Errorf("close JSON response: %w", closeErr)
}
if len(body) > maxJSONBytes {
return status, fmt.Errorf("JSON response exceeds %d bytes", maxJSONBytes)
}
return status, json.Unmarshal(body, target)
}
return 0, fmt.Errorf("request attempts exhausted")
}
func (checker *checker) rdapURL(domain string) string {
for suffix := domain; suffix != ""; {
if endpoint := checker.services[suffix]; endpoint != "" {
@@ -281,17 +117,17 @@ func (checker *checker) dnsStatus(ctx context.Context, resolver, domain string)
Type int `json:"type"`
} `json:"Question"`
}
status, err := checker.getJSON(ctx, endpoint, &response)
status, err := checker.getJSON(ctx, endpoint, acceptDNS, &response)
if err != nil || status != http.StatusOK || response.Status == nil {
return "unknown"
}
if len(response.Question) != 1 || !strings.EqualFold(strings.TrimSuffix(response.Question[0].Name, "."), domain) || response.Question[0].Type != 2 {
if len(response.Question) != 1 || !strings.EqualFold(strings.TrimSuffix(response.Question[0].Name, "."), domain) || response.Question[0].Type != dnsTypeNS {
return "unknown"
}
switch *response.Status {
case 0:
case dnsRcodeNoError:
return "NOERROR"
case 3:
case dnsRcodeNXDomain:
return "NXDOMAIN"
default:
return fmt.Sprintf("RCODE_%d", *response.Status)
@@ -299,30 +135,33 @@ func (checker *checker) dnsStatus(ctx context.Context, resolver, domain string)
}
func (checker *checker) check(ctx context.Context, entry *domainEntry) checkResult {
result := checkResult{domainEntry: entry, Status: "unknown"}
result := checkResult{domainEntry: entry, Status: statusUnknown}
result.RDAPURL = checker.rdapURL(entry.Domain)
if result.RDAPURL == "" {
result.Status = "unsupported"
result.Status = statusUnsupported
result.Detail = "No HTTPS RDAP service in IANA bootstrap"
return result
}
var response rdapResponse
status, err := checker.getJSON(ctx, result.RDAPURL, &response)
status, err := checker.getJSON(ctx, result.RDAPURL, acceptRDAP, &response)
result.HTTPStatus = status
if err != nil {
// Some registries, including Verisign for .com and .net, answer 404 with an empty body.
emptyNotFound := status == http.StatusNotFound && errors.Is(err, errEmptyBody)
if err != nil && !emptyNotFound {
result.Detail = err.Error()
return result
}
if status == http.StatusNotFound {
if response.ErrorCode != http.StatusNotFound {
result.Detail = "HTTP 404 without an RDAP errorCode of 404"
// A non-RDAP 404 body, such as a proxy error page, is not evidence of a missing domain.
if !emptyNotFound && response.ErrorCode != http.StatusNotFound {
result.Detail = "HTTP 404 with a body that is not an RDAP errorCode of 404"
return result
}
for _, resolver := range checker.resolvers {
result.DNS = append(result.DNS, checker.dnsStatus(ctx, resolver, entry.Domain))
}
if len(result.DNS) == 2 && result.DNS[0] == "NXDOMAIN" && result.DNS[1] == "NXDOMAIN" {
result.Status = "possibly_unregistered"
result.Status = statusPossiblyUnregistered
result.Detail = "Registry RDAP 404 and NXDOMAIN from two resolvers; review before removal"
} else {
result.Detail = "Registry RDAP 404 without two NXDOMAIN confirmations"
@@ -333,15 +172,16 @@ func (checker *checker) check(ctx context.Context, entry *domainEntry) checkResu
result.Detail = "RDAP response does not identify the queried domain"
return result
}
result.Status = "registered"
result.RegistryHold = response.Status
result.Status = statusRegistered
result.RegistryStatus = response.Status
for _, event := range response.Events {
// Ignore "reregistration": some registries, such as Google Registry, use it for renewals.
if event.Action != "registration" {
continue
}
registered, err := time.Parse(time.RFC3339, event.Date)
if err != nil {
result.Status = "unknown"
result.Status = statusUnknown
result.Detail = "Invalid RDAP registration event date"
return result
}
@@ -351,7 +191,7 @@ func (checker *checker) check(ctx context.Context, entry *domainEntry) checkResu
}
// Registry timestamps and commit clocks may differ; require a full day of separation.
if !entry.FirstSeen.IsZero() && result.Registered.After(entry.FirstSeen.Add(24*time.Hour)) {
result.Status = "possibly_reregistered"
result.Status = statusPossiblyReregistered
result.Detail = "Registration postdates earliest rule history by more than 24 hours; ownership needs manual verification"
}
return result
+15 -10
View File
@@ -16,21 +16,25 @@ func TestCheckRegistryAndDNS(t *testing.T) {
firstSeen := time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC)
registered := `{"objectClassName":"domain","ldhName":"example.com","events":[{"eventAction":"registration","eventDate":"2000-01-01T00:00:00Z"}]}`
testCases := []struct {
name string
rdapStatus int
rdapBody string
dnsBodies []string
wantStatus string
wantDNS []string
wantHold []string
name string
rdapStatus int
rdapBody string
dnsBodies []string
wantStatus string
wantDNS []string
wantRegistry []string
}{
{name: "registered", rdapStatus: 200, rdapBody: registered, wantStatus: "registered"},
{name: "registered on hold", rdapStatus: 200, rdapBody: `{"objectClassName":"domain","ldhName":"example.com","status":["server hold"]}`, wantStatus: "registered", wantHold: []string{"server hold"}},
{name: "registered on hold", rdapStatus: 200, rdapBody: `{"objectClassName":"domain","ldhName":"example.com","status":["server hold"]}`, wantStatus: "registered", wantRegistry: []string{"server hold"}},
{name: "two NXDOMAIN confirmations", rdapStatus: 404, rdapBody: `{"errorCode":404}`, dnsBodies: []string{dnsResponse(3), dnsResponse(3)}, wantStatus: "possibly_unregistered", wantDNS: []string{"NXDOMAIN", "NXDOMAIN"}},
{name: "NOERROR without answers is not NXDOMAIN", rdapStatus: 404, rdapBody: `{"errorCode":404}`, dnsBodies: []string{dnsResponse(3), dnsResponse(0)}, wantStatus: "unknown", wantDNS: []string{"NXDOMAIN", "NOERROR"}},
{name: "SERVFAIL is not NXDOMAIN", rdapStatus: 404, rdapBody: `{"errorCode":404}`, dnsBodies: []string{dnsResponse(2), dnsResponse(3)}, wantStatus: "unknown", wantDNS: []string{"RCODE_2", "NXDOMAIN"}},
{name: "missing DNS status", rdapStatus: 404, rdapBody: `{"errorCode":404}`, dnsBodies: []string{`{"Question":[{"name":"example.com.","type":2}]}`, dnsResponse(3)}, wantStatus: "unknown", wantDNS: []string{"unknown", "NXDOMAIN"}},
{name: "different DNS question", rdapStatus: 404, rdapBody: `{"errorCode":404}`, dnsBodies: []string{`{"Status":3,"Question":[{"name":"other.com.","type":2}]}`, dnsResponse(3)}, wantStatus: "unknown", wantDNS: []string{"unknown", "NXDOMAIN"}},
{name: "empty 404 body with two NXDOMAIN confirmations", rdapStatus: 404, rdapBody: "", dnsBodies: []string{dnsResponse(3), dnsResponse(3)}, wantStatus: "possibly_unregistered", wantDNS: []string{"NXDOMAIN", "NXDOMAIN"}},
{name: "blank 404 body with two NXDOMAIN confirmations", rdapStatus: 404, rdapBody: "\r\n", dnsBodies: []string{dnsResponse(3), dnsResponse(3)}, wantStatus: "possibly_unregistered", wantDNS: []string{"NXDOMAIN", "NXDOMAIN"}},
{name: "empty 404 body without two NXDOMAIN confirmations", rdapStatus: 404, rdapBody: "", dnsBodies: []string{dnsResponse(3), dnsResponse(0)}, wantStatus: "unknown", wantDNS: []string{"NXDOMAIN", "NOERROR"}},
{name: "empty 200 body", rdapStatus: 200, rdapBody: "", wantStatus: "unknown"},
{name: "HTML 404", rdapStatus: 404, rdapBody: "<html>Not found</html>", wantStatus: "unknown"},
{name: "404 without RDAP error", rdapStatus: 404, rdapBody: `{}`, wantStatus: "unknown"},
{name: "RDAP error disagrees with HTTP", rdapStatus: 404, rdapBody: `{"errorCode":400}`, wantStatus: "unknown"},
@@ -39,6 +43,7 @@ func TestCheckRegistryAndDNS(t *testing.T) {
{name: "invalid registration date", rdapStatus: 200, rdapBody: `{"objectClassName":"domain","ldhName":"example.com","events":[{"eventAction":"registration","eventDate":"invalid"}]}`, wantStatus: "unknown"},
{name: "registration exactly 24 hours later", rdapStatus: 200, rdapBody: `{"objectClassName":"domain","ldhName":"example.com","events":[{"eventAction":"registration","eventDate":"2020-01-02T00:00:00Z"}]}`, wantStatus: "registered"},
{name: "registration beyond timestamp margin", rdapStatus: 200, rdapBody: `{"objectClassName":"domain","ldhName":"EXAMPLE.COM.","events":[{"eventAction":"registration","eventDate":"2020-01-02T00:00:01Z"}]}`, wantStatus: "possibly_reregistered"},
{name: "renewal reported as reregistration", rdapStatus: 200, rdapBody: `{"objectClassName":"domain","ldhName":"example.com","events":[{"eventAction":"registration","eventDate":"2000-01-01T00:00:00Z"},{"eventAction":"reregistration","eventDate":"2024-01-01T00:00:00Z"}]}`, wantStatus: "registered"},
{name: "earliest registration event", rdapStatus: 200, rdapBody: `{"objectClassName":"domain","ldhName":"example.com","events":[{"eventAction":"registration","eventDate":"2024-01-01T00:00:00Z"},{"eventAction":"registration","eventDate":"2000-01-01T00:00:00Z"}]}`, wantStatus: "registered"},
}
for _, tc := range testCases {
@@ -77,8 +82,8 @@ func TestCheckRegistryAndDNS(t *testing.T) {
if !slices.Equal(result.DNS, tc.wantDNS) {
t.Errorf("DNS evidence = %v, want %v", result.DNS, tc.wantDNS)
}
if !slices.Equal(result.RegistryHold, tc.wantHold) {
t.Errorf("registry status = %v, want %v", result.RegistryHold, tc.wantHold)
if !slices.Equal(result.RegistryStatus, tc.wantRegistry) {
t.Errorf("registry status = %v, want %v", result.RegistryStatus, tc.wantRegistry)
}
if result.HTTPStatus != tc.rdapStatus || result.RDAPURL != server.URL+"/rdap/domain/example.com" {
t.Errorf("registry evidence = HTTP %d %q, want original registry response", result.HTTPStatus, result.RDAPURL)
+7 -12
View File
@@ -6,6 +6,7 @@ import (
"fmt"
"io"
"io/fs"
"maps"
"net"
"os"
"os/exec"
@@ -27,7 +28,7 @@ type source struct {
type domainEntry struct {
Domain string `json:"domain"`
Sources []source `json:"sources"`
FirstSeen time.Time `json:"first_seen"`
FirstSeen time.Time `json:"first_seen,omitzero"`
}
type inventory struct {
@@ -183,21 +184,15 @@ func loadHistory(ctx context.Context, dataPath string, domains map[string]*domai
if err := command.Start(); err != nil {
return err
}
readErr := readHistory(pipe, domains)
if readErr != nil {
if err := readHistory(pipe, domains); err != nil {
// Report the parse failure rather than the resulting "signal: killed".
_ = command.Process.Kill()
}
if err := command.Wait(); err != nil {
_ = command.Wait()
return err
}
return readErr
return command.Wait()
}
func sortedDomains(domains map[string]*domainEntry) []string {
names := make([]string, 0, len(domains))
for name := range domains {
names = append(names, name)
}
slices.Sort(names)
return names
return slices.Sorted(maps.Keys(domains))
}
+12
View File
@@ -1,7 +1,9 @@
package main
import (
"bufio"
"context"
"errors"
"os"
"os/exec"
"path/filepath"
@@ -130,6 +132,16 @@ func TestLoadHistoryIncludesPrunedMergedBranch(t *testing.T) {
assertHistoryDate(t, domains["shared.com"], "2021-01-01T00:00:00Z")
}
func TestLoadHistoryReportsReadErrors(t *testing.T) {
repository := newHistoryRepository(t)
writeHistoryList(t, "base.com\n"+strings.Repeat("a", 5*1024*1024)+"\n")
commitHistoryList(t, repository, "2020-01-01T00:00:00Z")
err := loadHistory(context.Background(), historyDataPath, map[string]*domainEntry{"base.com": {Domain: "base.com"}})
if !errors.Is(err, bufio.ErrTooLong) {
t.Fatalf("loadHistory() error = %v, want %v", err, bufio.ErrTooLong)
}
}
func TestLoadHistoryRejectsShallowRepository(t *testing.T) {
repository := newHistoryRepository(t)
writeHistoryList(t, "base.com\n")
+192
View File
@@ -0,0 +1,192 @@
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"sync"
"time"
)
const (
acceptJSON = "application/json"
acceptRDAP = "application/rdap+json, application/json"
acceptDNS = "application/dns-json"
userAgent = "domain-list-community-domain-audit/1.0 (+https://github.com/v2fly/domain-list-community)"
maxJSONBytes = 2 * 1024 * 1024
maxAttempts = 3
maxRedirects = 10
)
var (
errRedirectPolicy = errors.New("redirect refused")
errEmptyBody = errors.New("empty response body")
)
type hostLimiter struct {
mu sync.Mutex
next time.Time
}
func (limiter *hostLimiter) wait(ctx context.Context, interval time.Duration) error {
for {
if err := ctx.Err(); err != nil {
return err
}
limiter.mu.Lock()
delay := time.Until(limiter.next)
if delay <= 0 {
limiter.next = time.Now().Add(interval)
limiter.mu.Unlock()
return nil
}
limiter.mu.Unlock()
if err := pause(ctx, delay); err != nil {
return err
}
}
}
func (limiter *hostLimiter) deferUntil(until time.Time) {
limiter.mu.Lock()
defer limiter.mu.Unlock()
if until.After(limiter.next) {
limiter.next = until
}
}
func (checker *checker) limiterFor(host string) *hostLimiter {
value, _ := checker.limiters.LoadOrStore(host, &hostLimiter{})
return value.(*hostLimiter)
}
func pause(ctx context.Context, delay time.Duration) error {
timer := time.NewTimer(delay)
defer timer.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-timer.C:
return nil
}
}
func retryDelay(value string, attempt int) time.Duration {
if seconds, err := strconv.Atoi(value); err == nil && seconds >= 0 {
return time.Duration(seconds) * time.Second
}
if date, err := http.ParseTime(value); err == nil && time.Until(date) > 0 {
return time.Until(date)
}
return time.Duration(1<<attempt) * time.Second
}
// newRequest builds every hop from scratch so cookies or sensitive headers cannot leak across hosts.
func newRequest(ctx context.Context, endpoint, accept string) (*http.Request, error) {
request, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return nil, err
}
request.Header.Set("Accept", accept)
request.Header.Set("User-Agent", userAgent)
return request, nil
}
func (checker *checker) get(ctx context.Context, endpoint, accept string) (*http.Response, error) {
request, err := newRequest(ctx, endpoint, accept)
if err != nil {
return nil, err
}
client := *checker.client
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
for hop := 1; ; hop++ {
// Start each network timeout only after this hop's pacing delay has elapsed.
if err := checker.limiterFor(request.URL.Host).wait(ctx, checker.interval); err != nil {
return nil, err
}
response, err := client.Do(request)
if err != nil {
return nil, err
}
if response.Request == nil {
response.Request = request
}
switch response.StatusCode {
case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect:
if response.Header.Get("Location") == "" {
return response, nil
}
default:
return response, nil
}
location, err := response.Location()
_ = response.Body.Close()
switch {
case err != nil:
return nil, fmt.Errorf("%w: %v", errRedirectPolicy, err)
case location.Scheme != "https":
return nil, fmt.Errorf("%w: insecure redirect to %s", errRedirectPolicy, location.Redacted())
case hop >= maxRedirects:
return nil, fmt.Errorf("%w: stopped after %d redirects", errRedirectPolicy, maxRedirects)
}
if request, err = newRequest(ctx, location.String(), accept); err != nil {
return nil, err
}
}
}
// getJSON decodes a complete, bounded 200 or 404 response. An empty body returns errEmptyBody.
func (checker *checker) getJSON(ctx context.Context, endpoint, accept string, target any) (int, error) {
parsed, err := url.Parse(endpoint)
if err != nil {
return 0, err
}
limiter := checker.limiterFor(parsed.Host)
for attempt := 0; attempt < maxAttempts; attempt++ {
response, requestErr := checker.get(ctx, endpoint, accept)
if requestErr != nil {
if attempt < maxAttempts-1 && ctx.Err() == nil && !errors.Is(requestErr, errRedirectPolicy) {
limiter.deferUntil(time.Now().Add(retryDelay("", attempt)))
continue
}
return 0, requestErr
}
status := response.StatusCode
if status == http.StatusTooManyRequests || status >= 500 {
_ = response.Body.Close()
until := time.Now().Add(retryDelay(response.Header.Get("Retry-After"), attempt))
limiter.deferUntil(until)
checker.limiterFor(response.Request.URL.Host).deferUntil(until)
if attempt < maxAttempts-1 {
continue
}
return status, fmt.Errorf("HTTP %d after %d attempts", status, maxAttempts)
}
if status != http.StatusOK && status != http.StatusNotFound {
_ = response.Body.Close()
return status, fmt.Errorf("HTTP %d", status)
}
body, readErr := io.ReadAll(io.LimitReader(response.Body, maxJSONBytes+1))
closeErr := response.Body.Close()
if readErr != nil {
return status, fmt.Errorf("read JSON response: %w", readErr)
}
if closeErr != nil {
return status, fmt.Errorf("close JSON response: %w", closeErr)
}
if len(body) > maxJSONBytes {
return status, fmt.Errorf("JSON response exceeds %d bytes", maxJSONBytes)
}
if len(bytes.TrimSpace(body)) == 0 {
return status, errEmptyBody
}
return status, json.Unmarshal(body, target)
}
return 0, fmt.Errorf("request attempts exhausted")
}
+27 -32
View File
@@ -24,16 +24,9 @@ func auditHTTPResponse(status int, body string) *http.Response {
}
func TestGetJSONRedirectPacingOutsideRequestTimeout(t *testing.T) {
var sourceRequests, destinationRequests, policyCalls atomic.Int32
var sourceRequests, destinationRequests atomic.Int32
client := &http.Client{
Timeout: 50 * time.Millisecond,
CheckRedirect: func(request *http.Request, previous []*http.Request) error {
policyCalls.Add(1)
if request.URL.Host != "destination.example" || len(previous) != 1 || request.Header.Get("Accept") == "" {
t.Errorf("unexpected redirect policy input: %s, %d previous requests, headers %v", request.URL, len(previous), request.Header)
}
return nil
},
Transport: auditHTTPTransport(func(request *http.Request) (*http.Response, error) {
switch request.URL.String() {
case bootstrapURL:
@@ -51,6 +44,9 @@ func TestGetJSONRedirectPacingOutsideRequestTimeout(t *testing.T) {
if request.Header.Get("Cookie") != "" || request.Header.Get("Authorization") != "" {
t.Error("sensitive source headers leaked to the redirect destination")
}
if request.Header.Get("Accept") != acceptRDAP || request.Header.Get("User-Agent") != userAgent {
t.Errorf("redirect destination headers = %v, want RDAP Accept and audit User-Agent", request.Header)
}
if err := request.Context().Err(); err != nil {
return nil, err
}
@@ -69,12 +65,12 @@ func TestGetJSONRedirectPacingOutsideRequestTimeout(t *testing.T) {
// This destination's cooldown exceeds an entire network request's timeout.
checker.limiterFor("destination.example").deferUntil(time.Now().Add(150 * time.Millisecond))
var result rdapResponse
status, err := checker.getJSON(ctx, "https://source.example/domain/example.com", &result)
status, err := checker.getJSON(ctx, "https://source.example/domain/example.com", acceptRDAP, &result)
if err != nil || status != 404 || result.ErrorCode != 404 {
t.Fatalf("paced redirect = HTTP %d, %+v, %v", status, result, err)
}
if sourceRequests.Load() != 1 || destinationRequests.Load() != 1 || policyCalls.Load() != 1 {
t.Errorf("redirect consumed retries: source=%d destination=%d policy=%d", sourceRequests.Load(), destinationRequests.Load(), policyCalls.Load())
if sourceRequests.Load() != 1 || destinationRequests.Load() != 1 {
t.Errorf("redirect consumed retries: source=%d destination=%d", sourceRequests.Load(), destinationRequests.Load())
}
}
@@ -97,14 +93,14 @@ func TestGetJSONFollowsTLSAndSameHostRedirects(t *testing.T) {
defer server.Close()
checker := &checker{client: server.Client(), interval: time.Millisecond}
var result rdapResponse
status, err := checker.getJSON(context.Background(), server.URL+"/start", &result)
status, err := checker.getJSON(context.Background(), server.URL+"/start", acceptRDAP, &result)
if err != nil || status != 200 || result.ErrorCode != 404 || requests.Load() != 3 {
t.Errorf("same-host TLS redirects = HTTP %d, %+v, %v, %d requests", status, result, err, requests.Load())
}
}
func TestGetJSONEnforcesRedirectPolicy(t *testing.T) {
for _, name := range []string{"insecure destination", "redirect loop", "caller rejects redirect", "caller keeps response"} {
for _, name := range []string{"insecure destination", "redirect loop"} {
t.Run(name, func(t *testing.T) {
var requests atomic.Int32
client := &http.Client{Transport: auditHTTPTransport(func(request *http.Request) (*http.Response, error) {
@@ -117,41 +113,35 @@ func TestGetJSONEnforcesRedirectPolicy(t *testing.T) {
response.Header.Set("Location", location)
return response, nil
})}
if name == "caller rejects redirect" {
client.CheckRedirect = func(*http.Request, []*http.Request) error { return errors.New("caller policy") }
}
if name == "caller keeps response" {
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
}
checker := &checker{client: client, interval: time.Nanosecond}
var result rdapResponse
status, err := checker.getJSON(context.Background(), "https://registry.example/start", &result)
if err == nil {
t.Fatal("redirect policy failure was accepted as JSON evidence")
_, err := checker.getJSON(context.Background(), "https://registry.example/start", acceptRDAP, &result)
if !errors.Is(err, errRedirectPolicy) {
t.Fatalf("redirect policy error = %v, want %v", err, errRedirectPolicy)
}
wantRequests := int32(1)
if name == "redirect loop" {
wantRequests = 10
wantRequests = maxRedirects
}
if requests.Load() != wantRequests {
t.Errorf("redirect requests = %d, want %d without retries", requests.Load(), wantRequests)
}
if name == "caller keeps response" && status != http.StatusFound {
t.Errorf("caller-retained response status = %d, want 302", status)
}
})
}
}
func TestGetJSONRejectsIncompleteOrOversizedBody(t *testing.T) {
for _, name := range []string{"read error after valid prefix", "exactly at limit", "larger than limit"} {
for _, name := range []string{"read error after valid prefix", "empty body", "exactly at limit", "larger than limit"} {
t.Run(name, func(t *testing.T) {
checker := &checker{interval: time.Nanosecond, client: &http.Client{Transport: auditHTTPTransport(func(request *http.Request) (*http.Response, error) {
response := auditHTTPResponse(404, "")
prefix := `{"errorCode":404}`
if name == "read error after valid prefix" {
switch name {
case "read error after valid prefix":
response.Body = io.NopCloser(io.MultiReader(strings.NewReader(prefix), auditHTTPReadError{}))
} else {
case "empty body":
// Keep the empty body from auditHTTPResponse.
default:
size := maxJSONBytes
if name == "larger than limit" {
size++
@@ -161,12 +151,17 @@ func TestGetJSONRejectsIncompleteOrOversizedBody(t *testing.T) {
return response, nil
})}}
var result rdapResponse
status, err := checker.getJSON(context.Background(), "https://registry.example/domain/example.com", &result)
if name == "exactly at limit" {
status, err := checker.getJSON(context.Background(), "https://registry.example/domain/example.com", acceptRDAP, &result)
switch {
case name == "exactly at limit":
if err != nil || status != 404 || result.ErrorCode != 404 {
t.Errorf("valid body at limit = HTTP %d, %+v, %v", status, result, err)
}
} else if err == nil || result.ErrorCode != 0 {
case name == "empty body":
if !errors.Is(err, errEmptyBody) || status != 404 {
t.Errorf("empty body = HTTP %d, %v, want 404 with %v", status, err, errEmptyBody)
}
case err == nil || result.ErrorCode != 0:
t.Errorf("invalid body populated evidence: HTTP %d, %+v, %v", status, result, err)
}
})
+1 -1
View File
@@ -46,7 +46,7 @@ func auditDomains(ctx context.Context, data *inventory, client *http.Client, int
if err != nil {
bootstrapErr := fmt.Errorf("load RDAP bootstrap: %w", err)
for index, name := range names {
results[index] = checkResult{domainEntry: data.Domains[name], Status: "unknown", Detail: bootstrapErr.Error()}
results[index] = checkResult{domainEntry: data.Domains[name], Status: statusUnknown, Detail: bootstrapErr.Error()}
}
return errors.Join(bootstrapErr, writeReports(outputDir, data, results))
}
+2 -8
View File
@@ -15,12 +15,6 @@ import (
"time"
)
type bootstrapTransport func(*http.Request) (*http.Response, error)
func (transport bootstrapTransport) RoundTrip(request *http.Request) (*http.Response, error) {
return transport(request)
}
func TestAuditDomainsPreservesReportsWhenBootstrapTimesOut(t *testing.T) {
for _, status := range []int{http.StatusServiceUnavailable, http.StatusTooManyRequests} {
t.Run(http.StatusText(status), func(t *testing.T) {
@@ -33,7 +27,7 @@ func TestAuditDomainsPreservesReportsWhenBootstrapTimesOut(t *testing.T) {
LiteralRules: 2, Skipped: map[string]int{"keyword": 1},
}
var requests atomic.Int32
client := &http.Client{Transport: bootstrapTransport(func(request *http.Request) (*http.Response, error) {
client := &http.Client{Transport: auditHTTPTransport(func(request *http.Request) (*http.Response, error) {
requests.Add(1)
if request.URL.String() != bootstrapURL {
t.Errorf("unexpected request before bootstrap succeeded: %s", request.URL)
@@ -107,7 +101,7 @@ func TestAuditDomainsPreservesBootstrapAndReportWriteErrors(t *testing.T) {
bootstrapErr := errors.New("bootstrap transport unavailable")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
client := &http.Client{Transport: bootstrapTransport(func(request *http.Request) (*http.Response, error) {
client := &http.Client{Transport: auditHTTPTransport(func(request *http.Request) (*http.Response, error) {
cancel()
return nil, bootstrapErr
})}
+7 -7
View File
@@ -20,7 +20,7 @@ func writeReports(outputDir string, data *inventory, results []checkResult) erro
if result.FirstSeen.IsZero() {
missingHistory++
}
if result.Status == "registered" && result.Registered.IsZero() {
if result.Status == statusRegistered && result.Registered.IsZero() {
missingRegistration++
}
}
@@ -54,11 +54,11 @@ func writeReports(outputDir string, data *inventory, results []checkResult) erro
fmt.Fprintf(&summary, "\nScanned %d literal rules, grouped into %d registration domains.\n", data.LiteralRules, len(results))
fmt.Fprintln(&summary, "\nThis is an advisory report for manual review. No rules are removed automatically. Registered does not mean ownership is correct. A later registration date suggests a lapse but does not prove a change of owner.")
fmt.Fprintln(&summary, "\n| Result | Domains |\n| --- | ---: |")
for _, status := range []string{"registered", "possibly_unregistered", "possibly_reregistered", "unknown", "unsupported"} {
for _, status := range []string{statusRegistered, statusPossiblyUnregistered, statusPossiblyReregistered, statusUnknown, statusUnsupported} {
fmt.Fprintf(&summary, "| %s | %d |\n", status, counts[status])
}
fmt.Fprintf(&summary, "\nUnknown and unsupported results are coverage gaps, not evidence of expiry. Registration-date comparison was unavailable for %d registered domains without a registration date, and %d domains without rule history.\n", missingRegistration, missingHistory)
if counts["unknown"] > 0 {
if counts[statusUnknown] > 0 {
fmt.Fprintln(&summary, "\n**Coverage is incomplete.** Inspect `unknown` results in the JSON report before drawing conclusions.")
}
fmt.Fprintln(&summary, "\nSkipped rules:")
@@ -71,11 +71,11 @@ func writeReports(outputDir string, data *inventory, results []checkResult) erro
fmt.Fprintf(&summary, "- %s: %d\n", markdownText(typ), data.Skipped[typ])
}
fmt.Fprintln(&summary, "\nIncludes are covered through their source files. Keywords and regular expressions cannot be queried as DNS names. TLD-only names and names without an ICANN registration boundary are excluded, along with Tor .onion names and infrastructure .arpa names.")
fmt.Fprintln(&summary, "\n## Review candidates\n\nA missing registration requires registry RDAP `errorCode: 404` plus NXDOMAIN from both Google and Cloudflare DNS for the registration domain. NOERROR (including NODATA), DNS failures, non-RDAP 404 responses and unsupported registries are not classified as unregistered.")
fmt.Fprintln(&summary, "\n## Review candidates\n\nA missing registration requires a registry RDAP HTTP 404, with an empty body or `errorCode: 404`, plus NXDOMAIN from both Google and Cloudflare DNS for the registration domain. NOERROR (including NODATA), DNS failures, other 404 bodies and unsupported registries are not classified as unregistered.")
fmt.Fprintln(&summary, "\n| Domain | Finding | First in history (UTC) | Registered (UTC) | Source locations |\n| --- | --- | --- | --- | --- |")
candidates := 0
for _, result := range results {
if result.Status != "possibly_unregistered" && result.Status != "possibly_reregistered" {
if result.Status != statusPossiblyUnregistered && result.Status != statusPossiblyReregistered {
continue
}
candidates++
@@ -93,8 +93,8 @@ func writeReports(outputDir string, data *inventory, results []checkResult) erro
if err := os.WriteFile(filepath.Join(outputDir, "summary.md"), []byte(summary.String()), 0644); err != nil {
return err
}
fmt.Printf("Audit reports saved to %s: %d review candidates, %d unknown, %d unsupported\n", outputDir, candidates, counts["unknown"], counts["unsupported"])
if counts["registered"]+counts["possibly_unregistered"]+counts["possibly_reregistered"] == 0 {
fmt.Printf("Audit reports saved to %s: %d review candidates, %d unknown, %d unsupported\n", outputDir, candidates, counts[statusUnknown], counts[statusUnsupported])
if counts[statusRegistered]+counts[statusPossiblyUnregistered]+counts[statusPossiblyReregistered] == 0 {
return fmt.Errorf("no conclusive registry responses; reports saved with coverage gaps")
}
return nil
+11 -11
View File
@@ -25,7 +25,7 @@ func TestWriteReportsPreservesEvidenceAndCoverage(t *testing.T) {
{
domainEntry: &domainEntry{Domain: "example.com", Sources: sources, FirstSeen: firstSeen},
Status: "possibly_reregistered", RDAPURL: "https://registry.example/domain/example.com",
HTTPStatus: 200, Registered: registered, RegistryHold: []string{"active"},
HTTPStatus: 200, Registered: registered, RegistryStatus: []string{"active"},
Detail: "Review registration history",
},
{
@@ -54,15 +54,15 @@ func TestWriteReportsPreservesEvidenceAndCoverage(t *testing.T) {
MissingHistory int `json:"missing_history"`
MissingRegistration int `json:"missing_registration_date"`
Results []struct {
Domain string `json:"domain"`
Sources []source `json:"sources"`
FirstSeen time.Time `json:"first_seen"`
Status string `json:"status"`
RDAPURL string `json:"rdap_url"`
HTTPStatus int `json:"http_status"`
Registered time.Time `json:"registered"`
RegistryHold []string `json:"registry_status"`
Detail string `json:"detail"`
Domain string `json:"domain"`
Sources []source `json:"sources"`
FirstSeen time.Time `json:"first_seen"`
Status string `json:"status"`
RDAPURL string `json:"rdap_url"`
HTTPStatus int `json:"http_status"`
Registered time.Time `json:"registered"`
RegistryStatus []string `json:"registry_status"`
Detail string `json:"detail"`
} `json:"results"`
}
if err := json.Unmarshal(encoded, &report); err != nil {
@@ -85,7 +85,7 @@ func TestWriteReportsPreservesEvidenceAndCoverage(t *testing.T) {
if first.Domain != "example.com" || !reflect.DeepEqual(first.Sources, sources) || !first.FirstSeen.Equal(firstSeen) || !first.Registered.Equal(registered) {
t.Errorf("report did not preserve source and date evidence: %+v", first)
}
if first.Status != "possibly_reregistered" || first.RDAPURL != results[0].RDAPURL || first.HTTPStatus != 200 || !reflect.DeepEqual(first.RegistryHold, []string{"active"}) || first.Detail != results[0].Detail {
if first.Status != "possibly_reregistered" || first.RDAPURL != results[0].RDAPURL || first.HTTPStatus != 200 || !reflect.DeepEqual(first.RegistryStatus, []string{"active"}) || first.Detail != results[0].Detail {
t.Errorf("report did not preserve registry evidence: %+v", first)
}
summary, err := os.ReadFile(filepath.Join(outputDir, "summary.md"))