// Package outboundtest lets a test reach a server on this machine
// through the same allowance list an operator uses
// (--allow-outbound), never by switching the guard off: only loopback
// is named, so a private or metadata address is still refused.
package outboundtest
import (
"context"
"errors"
"fmt"
"net"
"net/netip"
"os"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"craftdesign.group/quarry/internal/outbound"
)
var loopback = []netip.Prefix{netip.MustParsePrefix("127.0.0.0/8"), netip.MustParsePrefix("::1/128")}
// AllowLoopback admits loopback for the test and restores the empty
// allowance when it ends.
func AllowLoopback(t testing.TB) {
t.Helper()
Set(t, loopback...)
}
// resolve answers "localhost" with loopback and every other name with
// one public documentation address (a public resolver), so a test that stores
// an address such as https://hooks.example/x does not need a network;
// nothing that resolves this way is ever dialled with a real answer.
func resolve(_ context.Context, host string) ([]net.IPAddr, error) {
if strings.EqualFold(host, "localhost") {
return []net.IPAddr{{IP: net.ParseIP("127.0.0.1")}}, nil
}
return []net.IPAddr{{IP: net.ParseIP("8.8.4.4")}}, nil
}
// Main is for a package's TestMain: loopback is admitted for the whole
// run, and names resolve without a network (see resolve).
//
// func TestMain(m *testing.M) { os.Exit(outboundtest.Main(m)) }
func Main(m *testing.M) int {
outbound.Default.Allow(loopback)
outbound.Default.Resolve = resolve
// No test may use the network: a dial to anything but loopback, or a
// lookup through the system resolver, is counted and refused, and
// fails the run.
var stray atomic.Int32
var mu sync.Mutex
var seen []string
note := func(what string) {
stray.Add(1)
mu.Lock()
seen = append(seen, what)
mu.Unlock()
}
real := &net.Dialer{Timeout: 5 * time.Second}
outbound.Default.Connect = func(ctx context.Context, network, addr string) (net.Conn, error) {
if ap, err := netip.ParseAddrPort(addr); err != nil || !ap.Addr().IsLoopback() {
note("dial " + addr)
return nil, errors.New("outboundtest: a test dialled a non-loopback address")
}
return real.DialContext(ctx, network, addr)
}
net.DefaultResolver = &net.Resolver{PreferGo: true, Dial: func(_ context.Context, _, addr string) (net.Conn, error) {
note("resolver " + addr)
return nil, errors.New("outboundtest: a test used the system resolver")
}}
code := m.Run()
if stray.Load() > 0 {
fmt.Fprintf(os.Stderr, "FAIL: tests touched the network: %v\n", seen)
if code == 0 {
code = 1
}
}
return code
}
// Set replaces the allowance for one test with exactly prefixes (none
// for an empty guard) and restores the previous list when it ends.
func Set(t testing.TB, prefixes ...netip.Prefix) {
t.Helper()
prev := outbound.Default.Allowed()
outbound.Default.Allow(prefixes)
t.Cleanup(func() { outbound.Default.Allow(prev) })
}
// Prefix parses a CIDR or address for Set.
func Prefix(s string) netip.Prefix {
if p, err := netip.ParsePrefix(s); err == nil {
return p
}
return netip.PrefixFrom(netip.MustParseAddr(s), netip.MustParseAddr(s).BitLen())
}
// Resolve makes the names in table answer as given (an empty list: no such host) for one test (every
// other name answers as Main set it), restoring the resolver after.
func Resolve(t testing.TB, table map[string][]string) {
t.Helper()
prev := outbound.Default.Resolve
outbound.Default.Resolve = func(ctx context.Context, host string) ([]net.IPAddr, error) {
if ips, ok := table[host]; ok {
if len(ips) == 0 {
return nil, errors.New("no such host")
}
var out []net.IPAddr
for _, s := range ips {
out = append(out, net.IPAddr{IP: net.ParseIP(s)})
}
return out, nil
}
return prev(ctx, host)
}
t.Cleanup(func() { outbound.Default.Resolve = prev })
}
// Connect replaces the connection step for one test, so a dial can be
// observed without a packet leaving; fn sees the vetted address.
func Connect(t testing.TB, fn func(network, addr string) error) {
t.Helper()
prev := outbound.Default.Connect
outbound.Default.Connect = func(_ context.Context, network, addr string) (net.Conn, error) {
return nil, fn(network, addr)
}
t.Cleanup(func() { outbound.Default.Connect = prev })
}