oficina / docs Public

Keep the sign-in tests' Keymail discovery in the process

Astra's first review on #76: TestSigninNeverWaitsForTheMailer's two
unforced POSTs asked the real resolver whether example.test runs
Keymail, so slow discovery could fail its two-second bound with the
queue working. TestMain now installs keymailtest (Slides' and Calendar's
stub) for the whole internal/docs binary and still fails the run on a
leaked mail worker or log pump. The timing test keeps its unforced and
forced cases.

One change from Slides' copy: home/roster clones http.DefaultTransport
as an *http.Transport, so Install leaves one there (an HTTP/1-only
clone with the fixture router registered for "https") instead of a
wrapper type.

TestKeymailDiscoveryStaysInProcess requires example.com, which public
DNS resolves, to come back NXDOMAIN; without the stub it resolved.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 7144e410f68add1a40afc832f9c8e4416940d168 parent 0e5421b
3 files changed, +251 −1
  • internal/docs/keymail_hermetic_test.go +25 −0
  • internal/docs/keymailtest/keymailtest.go +211 −0
  • internal/docs/mailqueue_test.go +15 −1

CI passed — run details

diff --git a/internal/docs/keymail_hermetic_test.go b/internal/docs/keymail_hermetic_test.go
new file mode 100644
index 0000000..28cf9d8
--- /dev/null
+++ b/internal/docs/keymail_hermetic_test.go
@@ -0,0 +1,25 @@
+package docs
+
+import (
+ "context"
+ "errors"
+ "net"
+ "testing"
+ "time"
+)
+
+// TestKeymailDiscoveryStaysInProcess: every unforced POST /signin
+// classifies its address (rastrillo/auth's Keymail discovery), so this
+// package's tests — TestSigninNeverWaitsForTheMailer's timing above all
+// — must not ask the real network whether a domain runs Keymail. With
+// keymailtest installed (TestMain) every query is answered NXDOMAIN
+// in-process, so even example.com, which public DNS resolves, must not.
+func TestKeymailDiscoveryStaysInProcess(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ addrs, err := net.DefaultResolver.LookupHost(ctx, "example.com")
+ var dnsErr *net.DNSError
+ if !errors.As(err, &dnsErr) || !dnsErr.IsNotFound {
+ t.Fatalf("LookupHost(example.com) = %v, %v; want NXDOMAIN from keymailtest's in-process resolver", addrs, err)
+ }
+}
diff --git a/internal/docs/keymailtest/keymailtest.go b/internal/docs/keymailtest/keymailtest.go
new file mode 100644
index 0000000..352458d
--- /dev/null
+++ b/internal/docs/keymailtest/keymailtest.go
@@ -0,0 +1,211 @@
+// Package keymailtest keeps sign-in's Keymail classification inside the
+// test process. It is imported by tests only.
+//
+// rastrillo/auth (at the version this app pins) builds its classifier
+// with no seams: TXT lookups go through net.DefaultResolver and the
+// well-known probe, the federation lookup and the token exchange go
+// through http.DefaultTransport. So those two globals are the hooks
+// (auth_keymail_test.go's isolated OAuth child swaps the same two).
+// Install replaces both for the life of the test binary:
+//
+// - every DNS query is answered NXDOMAIN by a resolver on loopback,
+// so no DNS packet leaves the process, and a domain with no
+// `_keymail` record is probed directly — keymail.dev's own shape;
+// - an https request to a host registered with Serve is answered
+// in-process by that fixture; anything else falls through to the
+// real transport, where the resolver above makes a name
+// unreachable (IP literals, which httptest servers use, still work).
+//
+// Every address at a domain nobody registered therefore classifies as
+// "not Keymail", which is what every pre-existing sign-in test assumes.
+//
+// Unlike Slides' copy, http.DefaultTransport stays an *http.Transport:
+// home/roster clones it with a type assertion when a team runtime has
+// no transport of its own. Install puts a clone in its place, HTTP/1
+// only, with the fixture router registered for "https"
+// (RegisterProtocol); a host nobody registered is skipped
+// (ErrSkipAltProtocol) and dialled as usual.
+package keymailtest
+
+import (
+ "context"
+ "crypto/rand"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "time"
+)
+
+var (
+ mu sync.Mutex
+ servers = map[string]*Server{}
+)
+
+// Install swaps net.DefaultResolver and http.DefaultTransport for the
+// stubs described in the package comment and returns a function that
+// puts them back. Call it once, from TestMain.
+func Install() (restore func(), err error) {
+ dns, err := net.ListenPacket("udp", "127.0.0.1:0")
+ if err != nil {
+ return nil, err
+ }
+ go answerNXDOMAIN(dns)
+ oldResolver, oldTransport := net.DefaultResolver, http.DefaultTransport
+ base, ok := oldTransport.(*http.Transport)
+ if !ok {
+ _ = dns.Close()
+ return nil, fmt.Errorf("keymailtest: http.DefaultTransport is %T, not *http.Transport", oldTransport)
+ }
+ tr := base.Clone()
+ // HTTP/1 only: the bundled HTTP/2 claims the "https" slot on first
+ // use, and the fixture router must hold it.
+ tr.Protocols = new(http.Protocols)
+ tr.Protocols.SetHTTP1(true)
+ tr.RegisterProtocol("https", fixtures{})
+ net.DefaultResolver = &net.Resolver{PreferGo: true, Dial: func(ctx context.Context, _, _ string) (net.Conn, error) {
+ return (&net.Dialer{}).DialContext(ctx, "udp", dns.LocalAddr().String())
+ }}
+ http.DefaultTransport = tr
+ return func() {
+ net.DefaultResolver, http.DefaultTransport = oldResolver, oldTransport
+ _ = dns.Close()
+ }, nil
+}
+
+// answerNXDOMAIN echoes each query back as a "no such name" answer.
+func answerNXDOMAIN(conn net.PacketConn) {
+ b := make([]byte, 4096)
+ for {
+ n, addr, err := conn.ReadFrom(b)
+ if err != nil {
+ return
+ }
+ if n < 12 {
+ continue
+ }
+ reply := append([]byte(nil), b[:n]...)
+ reply[2], reply[3] = 0x81, 0x83 // response, recursion, NXDOMAIN
+ for i := 6; i < 12; i++ {
+ reply[i] = 0 // no answer, authority or additional records
+ }
+ _, _ = conn.WriteTo(reply, addr)
+ }
+}
+
+// fixtures answers https requests to a registered host in-process and
+// hands every other request back to the transport.
+type fixtures struct{}
+
+func (fixtures) RoundTrip(r *http.Request) (*http.Response, error) {
+ mu.Lock()
+ s := servers[r.URL.Host]
+ mu.Unlock()
+ if s == nil || r.URL.Scheme != "https" {
+ return nil, http.ErrSkipAltProtocol
+ }
+ rec := httptest.NewRecorder()
+ s.ServeHTTP(rec, r)
+ res := rec.Result()
+ res.Request = r
+ return res, nil
+}
+
+// Server is one Keymail deployment at one host: the well-known
+// document, the federation lookup for the accounts it holds, and the
+// token exchange for the codes Approve hands out.
+type Server struct {
+ host string
+
+ mu sync.Mutex
+ accounts map[string]bool
+ codes map[string]string
+ lookups int
+ tokens int
+}
+
+// Serve registers a Keymail deployment at host (which is also the
+// address domain it answers for, since nothing publishes a `_keymail`
+// record) holding the given accounts. It is unregistered when the test
+// ends.
+func Serve(t interface{ Cleanup(func()) }, host string, accounts ...string) *Server {
+ s := &Server{host: host, accounts: map[string]bool{}, codes: map[string]string{}}
+ for _, a := range accounts {
+ s.accounts[strings.ToLower(a)] = true
+ }
+ mu.Lock()
+ servers[host] = s
+ mu.Unlock()
+ t.Cleanup(func() {
+ mu.Lock()
+ delete(servers, host)
+ mu.Unlock()
+ })
+ return s
+}
+
+// Approve is Keymail's consent screen saying yes for address: it
+// returns the code the browser would carry back to /auth/callback.
+func (s *Server) Approve(address string) string {
+ var b [12]byte
+ _, _ = rand.Read(b[:])
+ code := hex.EncodeToString(b[:])
+ s.mu.Lock()
+ s.codes[code] = address
+ s.mu.Unlock()
+ return code
+}
+
+// Lookups is how many federation lookups reached this deployment.
+func (s *Server) Lookups() int {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.lookups
+}
+
+// Tokens is how many token exchanges reached this deployment.
+func (s *Server) Tokens() int {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.tokens
+}
+
+func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ switch r.URL.Path {
+ case "/.well-known/keymail":
+ _ = json.NewEncoder(w).Encode(map[string]any{"version": "1", "reauth": true})
+ case "/api/federation/lookup":
+ s.mu.Lock()
+ s.lookups++
+ ok := s.accounts[strings.ToLower(r.URL.Query().Get("addr"))]
+ s.mu.Unlock()
+ if !ok {
+ w.WriteHeader(http.StatusNotFound)
+ }
+ _ = json.NewEncoder(w).Encode(map[string]bool{"ok": ok})
+ case "/api/oauth/token":
+ var in map[string]string
+ _ = json.NewDecoder(r.Body).Decode(&in)
+ s.mu.Lock()
+ s.tokens++
+ address, ok := s.codes[in["code"]]
+ delete(s.codes, in["code"])
+ s.mu.Unlock()
+ if r.Method != http.MethodPost || !ok {
+ w.WriteHeader(http.StatusBadRequest)
+ _ = json.NewEncoder(w).Encode(map[string]string{"error": "invalid_grant"})
+ return
+ }
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "access_token": "synthetic", "token_type": "bearer",
+ "address": address, "auth_time": time.Now().Unix(),
+ })
+ default:
+ w.WriteHeader(http.StatusNotFound)
+ }
+}
diff --git a/internal/docs/mailqueue_test.go b/internal/docs/mailqueue_test.go
index 57623a5..d4b9518 100644
--- a/internal/docs/mailqueue_test.go
+++ b/internal/docs/mailqueue_test.go
@@ -10,6 +10,8 @@ import (
"sync"
"testing"
"time"
+
+ "github.com/carlosframework/docs/internal/docs/keymailtest"
)
// stuckHandler is a slog handler whose every write blocks until release
@@ -266,10 +268,21 @@ func TestMailQueueCloseIsBoundedWithAStalledLogger(t *testing.T) {
}
}
-// TestMain fails the run if any sign-in mail queue worker or log pump
+// TestMain keeps Keymail classification inside the process: every
+// unforced POST /signin classifies its address, and without this each
+// one would ask the real network whether the domain runs Keymail. Every
+// DNS query is answered NXDOMAIN and only fixtures a test registers
+// answer HTTPS (keymailtest), so every address here is plain email.
+//
+// It also fails the run if any sign-in mail queue worker or log pump
// outlives the package's tests: every app a test builds is closed in its
// cleanup (NewForTestWith).
func TestMain(m *testing.M) {
+ restore, err := keymailtest.Install()
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "keymailtest.Install:", err)
+ os.Exit(1)
+ }
code := m.Run()
if code == 0 {
deadline := time.Now().Add(5 * time.Second)
@@ -281,5 +294,6 @@ func TestMain(m *testing.M) {
code = 1
}
}
+ restore()
os.Exit(code)
}