panel: server status page, per-domain DNS checks, /domains move
Phase 13. Two new packages and one new screen. internal/health owns the shared status vocabulary (ok/warn/error/unknown) and the local checks: supervisord's process table, TLS certificate expiry and the two milter sockets. Each check reports a problem as a status rather than an error, so one broken component costs a line and not the page. internal/dnscheck does the read-only lookups: forward-confirmed reverse DNS for SELFPOST_HOSTNAME, and per-domain DKIM (compared against the key this server actually signs with), SPF and DMARC. Every check is bounded by a timeout and cached, and the resolver sits behind an interface so the tests drive every branch without touching the network. The SPF check is deliberately shallow: it looks for a mechanism literally covering the server's address and does not follow include:/redirect=, so a record that authorises us through an include is reported as "cannot tell" rather than as a failure. /status renders both, with the local checks in an HTMX-polled fragment and the DNS lookups behind a Re-check button, and becomes the panel's landing page: / now redirects there and the domain list lives at /domains. The Reload button moves onto /status, where it reads as what it is — a drift-recovery for the daemons — with text explaining what it regenerates. A template test fails on any remaining href="/" so a stale link cannot silently land on the wrong screen. Also fixes a defect this made visible: the panel could never read the mail queue in the documented deployment. postqueue relies on its setgid-postdrop bit, which the compose file's no-new-privileges disables, so the Queue screen always said "Could not read the mail queue" — including in the released 1.0.0 image. The panel user is now a real member of postdrop, which needs no setgid transition. Verified in a container on the dev server against real DNS: PTR matching (selfpost.example.com) and not matching (example.com), DKIM absent and mismatched, SPF absent and via include:, DMARC p=quarantine/p=reject/absent, and a resolver timeout degrading to "unknown" without hanging the page. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,232 @@
|
||||
// Package dnscheck performs the read-only DNS lookups behind the panel's
|
||||
// deliverability checks: forward-confirmed reverse DNS (FCrDNS) for the
|
||||
// server's own hostname, and the DKIM/SPF/DMARC records published for each
|
||||
// sending domain.
|
||||
//
|
||||
// Every lookup is bounded by a timeout and results are cached, because DNS is
|
||||
// the one part of the status page that talks to the network: a slow or dead
|
||||
// resolver must degrade a single card to "could not check", never hang the
|
||||
// page. Nothing here changes state — the panel only reports what the world can
|
||||
// see about this server.
|
||||
package dnscheck
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"codeberg.org/mix/selfpost/internal/health"
|
||||
)
|
||||
|
||||
const (
|
||||
// lookupTimeout bounds all the lookups of a single check together, so a
|
||||
// dead resolver costs one wait and not one per record type.
|
||||
lookupTimeout = 5 * time.Second
|
||||
// serverTTL/domainTTL are how long a cached result stays fresh. The
|
||||
// server's own hostname/PTR is cheap and rarely changes; a domain's
|
||||
// records are three lookups, and the operator has just published them, so
|
||||
// a few minutes plus an explicit Re-check button is the right trade.
|
||||
serverTTL = time.Minute
|
||||
domainTTL = 5 * time.Minute
|
||||
)
|
||||
|
||||
// Result is the outcome of one published-record check.
|
||||
type Result struct {
|
||||
Status health.Status
|
||||
// Detail is a full sentence for the operator: what was found and, when
|
||||
// something is wrong, what to do about it.
|
||||
Detail string
|
||||
// Records is what was actually found in DNS, shown verbatim so the
|
||||
// operator can compare it with what they published.
|
||||
Records []string
|
||||
}
|
||||
|
||||
// Server is the state of the server's own name in DNS: the addresses
|
||||
// SELFPOST_HOSTNAME resolves to, and whether their PTR records point back at
|
||||
// it. Receiving servers weigh this heavily, so a mismatch is an error.
|
||||
type Server struct {
|
||||
Hostname string
|
||||
IPs []string // forward-resolved addresses, reused for the SPF check
|
||||
PTR Result
|
||||
CheckedAt time.Time
|
||||
}
|
||||
|
||||
// Domain is the published-DNS state of one sending domain.
|
||||
type Domain struct {
|
||||
Name string
|
||||
DKIM Result
|
||||
SPF Result
|
||||
DMARC Result
|
||||
Overall health.Status
|
||||
CheckedAt time.Time
|
||||
}
|
||||
|
||||
// Query describes the domain to check. ExpectedDKIM is the TXT value the panel
|
||||
// tells the operator to publish (domain.DKIMRecord.Value), so the check
|
||||
// compares DNS against the key this server actually signs with. ServerIPs comes
|
||||
// from a preceding Server check.
|
||||
type Query struct {
|
||||
Name string
|
||||
Selector string
|
||||
ExpectedDKIM string
|
||||
ServerIPs []string
|
||||
}
|
||||
|
||||
// resolver is the slice of *net.Resolver this package uses, as an interface so
|
||||
// tests can drive the checks without touching the network.
|
||||
type resolver interface {
|
||||
LookupTXT(ctx context.Context, name string) ([]string, error)
|
||||
LookupIPAddr(ctx context.Context, host string) ([]net.IPAddr, error)
|
||||
LookupAddr(ctx context.Context, addr string) ([]string, error)
|
||||
LookupMX(ctx context.Context, name string) ([]*net.MX, error)
|
||||
}
|
||||
|
||||
// Checker runs the checks and caches their results. The zero value is not
|
||||
// usable; call New.
|
||||
type Checker struct {
|
||||
resolver resolver
|
||||
timeout time.Duration
|
||||
serverTTL time.Duration
|
||||
domainTTL time.Duration
|
||||
|
||||
mu sync.Mutex
|
||||
servers map[string]cached[Server]
|
||||
domains map[string]cached[Domain]
|
||||
}
|
||||
|
||||
type cached[T any] struct {
|
||||
value T
|
||||
expires time.Time
|
||||
}
|
||||
|
||||
// New returns a Checker using the process resolver and the package's default
|
||||
// timeout and cache lifetimes.
|
||||
func New() *Checker {
|
||||
return newChecker(net.DefaultResolver, lookupTimeout, serverTTL, domainTTL)
|
||||
}
|
||||
|
||||
func newChecker(r resolver, timeout, srvTTL, domTTL time.Duration) *Checker {
|
||||
return &Checker{
|
||||
resolver: r,
|
||||
timeout: timeout,
|
||||
serverTTL: srvTTL,
|
||||
domainTTL: domTTL,
|
||||
servers: make(map[string]cached[Server]),
|
||||
domains: make(map[string]cached[Domain]),
|
||||
}
|
||||
}
|
||||
|
||||
// Server checks the server's own hostname. force skips the cache, for the
|
||||
// Re-check button.
|
||||
func (c *Checker) Server(hostname string, force bool) Server {
|
||||
if !force {
|
||||
c.mu.Lock()
|
||||
entry, ok := c.servers[hostname]
|
||||
c.mu.Unlock()
|
||||
if ok && time.Now().Before(entry.expires) {
|
||||
return entry.value
|
||||
}
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
|
||||
defer cancel()
|
||||
srv := c.checkServer(ctx, hostname)
|
||||
|
||||
c.mu.Lock()
|
||||
c.servers[hostname] = cached[Server]{value: srv, expires: srv.CheckedAt.Add(c.serverTTL)}
|
||||
c.mu.Unlock()
|
||||
return srv
|
||||
}
|
||||
|
||||
// Domain checks one sending domain's published records. force skips the cache,
|
||||
// for the Re-check button on the domain page.
|
||||
func (c *Checker) Domain(q Query, force bool) Domain {
|
||||
if !force {
|
||||
c.mu.Lock()
|
||||
entry, ok := c.domains[q.Name]
|
||||
c.mu.Unlock()
|
||||
if ok && time.Now().Before(entry.expires) {
|
||||
return entry.value
|
||||
}
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
|
||||
defer cancel()
|
||||
d := c.checkDomain(ctx, q)
|
||||
|
||||
c.mu.Lock()
|
||||
c.domains[q.Name] = cached[Domain]{value: d, expires: d.CheckedAt.Add(c.domainTTL)}
|
||||
c.mu.Unlock()
|
||||
return d
|
||||
}
|
||||
|
||||
// Forget drops a domain's cached result, so the next page view re-checks it.
|
||||
// Used when a domain is removed or re-imported.
|
||||
func (c *Checker) Forget(domainName string) {
|
||||
c.mu.Lock()
|
||||
delete(c.domains, domainName)
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
// checkDomain runs the three record checks concurrently: they are independent,
|
||||
// and in series three timeouts would stack up into a page that looks hung.
|
||||
func (c *Checker) checkDomain(ctx context.Context, q Query) Domain {
|
||||
d := Domain{Name: q.Name, CheckedAt: time.Now()}
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(3)
|
||||
go func() { defer wg.Done(); d.DKIM = c.checkDKIM(ctx, q) }()
|
||||
go func() { defer wg.Done(); d.SPF = c.checkSPF(ctx, q) }()
|
||||
go func() { defer wg.Done(); d.DMARC = c.checkDMARC(ctx, q.Name) }()
|
||||
wg.Wait()
|
||||
d.Overall = health.Worst(d.DKIM.Status, d.SPF.Status, d.DMARC.Status)
|
||||
return d
|
||||
}
|
||||
|
||||
// lookupTXT wraps the resolver's TXT lookup, separating "the name does not
|
||||
// exist / has no TXT records" (a finding to report) from "the lookup failed"
|
||||
// (nothing was learned).
|
||||
func (c *Checker) lookupTXT(ctx context.Context, name string) (records []string, found bool, err error) {
|
||||
txt, err := c.resolver.LookupTXT(ctx, name)
|
||||
if err != nil {
|
||||
var dnsErr *net.DNSError
|
||||
if errors.As(err, &dnsErr) && dnsErr.IsNotFound {
|
||||
return nil, false, nil
|
||||
}
|
||||
return nil, false, err
|
||||
}
|
||||
if len(txt) == 0 {
|
||||
return nil, false, nil
|
||||
}
|
||||
return txt, true, nil
|
||||
}
|
||||
|
||||
// lookupFailed is the shared shape for "the resolver did not answer": unknown,
|
||||
// not an accusation against the domain's configuration.
|
||||
func lookupFailed(what string, err error) Result {
|
||||
return Result{
|
||||
Status: health.StatusUnknown,
|
||||
Detail: "Could not check " + what + ": the DNS lookup failed (" + dnsErrorText(err) + "). Try Re-check in a moment.",
|
||||
}
|
||||
}
|
||||
|
||||
// dnsErrorText reduces a resolver error to its message, without the internals
|
||||
// (Go wraps the name and server into the string form).
|
||||
func dnsErrorText(err error) string {
|
||||
var dnsErr *net.DNSError
|
||||
if errors.As(err, &dnsErr) {
|
||||
if dnsErr.IsTimeout {
|
||||
return "timed out"
|
||||
}
|
||||
return dnsErr.Err
|
||||
}
|
||||
return err.Error()
|
||||
}
|
||||
|
||||
// normalizeName lowercases a DNS name and drops the root label, so a PTR answer
|
||||
// ("mail.example.com.") compares equal to a configured hostname.
|
||||
func normalizeName(name string) string {
|
||||
return strings.TrimSuffix(strings.ToLower(strings.TrimSpace(name)), ".")
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
package dnscheck
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"codeberg.org/mix/selfpost/internal/health"
|
||||
)
|
||||
|
||||
// fakeResolver serves a fixed zone, so the checks can be driven through every
|
||||
// branch without touching the network. An absent name resolves to the same
|
||||
// "not found" DNSError the standard resolver returns for NXDOMAIN.
|
||||
type fakeResolver struct {
|
||||
txt map[string][]string
|
||||
addr map[string][]net.IPAddr
|
||||
ptr map[string][]string
|
||||
mx map[string][]*net.MX
|
||||
|
||||
// fail names that must return a transient failure instead of an answer.
|
||||
fail map[string]bool
|
||||
// lookups counts every query, for the cache tests.
|
||||
lookups int
|
||||
}
|
||||
|
||||
func notFound(name string) error {
|
||||
return &net.DNSError{Err: "no such host", Name: name, IsNotFound: true}
|
||||
}
|
||||
|
||||
func (f *fakeResolver) LookupTXT(_ context.Context, name string) ([]string, error) {
|
||||
f.lookups++
|
||||
if f.fail[name] {
|
||||
return nil, &net.DNSError{Err: "server misbehaving", Name: name, IsTemporary: true}
|
||||
}
|
||||
if v, ok := f.txt[name]; ok {
|
||||
return v, nil
|
||||
}
|
||||
return nil, notFound(name)
|
||||
}
|
||||
|
||||
func (f *fakeResolver) LookupIPAddr(_ context.Context, host string) ([]net.IPAddr, error) {
|
||||
f.lookups++
|
||||
if v, ok := f.addr[host]; ok {
|
||||
return v, nil
|
||||
}
|
||||
return nil, notFound(host)
|
||||
}
|
||||
|
||||
func (f *fakeResolver) LookupAddr(_ context.Context, addr string) ([]string, error) {
|
||||
f.lookups++
|
||||
if v, ok := f.ptr[addr]; ok {
|
||||
return v, nil
|
||||
}
|
||||
return nil, notFound(addr)
|
||||
}
|
||||
|
||||
func (f *fakeResolver) LookupMX(_ context.Context, name string) ([]*net.MX, error) {
|
||||
f.lookups++
|
||||
if v, ok := f.mx[name]; ok {
|
||||
return v, nil
|
||||
}
|
||||
return nil, notFound(name)
|
||||
}
|
||||
|
||||
func ipAddrs(ips ...string) []net.IPAddr {
|
||||
out := make([]net.IPAddr, 0, len(ips))
|
||||
for _, s := range ips {
|
||||
out = append(out, net.IPAddr{IP: net.ParseIP(s)})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func newTestChecker(f *fakeResolver) *Checker {
|
||||
return newChecker(f, time.Second, time.Minute, time.Minute)
|
||||
}
|
||||
|
||||
func TestServerPTRMatches(t *testing.T) {
|
||||
f := &fakeResolver{
|
||||
addr: map[string][]net.IPAddr{"mail.example.com": ipAddrs("203.0.113.10")},
|
||||
ptr: map[string][]string{"203.0.113.10": {"mail.example.com."}},
|
||||
}
|
||||
srv := newTestChecker(f).Server("mail.example.com", false)
|
||||
if srv.PTR.Status != health.StatusOK {
|
||||
t.Fatalf("status = %q (%s)", srv.PTR.Status, srv.PTR.Detail)
|
||||
}
|
||||
if len(srv.IPs) != 1 || srv.IPs[0] != "203.0.113.10" {
|
||||
t.Errorf("IPs = %v, want the forward-resolved address for the SPF check", srv.IPs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServerPTRMismatchIsAnError(t *testing.T) {
|
||||
f := &fakeResolver{
|
||||
addr: map[string][]net.IPAddr{"mail.example.com": ipAddrs("203.0.113.10")},
|
||||
ptr: map[string][]string{"203.0.113.10": {"static-10.provider.net."}},
|
||||
}
|
||||
srv := newTestChecker(f).Server("mail.example.com", false)
|
||||
if srv.PTR.Status != health.StatusError {
|
||||
t.Fatalf("status = %q (%s)", srv.PTR.Status, srv.PTR.Detail)
|
||||
}
|
||||
if len(srv.PTR.Records) != 1 || !strings.Contains(srv.PTR.Records[0], "static-10.provider.net") {
|
||||
t.Errorf("records = %v, want the PTR name that was actually found", srv.PTR.Records)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServerPTRMissing(t *testing.T) {
|
||||
f := &fakeResolver{addr: map[string][]net.IPAddr{"mail.example.com": ipAddrs("203.0.113.10")}}
|
||||
srv := newTestChecker(f).Server("mail.example.com", false)
|
||||
if srv.PTR.Status != health.StatusError {
|
||||
t.Errorf("status = %q (%s)", srv.PTR.Status, srv.PTR.Detail)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServerPartialPTRWarns(t *testing.T) {
|
||||
f := &fakeResolver{
|
||||
addr: map[string][]net.IPAddr{"mail.example.com": ipAddrs("203.0.113.10", "2001:db8::1")},
|
||||
ptr: map[string][]string{"203.0.113.10": {"mail.example.com."}},
|
||||
}
|
||||
srv := newTestChecker(f).Server("mail.example.com", false)
|
||||
if srv.PTR.Status != health.StatusWarn {
|
||||
t.Errorf("status = %q (%s)", srv.PTR.Status, srv.PTR.Detail)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServerHostnameDoesNotResolve(t *testing.T) {
|
||||
srv := newTestChecker(&fakeResolver{}).Server("mail.example.com", false)
|
||||
if srv.PTR.Status != health.StatusError {
|
||||
t.Errorf("status = %q (%s)", srv.PTR.Status, srv.PTR.Detail)
|
||||
}
|
||||
if len(srv.IPs) != 0 {
|
||||
t.Errorf("IPs = %v, want none", srv.IPs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServerHostnameUnset(t *testing.T) {
|
||||
srv := newTestChecker(&fakeResolver{}).Server("", false)
|
||||
if srv.PTR.Status != health.StatusUnknown {
|
||||
t.Errorf("status = %q, want unknown when SELFPOST_HOSTNAME is unset", srv.PTR.Status)
|
||||
}
|
||||
}
|
||||
|
||||
const testDKIMValue = "v=DKIM1; h=sha256; k=rsa; p=MIIBIjANBgkqTESTKEY"
|
||||
|
||||
func dkimQuery(records map[string][]string) (*fakeResolver, Query) {
|
||||
q := Query{
|
||||
Name: "example.com",
|
||||
Selector: "selfpost",
|
||||
ExpectedDKIM: testDKIMValue,
|
||||
ServerIPs: []string{"203.0.113.10"},
|
||||
}
|
||||
return &fakeResolver{txt: records}, q
|
||||
}
|
||||
|
||||
func TestDKIMPublishedAndMatching(t *testing.T) {
|
||||
f, q := dkimQuery(map[string][]string{
|
||||
// Published with different spacing and a line break in the base64, as
|
||||
// DNS providers and TXT chunking produce.
|
||||
"selfpost._domainkey.example.com": {"v=DKIM1;h=sha256;k=rsa;p=MIIBIjANBgkq TESTKEY"},
|
||||
})
|
||||
got := newTestChecker(f).Domain(q, false)
|
||||
if got.DKIM.Status != health.StatusOK {
|
||||
t.Errorf("status = %q (%s)", got.DKIM.Status, got.DKIM.Detail)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDKIMMissing(t *testing.T) {
|
||||
f, q := dkimQuery(nil)
|
||||
got := newTestChecker(f).Domain(q, false)
|
||||
if got.DKIM.Status != health.StatusError {
|
||||
t.Errorf("status = %q (%s)", got.DKIM.Status, got.DKIM.Detail)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDKIMWrongKey(t *testing.T) {
|
||||
f, q := dkimQuery(map[string][]string{
|
||||
"selfpost._domainkey.example.com": {"v=DKIM1; h=sha256; k=rsa; p=SOMEOTHERKEY"},
|
||||
})
|
||||
got := newTestChecker(f).Domain(q, false)
|
||||
if got.DKIM.Status != health.StatusError {
|
||||
t.Errorf("status = %q (%s)", got.DKIM.Status, got.DKIM.Detail)
|
||||
}
|
||||
if !strings.Contains(got.DKIM.Detail, "not the one this server signs with") {
|
||||
t.Errorf("detail does not explain the mismatch: %s", got.DKIM.Detail)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDKIMRevoked(t *testing.T) {
|
||||
f, q := dkimQuery(map[string][]string{
|
||||
"selfpost._domainkey.example.com": {"v=DKIM1; h=sha256; k=rsa; p="},
|
||||
})
|
||||
got := newTestChecker(f).Domain(q, false)
|
||||
if got.DKIM.Status != health.StatusError || !strings.Contains(got.DKIM.Detail, "revokes") {
|
||||
t.Errorf("status = %q (%s)", got.DKIM.Status, got.DKIM.Detail)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDKIMLookupFailureIsUnknown(t *testing.T) {
|
||||
f, q := dkimQuery(nil)
|
||||
f.fail = map[string]bool{"selfpost._domainkey.example.com": true}
|
||||
got := newTestChecker(f).Domain(q, false)
|
||||
if got.DKIM.Status != health.StatusUnknown {
|
||||
t.Errorf("status = %q (%s), want unknown when the resolver fails", got.DKIM.Status, got.DKIM.Detail)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSPF(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
record []string
|
||||
want health.Status
|
||||
}{
|
||||
{"literal ip4", []string{"v=spf1 ip4:203.0.113.10 -all"}, health.StatusOK},
|
||||
{"covering CIDR", []string{"v=spf1 ip4:203.0.113.0/24 -all"}, health.StatusOK},
|
||||
{"other address only", []string{"v=spf1 ip4:198.51.100.7 -all"}, health.StatusError},
|
||||
{"include cannot be followed", []string{"v=spf1 include:_spf.provider.net -all"}, health.StatusWarn},
|
||||
{"plus all", []string{"v=spf1 +all"}, health.StatusWarn},
|
||||
{"negative qualifier does not authorise", []string{"v=spf1 -ip4:203.0.113.10 -all"}, health.StatusError},
|
||||
{"two records", []string{"v=spf1 ip4:203.0.113.10 -all", "v=spf1 -all"}, health.StatusError},
|
||||
{"no record", nil, health.StatusError},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
txt := map[string][]string{}
|
||||
if c.record != nil {
|
||||
txt["example.com"] = c.record
|
||||
}
|
||||
f := &fakeResolver{txt: txt}
|
||||
got := newTestChecker(f).checkSPF(context.Background(), Query{
|
||||
Name: "example.com",
|
||||
ServerIPs: []string{"203.0.113.10"},
|
||||
})
|
||||
if got.Status != c.want {
|
||||
t.Errorf("status = %q, want %q (%s)", got.Status, c.want, got.Detail)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSPFAMechanism(t *testing.T) {
|
||||
f := &fakeResolver{
|
||||
txt: map[string][]string{"example.com": {"v=spf1 a -all"}},
|
||||
addr: map[string][]net.IPAddr{"example.com": ipAddrs("203.0.113.10")},
|
||||
}
|
||||
got := newTestChecker(f).checkSPF(context.Background(), Query{
|
||||
Name: "example.com",
|
||||
ServerIPs: []string{"203.0.113.10"},
|
||||
})
|
||||
if got.Status != health.StatusOK {
|
||||
t.Errorf("status = %q (%s)", got.Status, got.Detail)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSPFMXMechanism(t *testing.T) {
|
||||
f := &fakeResolver{
|
||||
txt: map[string][]string{"example.com": {"v=spf1 mx -all"}},
|
||||
mx: map[string][]*net.MX{"example.com": {{Host: "mail.example.com.", Pref: 10}}},
|
||||
addr: map[string][]net.IPAddr{"mail.example.com": ipAddrs("203.0.113.10")},
|
||||
}
|
||||
got := newTestChecker(f).checkSPF(context.Background(), Query{
|
||||
Name: "example.com",
|
||||
ServerIPs: []string{"203.0.113.10"},
|
||||
})
|
||||
if got.Status != health.StatusOK {
|
||||
t.Errorf("status = %q (%s)", got.Status, got.Detail)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSPFWithoutServerIPIsUnknown(t *testing.T) {
|
||||
f := &fakeResolver{txt: map[string][]string{"example.com": {"v=spf1 -all"}}}
|
||||
got := newTestChecker(f).checkSPF(context.Background(), Query{Name: "example.com"})
|
||||
if got.Status != health.StatusUnknown {
|
||||
t.Errorf("status = %q (%s)", got.Status, got.Detail)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDMARC(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
record []string
|
||||
want health.Status
|
||||
}{
|
||||
{"reject", []string{"v=DMARC1; p=reject; rua=mailto:dmarc@example.com"}, health.StatusOK},
|
||||
{"none", []string{"v=DMARC1; p=none"}, health.StatusOK},
|
||||
{"no policy tag", []string{"v=DMARC1; rua=mailto:dmarc@example.com"}, health.StatusWarn},
|
||||
{"absent", nil, health.StatusWarn},
|
||||
{"duplicated", []string{"v=DMARC1; p=none", "v=DMARC1; p=reject"}, health.StatusError},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
txt := map[string][]string{}
|
||||
if c.record != nil {
|
||||
txt["_dmarc.example.com"] = c.record
|
||||
}
|
||||
f := &fakeResolver{txt: txt}
|
||||
got := newTestChecker(f).checkDMARC(context.Background(), "example.com")
|
||||
if got.Status != c.want {
|
||||
t.Errorf("status = %q, want %q (%s)", got.Status, c.want, got.Detail)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDMARCNonePolicyIsExplained(t *testing.T) {
|
||||
f := &fakeResolver{txt: map[string][]string{"_dmarc.example.com": {"v=DMARC1; p=none"}}}
|
||||
got := newTestChecker(f).checkDMARC(context.Background(), "example.com")
|
||||
if !strings.Contains(got.Detail, "monitoring only") {
|
||||
t.Errorf("p=none is not explained: %s", got.Detail)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResultsAreCachedAndForceBypassesTheCache(t *testing.T) {
|
||||
f := &fakeResolver{
|
||||
addr: map[string][]net.IPAddr{"mail.example.com": ipAddrs("203.0.113.10")},
|
||||
ptr: map[string][]string{"203.0.113.10": {"mail.example.com."}},
|
||||
}
|
||||
c := newTestChecker(f)
|
||||
|
||||
c.Server("mail.example.com", false)
|
||||
after := f.lookups
|
||||
if after == 0 {
|
||||
t.Fatal("the first check did not query the resolver")
|
||||
}
|
||||
c.Server("mail.example.com", false)
|
||||
if f.lookups != after {
|
||||
t.Errorf("a second check re-queried DNS: %d lookups, want %d", f.lookups, after)
|
||||
}
|
||||
c.Server("mail.example.com", true)
|
||||
if f.lookups == after {
|
||||
t.Error("force did not bypass the cache")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDomainOverallIsTheWorstOfTheThree(t *testing.T) {
|
||||
f, q := dkimQuery(map[string][]string{
|
||||
"selfpost._domainkey.example.com": {testDKIMValue},
|
||||
"example.com": {"v=spf1 ip4:203.0.113.10 -all"},
|
||||
// No DMARC: a warning.
|
||||
})
|
||||
got := newTestChecker(f).Domain(q, false)
|
||||
if got.DKIM.Status != health.StatusOK || got.SPF.Status != health.StatusOK {
|
||||
t.Fatalf("DKIM=%q SPF=%q", got.DKIM.Status, got.SPF.Status)
|
||||
}
|
||||
if got.Overall != health.StatusWarn {
|
||||
t.Errorf("overall = %q, want the DMARC warning to surface", got.Overall)
|
||||
}
|
||||
}
|
||||
|
||||
func TestForgetDropsTheCachedDomain(t *testing.T) {
|
||||
f, q := dkimQuery(map[string][]string{"selfpost._domainkey.example.com": {testDKIMValue}})
|
||||
c := newTestChecker(f)
|
||||
c.Domain(q, false)
|
||||
before := f.lookups
|
||||
c.Forget(q.Name)
|
||||
c.Domain(q, false)
|
||||
if f.lookups == before {
|
||||
t.Error("Forget did not drop the cached result")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package dnscheck
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"codeberg.org/mix/selfpost/internal/health"
|
||||
)
|
||||
|
||||
// checkDKIM compares the TXT record published at <selector>._domainkey.<domain>
|
||||
// with the key this server signs with. A wrong or absent record means every
|
||||
// message fails DKIM at the receiver, so both are errors.
|
||||
func (c *Checker) checkDKIM(ctx context.Context, q Query) Result {
|
||||
name := q.Selector + "._domainkey." + q.Name
|
||||
txt, found, err := c.lookupTXT(ctx, name)
|
||||
if err != nil {
|
||||
return lookupFailed("the DKIM record", err)
|
||||
}
|
||||
|
||||
expected := publicKeyTag(q.ExpectedDKIM)
|
||||
if !found {
|
||||
return Result{
|
||||
Status: health.StatusError,
|
||||
Detail: fmt.Sprintf("No TXT record is published at %s. Publish the record shown above — until then every message fails DKIM.", name),
|
||||
}
|
||||
}
|
||||
|
||||
for _, rec := range txt {
|
||||
got := publicKeyTag(rec)
|
||||
if got == "" {
|
||||
continue
|
||||
}
|
||||
if got == expected {
|
||||
return Result{
|
||||
Status: health.StatusOK,
|
||||
Detail: fmt.Sprintf("Published at %s and matching the key this server signs with.", name),
|
||||
Records: txt,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Something is published, but it is not our key. Separate the revoked case
|
||||
// (empty p=), which reads as a deliberate act rather than a typo.
|
||||
for _, rec := range txt {
|
||||
if v, ok := tagValue(rec, "p"); ok && v == "" {
|
||||
return Result{
|
||||
Status: health.StatusError,
|
||||
Detail: fmt.Sprintf("The record at %s has an empty p= tag, which revokes the key. Replace it with the record shown above.", name),
|
||||
Records: txt,
|
||||
}
|
||||
}
|
||||
}
|
||||
return Result{
|
||||
Status: health.StatusError,
|
||||
Detail: fmt.Sprintf("A TXT record exists at %s but its public key is not the one this server signs with — mail will fail DKIM. Replace it with the record shown above (an old record from a previous server is the usual cause).", name),
|
||||
Records: txt,
|
||||
}
|
||||
}
|
||||
|
||||
// checkDMARC reports whether the domain publishes a DMARC policy. DMARC is not
|
||||
// required for delivery, so its absence is advice (warn), not a fault.
|
||||
func (c *Checker) checkDMARC(ctx context.Context, domainName string) Result {
|
||||
name := "_dmarc." + domainName
|
||||
txt, found, err := c.lookupTXT(ctx, name)
|
||||
if err != nil {
|
||||
return lookupFailed("the DMARC record", err)
|
||||
}
|
||||
|
||||
var records []string
|
||||
for _, rec := range txt {
|
||||
if strings.HasPrefix(strings.ToLower(strings.TrimSpace(rec)), "v=dmarc1") {
|
||||
records = append(records, rec)
|
||||
}
|
||||
}
|
||||
if !found || len(records) == 0 {
|
||||
return Result{
|
||||
Status: health.StatusWarn,
|
||||
Detail: fmt.Sprintf("No DMARC record at %s. Delivery works without one, but publishing at least \"v=DMARC1; p=none; rua=mailto:you@%s\" tells receivers what to do with mail that fails DKIM and gets you reports.", name, domainName),
|
||||
}
|
||||
}
|
||||
if len(records) > 1 {
|
||||
return Result{
|
||||
Status: health.StatusError,
|
||||
Detail: fmt.Sprintf("More than one DMARC record is published at %s. Receivers treat that as no policy at all — keep exactly one.", name),
|
||||
Records: records,
|
||||
}
|
||||
}
|
||||
|
||||
policy, ok := tagValue(records[0], "p")
|
||||
if !ok || policy == "" {
|
||||
return Result{
|
||||
Status: health.StatusWarn,
|
||||
Detail: "A DMARC record is published but has no p= policy tag, so receivers ignore it. Add p=none, p=quarantine or p=reject.",
|
||||
Records: records,
|
||||
}
|
||||
}
|
||||
detail := fmt.Sprintf("Published with policy p=%s.", policy)
|
||||
if strings.EqualFold(policy, "none") {
|
||||
detail += " That is monitoring only — tighten it to quarantine or reject once the reports look clean."
|
||||
}
|
||||
return Result{Status: health.StatusOK, Detail: detail, Records: records}
|
||||
}
|
||||
|
||||
// publicKeyTag extracts the p= (public key) tag of a DKIM record, with all
|
||||
// whitespace removed: DNS providers and TXT chunking freely insert spaces and
|
||||
// line breaks into the base64, none of which are part of the key.
|
||||
func publicKeyTag(record string) string {
|
||||
v, ok := tagValue(record, "p")
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
return strings.Join(strings.Fields(v), "")
|
||||
}
|
||||
|
||||
// tagValue reads one tag from a DKIM/DMARC-style "tag=value; tag=value" record.
|
||||
// Tag names are case-sensitive per RFC 6376/7489, and values keep their case.
|
||||
func tagValue(record, tag string) (string, bool) {
|
||||
for _, part := range strings.Split(record, ";") {
|
||||
part = strings.TrimSpace(part)
|
||||
key, value, found := strings.Cut(part, "=")
|
||||
if !found {
|
||||
continue
|
||||
}
|
||||
if strings.TrimSpace(key) == tag {
|
||||
return strings.TrimSpace(value), true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package dnscheck
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"codeberg.org/mix/selfpost/internal/health"
|
||||
)
|
||||
|
||||
// checkServer resolves the panel's own hostname and confirms the reverse
|
||||
// lookup of each address points back at that name (FCrDNS). A missing or
|
||||
// mismatched PTR is the single most common reason mail from a self-hosted
|
||||
// server is rejected or scored as spam, which is why it is an error and not
|
||||
// advice.
|
||||
func (c *Checker) checkServer(ctx context.Context, hostname string) Server {
|
||||
srv := Server{Hostname: hostname, CheckedAt: time.Now()}
|
||||
if hostname == "" {
|
||||
srv.PTR = Result{
|
||||
Status: health.StatusUnknown,
|
||||
Detail: "SELFPOST_HOSTNAME is not set, so the server's own name in DNS cannot be checked. Set it in the deployment environment.",
|
||||
}
|
||||
return srv
|
||||
}
|
||||
|
||||
addrs, err := c.resolver.LookupIPAddr(ctx, hostname)
|
||||
if err != nil || len(addrs) == 0 {
|
||||
srv.PTR = Result{
|
||||
Status: health.StatusError,
|
||||
Detail: fmt.Sprintf("%s does not resolve to any address. Publish an A (or AAAA) record for it — receiving servers check the name this server announces in HELO.", hostname),
|
||||
}
|
||||
return srv
|
||||
}
|
||||
|
||||
want := normalizeName(hostname)
|
||||
matched, total := 0, len(addrs)
|
||||
var records []string
|
||||
for _, a := range addrs {
|
||||
ip := a.IP.String()
|
||||
srv.IPs = append(srv.IPs, ip)
|
||||
|
||||
names, err := c.resolver.LookupAddr(ctx, ip)
|
||||
if err != nil || len(names) == 0 {
|
||||
records = append(records, ip+" → no PTR record")
|
||||
continue
|
||||
}
|
||||
hit := false
|
||||
for _, n := range names {
|
||||
if normalizeName(n) == want {
|
||||
hit = true
|
||||
}
|
||||
}
|
||||
if hit {
|
||||
matched++
|
||||
records = append(records, ip+" → "+normalizeName(names[0]))
|
||||
} else {
|
||||
records = append(records, ip+" → "+normalizeName(names[0])+" (does not match)")
|
||||
}
|
||||
}
|
||||
|
||||
srv.PTR.Records = records
|
||||
switch {
|
||||
case matched == total:
|
||||
srv.PTR.Status = health.StatusOK
|
||||
srv.PTR.Detail = fmt.Sprintf("%s resolves to %s and the reverse lookup points back at it.", hostname, joinIPs(srv.IPs))
|
||||
case matched > 0:
|
||||
srv.PTR.Status = health.StatusWarn
|
||||
srv.PTR.Detail = fmt.Sprintf("Only %d of %d addresses of %s have a matching PTR record. Mail sent from the others may be rejected — set the reverse DNS of every address at your hosting provider.", matched, total, hostname)
|
||||
default:
|
||||
srv.PTR.Status = health.StatusError
|
||||
srv.PTR.Detail = fmt.Sprintf("No address of %s has a reverse (PTR) record pointing back at it. Many receiving servers reject or spam-score mail from such a host — set the reverse DNS of the server's IP to %s at your hosting provider.", hostname, hostname)
|
||||
}
|
||||
return srv
|
||||
}
|
||||
|
||||
func joinIPs(ips []string) string {
|
||||
switch len(ips) {
|
||||
case 0:
|
||||
return "no address"
|
||||
case 1:
|
||||
return ips[0]
|
||||
default:
|
||||
out := ips[0]
|
||||
for _, ip := range ips[1:] {
|
||||
out += ", " + ip
|
||||
}
|
||||
return out
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
package dnscheck
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
|
||||
"codeberg.org/mix/selfpost/internal/health"
|
||||
)
|
||||
|
||||
// spfLookupBudget caps how many DNS lookups one SPF evaluation may spend on
|
||||
// a/mx mechanisms. RFC 7208 allows a receiver ten; staying under the same
|
||||
// ceiling keeps a hostile or careless record from turning a page view into a
|
||||
// long chain of queries.
|
||||
const spfLookupBudget = 10
|
||||
|
||||
// checkSPF reports whether the domain's SPF record authorises this server.
|
||||
//
|
||||
// This is deliberately a shallow check (see docs/implementation-plan.md, phase
|
||||
// 13.B.2): it looks for a mechanism that literally covers the server's address —
|
||||
// ip4:/ip6:, or a/mx resolving to it — and does not recurse into include: or
|
||||
// redirect=, nor evaluate the record the way a receiver would. That is why a
|
||||
// record which does not obviously cover us but does use include: is reported as
|
||||
// a warning ("cannot tell") rather than a failure.
|
||||
func (c *Checker) checkSPF(ctx context.Context, q Query) Result {
|
||||
ips := parseIPs(q.ServerIPs)
|
||||
if len(ips) == 0 {
|
||||
return Result{
|
||||
Status: health.StatusUnknown,
|
||||
Detail: "The server's own address is not known (its hostname does not resolve), so SPF coverage cannot be checked. Fix the hostname/PTR check first.",
|
||||
}
|
||||
}
|
||||
|
||||
txt, found, err := c.lookupTXT(ctx, q.Name)
|
||||
if err != nil {
|
||||
return lookupFailed("the SPF record", err)
|
||||
}
|
||||
|
||||
var records []string
|
||||
for _, rec := range txt {
|
||||
if isSPF(rec) {
|
||||
records = append(records, strings.TrimSpace(rec))
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case !found || len(records) == 0:
|
||||
return Result{
|
||||
Status: health.StatusError,
|
||||
Detail: fmt.Sprintf("No SPF record is published for %s. Publish a TXT record such as \"v=spf1 ip4:%s -all\" — without it receivers have nothing authorising this server to send as the domain.", q.Name, ips[0]),
|
||||
}
|
||||
case len(records) > 1:
|
||||
return Result{
|
||||
Status: health.StatusError,
|
||||
Detail: fmt.Sprintf("More than one SPF record is published for %s. RFC 7208 allows exactly one; receivers treat several as a permanent error and the domain gets no SPF pass at all. Merge them into a single record.", q.Name),
|
||||
Records: records,
|
||||
}
|
||||
}
|
||||
|
||||
matched, unfollowed := c.evaluateSPF(ctx, records[0], q.Name, ips)
|
||||
switch {
|
||||
case matched == "+all" || matched == "all":
|
||||
return Result{
|
||||
Status: health.StatusWarn,
|
||||
Detail: "The SPF record ends with \"+all\", which authorises every server on the internet to send as this domain. Replace it with an explicit ip4:/ip6: or a mechanism plus \"-all\".",
|
||||
Records: records,
|
||||
}
|
||||
case matched != "":
|
||||
return Result{
|
||||
Status: health.StatusOK,
|
||||
Detail: fmt.Sprintf("The SPF record authorises this server through its %q mechanism.", matched),
|
||||
Records: records,
|
||||
}
|
||||
case len(unfollowed) > 0:
|
||||
return Result{
|
||||
Status: health.StatusWarn,
|
||||
Detail: fmt.Sprintf("No mechanism in the SPF record lists %s directly, but the record uses %s, which this check does not follow — the server may still be authorised through it. Verify with an external SPF validator, or add \"ip4:%s\" to be sure.",
|
||||
ips[0], strings.Join(unfollowed, ", "), ips[0]),
|
||||
Records: records,
|
||||
}
|
||||
default:
|
||||
return Result{
|
||||
Status: health.StatusError,
|
||||
Detail: fmt.Sprintf("The SPF record does not authorise %s, so mail sent from this server fails SPF. Add \"ip4:%s\" (or an \"a\" mechanism resolving here) to the record.", ips[0], ips[0]),
|
||||
Records: records,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// evaluateSPF walks the record's mechanisms, returning the first one that
|
||||
// covers one of the server's addresses, plus the mechanisms this shallow check
|
||||
// cannot resolve (include:/redirect=/exists:/ptr and anything past the lookup
|
||||
// budget) so the caller can say "cannot tell" instead of "fails".
|
||||
func (c *Checker) evaluateSPF(ctx context.Context, record, domainName string, ips []net.IP) (matched string, unfollowed []string) {
|
||||
budget := spfLookupBudget
|
||||
seenUnfollowed := make(map[string]bool)
|
||||
note := func(kind string) {
|
||||
if !seenUnfollowed[kind] {
|
||||
seenUnfollowed[kind] = true
|
||||
unfollowed = append(unfollowed, kind)
|
||||
}
|
||||
}
|
||||
|
||||
terms := strings.Fields(record)
|
||||
if len(terms) > 0 {
|
||||
terms = terms[1:] // drop the v=spf1 version token
|
||||
}
|
||||
for _, term := range terms {
|
||||
qualifier, mech := splitQualifier(term)
|
||||
lower := strings.ToLower(mech)
|
||||
name, hasArg := mechanismArg(mech)
|
||||
|
||||
switch {
|
||||
case strings.HasPrefix(lower, "ip4:"), strings.HasPrefix(lower, "ip6:"):
|
||||
if qualifier != '+' {
|
||||
continue
|
||||
}
|
||||
if coversAny(mech[4:], ips) {
|
||||
return term, unfollowed
|
||||
}
|
||||
|
||||
case lower == "a" || strings.HasPrefix(lower, "a:") || strings.HasPrefix(lower, "a/"):
|
||||
if strings.Contains(mech, "/") { // prefix-length form: not evaluated
|
||||
note("a/<prefix>")
|
||||
continue
|
||||
}
|
||||
target := domainName
|
||||
if hasArg {
|
||||
target = name
|
||||
}
|
||||
if budget <= 0 {
|
||||
note("further lookups")
|
||||
continue
|
||||
}
|
||||
budget--
|
||||
if qualifier == '+' && c.resolvesTo(ctx, target, ips) {
|
||||
return term, unfollowed
|
||||
}
|
||||
|
||||
case lower == "mx" || strings.HasPrefix(lower, "mx:") || strings.HasPrefix(lower, "mx/"):
|
||||
if strings.Contains(mech, "/") {
|
||||
note("mx/<prefix>")
|
||||
continue
|
||||
}
|
||||
target := domainName
|
||||
if hasArg {
|
||||
target = name
|
||||
}
|
||||
if budget <= 0 {
|
||||
note("further lookups")
|
||||
continue
|
||||
}
|
||||
budget--
|
||||
if qualifier == '+' && c.mxResolvesTo(ctx, target, ips, &budget) {
|
||||
return term, unfollowed
|
||||
}
|
||||
|
||||
case strings.HasPrefix(lower, "include:"):
|
||||
note("include:")
|
||||
case strings.HasPrefix(lower, "redirect="):
|
||||
note("redirect=")
|
||||
case strings.HasPrefix(lower, "exists:"):
|
||||
note("exists:")
|
||||
case lower == "ptr" || strings.HasPrefix(lower, "ptr:"):
|
||||
note("ptr")
|
||||
|
||||
case lower == "all":
|
||||
if qualifier == '+' {
|
||||
return "+all", unfollowed
|
||||
}
|
||||
// "-all"/"~all"/"?all" terminates the record: nothing after it is
|
||||
// evaluated by a receiver either.
|
||||
return "", unfollowed
|
||||
}
|
||||
}
|
||||
return "", unfollowed
|
||||
}
|
||||
|
||||
// resolvesTo reports whether name resolves to one of the server's addresses.
|
||||
func (c *Checker) resolvesTo(ctx context.Context, name string, ips []net.IP) bool {
|
||||
addrs, err := c.resolver.LookupIPAddr(ctx, name)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
for _, a := range addrs {
|
||||
for _, ip := range ips {
|
||||
if a.IP.Equal(ip) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// mxResolvesTo reports whether any of name's MX hosts resolves to one of the
|
||||
// server's addresses, spending at most the remaining lookup budget.
|
||||
func (c *Checker) mxResolvesTo(ctx context.Context, name string, ips []net.IP, budget *int) bool {
|
||||
mxs, err := c.resolver.LookupMX(ctx, name)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
for _, mx := range mxs {
|
||||
if *budget <= 0 {
|
||||
return false
|
||||
}
|
||||
*budget--
|
||||
if c.resolvesTo(ctx, strings.TrimSuffix(mx.Host, "."), ips) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// coversAny reports whether an ip4:/ip6: value — a bare address or a CIDR —
|
||||
// contains one of the server's addresses.
|
||||
func coversAny(value string, ips []net.IP) bool {
|
||||
value = strings.TrimSpace(value)
|
||||
if strings.Contains(value, "/") {
|
||||
_, network, err := net.ParseCIDR(value)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
for _, ip := range ips {
|
||||
if network.Contains(ip) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
listed := net.ParseIP(value)
|
||||
if listed == nil {
|
||||
return false
|
||||
}
|
||||
for _, ip := range ips {
|
||||
if listed.Equal(ip) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// splitQualifier peels the optional +/-/~/? qualifier off a mechanism,
|
||||
// defaulting to "+" (pass) as RFC 7208 does.
|
||||
func splitQualifier(term string) (byte, string) {
|
||||
if term == "" {
|
||||
return '+', ""
|
||||
}
|
||||
switch term[0] {
|
||||
case '+', '-', '~', '?':
|
||||
return term[0], term[1:]
|
||||
default:
|
||||
return '+', term
|
||||
}
|
||||
}
|
||||
|
||||
// mechanismArg returns the ":" argument of a mechanism, if it has one.
|
||||
func mechanismArg(mech string) (string, bool) {
|
||||
_, arg, found := strings.Cut(mech, ":")
|
||||
if !found || arg == "" {
|
||||
return "", false
|
||||
}
|
||||
return arg, true
|
||||
}
|
||||
|
||||
// isSPF reports whether a TXT record is an SPF record (the version token must
|
||||
// be the whole first term, so "v=spf10" is not one).
|
||||
func isSPF(record string) bool {
|
||||
rec := strings.TrimSpace(record)
|
||||
if len(rec) < 6 || !strings.EqualFold(rec[:6], "v=spf1") {
|
||||
return false
|
||||
}
|
||||
return len(rec) == 6 || rec[6] == ' ' || rec[6] == '\t'
|
||||
}
|
||||
|
||||
// parseIPs converts the string addresses carried on a Query back into net.IPs,
|
||||
// dropping anything unparsable.
|
||||
func parseIPs(in []string) []net.IP {
|
||||
var ips []net.IP
|
||||
for _, s := range in {
|
||||
if ip := net.ParseIP(s); ip != nil {
|
||||
ips = append(ips, ip)
|
||||
}
|
||||
}
|
||||
return ips
|
||||
}
|
||||
Reference in New Issue
Block a user