Commit b5899c314a for bind

commit b5899c314a1ccd3738c3a5426158586264017f10
Author: Štěpán Balážik <stepan@isc.org>
Date:   Mon Oct 19 12:09:11 2026 +0200

    Define the handlers in the order they are installed

    A reader meets the handlers in the install call and looks them up in
    the file; defined in that order, a base class before its subclasses,
    the file reads in dispatch order.

    Assisted-by: Claude:claude-fable-5-1

diff --git a/bin/tests/system/chain/ans3/ans.py b/bin/tests/system/chain/ans3/ans.py
index 4a4acdcda0..487b2861ba 100644
--- a/bin/tests/system/chain/ans3/ans.py
+++ b/bin/tests/system/chain/ans3/ans.py
@@ -78,22 +78,6 @@ class CnameThenDnameHandler(ResponseHandler):
         yield DnsResponseSend(qctx.response)


-class DnameOwnerWithoutAuthorityHandler(ResponseHandler):
-    """
-    Answer at the DNAME owner from zone data, with the authority section
-    stripped.
-    """
-
-    matcher = Qname("self.example.dname.")
-
-    async def get_responses(
-        self, qctx: QueryContext
-    ) -> AsyncGenerator[DnsResponseSend, None]:
-        del qctx.response.authority[:]
-        qctx.response.set_rcode(dns.rcode.NOERROR)
-        yield DnsResponseSend(qctx.response)
-
-
 class CnameToDnameOwnerHandler(ResponseHandler):
     """
     Attempt to trigger the resolver variant of CVE-2021-25215.  A `named`
@@ -119,6 +103,22 @@ class CnameToDnameOwnerHandler(ResponseHandler):
         yield DnsResponseSend(qctx.response)


+class DnameOwnerWithoutAuthorityHandler(ResponseHandler):
+    """
+    Answer at the DNAME owner from zone data, with the authority section
+    stripped.
+    """
+
+    matcher = Qname("self.example.dname.")
+
+    async def get_responses(
+        self, qctx: QueryContext
+    ) -> AsyncGenerator[DnsResponseSend, None]:
+        del qctx.response.authority[:]
+        qctx.response.set_rcode(dns.rcode.NOERROR)
+        yield DnsResponseSend(qctx.response)
+
+
 def main() -> None:
     server = AsyncDnsServer(acknowledge_manual_dname_handling=True, default_aa=True)
     server.install_response_handlers(
diff --git a/bin/tests/system/cookie/cookie_ans.py b/bin/tests/system/cookie/cookie_ans.py
index 70c9810024..27eba55a05 100644
--- a/bin/tests/system/cookie/cookie_ans.py
+++ b/bin/tests/system/cookie/cookie_ans.py
@@ -81,30 +81,38 @@ def legit_a(qctx: QueryContext) -> dns.rrset.RRset:
     return rrset(qctx.qname, dns.rdatatype.A, ANS9.ip)


-def spoofed_a(qctx: QueryContext) -> dns.rrset.RRset:
-    return rrset(qctx.qname, dns.rdatatype.A, ANS10.ip)
-
+class CookielessTcpAHandler(ResponseHandler):
+    matcher = (
+        Qtype(dns.rdatatype.A) & Protocol(DnsProtocol.TCP) & LeftmostLabel(b"nocookie")
+    )

-class _SpoofableHandler(ResponseHandler, abc.ABC):
-    def __init__(self, evil_server: bool) -> None:
-        self.evil_server = evil_server
+    async def get_responses(
+        self, qctx: QueryContext
+    ) -> AsyncGenerator[DnsResponseSend, None]:
+        qctx.response.answer.append(legit_a(qctx))
+        yield DnsResponseSend(qctx.response)


-class NsHandler(_SpoofableHandler):
-    matcher = Qtype(dns.rdatatype.NS) & LabelCount(2)
+class FallbackSoaHandler(ResponseHandler):
+    matcher = Qtype(dns.rdatatype.SOA)

     async def get_responses(
         self, qctx: QueryContext
     ) -> AsyncGenerator[DnsResponseSend, None]:
         add_cookie(qctx)
-        qctx.response.answer.append(ns(qctx))
-        if self.evil_server:
-            qctx.response.authority.append(spoofed_a(qctx))
-        else:
-            qctx.response.authority.append(legit_a(qctx))
+        qctx.response.answer.append(soa(qctx))
         yield DnsResponseSend(qctx.response)


+def spoofed_a(qctx: QueryContext) -> dns.rrset.RRset:
+    return rrset(qctx.qname, dns.rdatatype.A, ANS10.ip)
+
+
+class _SpoofableHandler(ResponseHandler, abc.ABC):
+    def __init__(self, evil_server: bool) -> None:
+        self.evil_server = evil_server
+
+
 class GlueHandler(_SpoofableHandler):
     matcher = Qtype(dns.rdatatype.A) & LabelCount(3) & LeftmostLabel(b"ns")

@@ -119,26 +127,33 @@ class GlueHandler(_SpoofableHandler):
         yield DnsResponseSend(qctx.response)


-class CookielessTcpAHandler(ResponseHandler):
-    matcher = (
-        Qtype(dns.rdatatype.A) & Protocol(DnsProtocol.TCP) & LeftmostLabel(b"nocookie")
-    )
+class NsHandler(_SpoofableHandler):
+    matcher = Qtype(dns.rdatatype.NS) & LabelCount(2)

     async def get_responses(
         self, qctx: QueryContext
     ) -> AsyncGenerator[DnsResponseSend, None]:
-        qctx.response.answer.append(legit_a(qctx))
+        add_cookie(qctx)
+        qctx.response.answer.append(ns(qctx))
+        if self.evil_server:
+            qctx.response.authority.append(spoofed_a(qctx))
+        else:
+            qctx.response.authority.append(legit_a(qctx))
         yield DnsResponseSend(qctx.response)


-class TcpAHandler(ResponseHandler):
-    matcher = Qtype(dns.rdatatype.A) & Protocol(DnsProtocol.TCP)
+class SpoofedUdpAHandler(ResponseHandler):
+    matcher = (
+        Qtype(dns.rdatatype.A)
+        & Protocol(DnsProtocol.UDP)
+        & LeftmostLabel(b"nocookie", b"tcponly")
+    )

     async def get_responses(
         self, qctx: QueryContext
     ) -> AsyncGenerator[DnsResponseSend, None]:
-        add_cookie(qctx)
         qctx.response.answer.append(legit_a(qctx))
+        qctx.response.answer.append(spoofed_a(qctx))
         yield DnsResponseSend(qctx.response)


@@ -161,18 +176,14 @@ class WithtsigUdpAHandler(ResponseHandler):
         yield DnsResponseSend(qctx.response)


-class SpoofedUdpAHandler(ResponseHandler):
-    matcher = (
-        Qtype(dns.rdatatype.A)
-        & Protocol(DnsProtocol.UDP)
-        & LeftmostLabel(b"nocookie", b"tcponly")
-    )
+class TcpAHandler(ResponseHandler):
+    matcher = Qtype(dns.rdatatype.A) & Protocol(DnsProtocol.TCP)

     async def get_responses(
         self, qctx: QueryContext
     ) -> AsyncGenerator[DnsResponseSend, None]:
+        add_cookie(qctx)
         qctx.response.answer.append(legit_a(qctx))
-        qctx.response.answer.append(spoofed_a(qctx))
         yield DnsResponseSend(qctx.response)


@@ -187,17 +198,6 @@ class UdpAHandler(ResponseHandler):
         yield DnsResponseSend(qctx.response)


-class FallbackSoaHandler(ResponseHandler):
-    matcher = Qtype(dns.rdatatype.SOA)
-
-    async def get_responses(
-        self, qctx: QueryContext
-    ) -> AsyncGenerator[DnsResponseSend, None]:
-        add_cookie(qctx)
-        qctx.response.answer.append(soa(qctx))
-        yield DnsResponseSend(qctx.response)
-
-
 class FallbackHandler(ResponseHandler):
     async def get_responses(
         self, qctx: QueryContext
diff --git a/bin/tests/system/digdelv/ans7/ans.py b/bin/tests/system/digdelv/ans7/ans.py
index 4d87f335c3..be6cb7f759 100644
--- a/bin/tests/system/digdelv/ans7/ans.py
+++ b/bin/tests/system/digdelv/ans7/ans.py
@@ -19,14 +19,6 @@ from isctest.asyncserver.handlers import IgnoreAllQueries
 from isctest.asyncserver.matchers import Domain, Matcher


-class SilentHandler(IgnoreAllQueries):
-    """
-    Handler that doesn't respond.
-    """
-
-    matcher = Domain("silent.example")
-
-
 class CloseHandler(ResponseHandler):
     """
     Handler that doesn't respond and closes TCP connection.
@@ -69,6 +61,14 @@ class SilentEverySecondQueryHandler(IgnoreAllQueries):
     matcher = EverySecond(Domain("silent-then-servfail.example"))


+class SilentHandler(IgnoreAllQueries):
+    """
+    Handler that doesn't respond.
+    """
+
+    matcher = Domain("silent.example")
+
+
 def main() -> None:
     server = AsyncDnsServer(default_rcode=dns.rcode.SERVFAIL)
     server.install_response_handlers(
diff --git a/bin/tests/system/dnssec/ans10/ans.py b/bin/tests/system/dnssec/ans10/ans.py
index 6412b95f93..f26310f135 100644
--- a/bin/tests/system/dnssec/ans10/ans.py
+++ b/bin/tests/system/dnssec/ans10/ans.py
@@ -30,6 +30,18 @@ def rrset(
     return dns.rrset.from_text(owner, ttl, dns.rdataclass.IN, rdtype, rdata)


+class AddNsecToTxtHandler(ResponseHandler):
+    matcher = Qtype(dns.rdatatype.TXT)
+
+    async def get_responses(
+        self, qctx: QueryContext
+    ) -> AsyncGenerator[DnsResponseSend, None]:
+        nsec = f"{qctx.qname.to_text()} A NS SOA RRSIG NSEC"
+        nsec_rrset = rrset(qctx.qname, dns.rdatatype.NSEC, nsec, ttl=1)
+        qctx.response.authority.append(nsec_rrset)
+        yield DnsResponseSend(qctx.response)
+
+
 class AddRrsigToAHandler(ResponseHandler):
     matcher = Qtype(dns.rdatatype.A)

@@ -45,18 +57,6 @@ class AddRrsigToAHandler(ResponseHandler):
         yield DnsResponseSend(qctx.response)


-class AddNsecToTxtHandler(ResponseHandler):
-    matcher = Qtype(dns.rdatatype.TXT)
-
-    async def get_responses(
-        self, qctx: QueryContext
-    ) -> AsyncGenerator[DnsResponseSend, None]:
-        nsec = f"{qctx.qname.to_text()} A NS SOA RRSIG NSEC"
-        nsec_rrset = rrset(qctx.qname, dns.rdatatype.NSEC, nsec, ttl=1)
-        qctx.response.authority.append(nsec_rrset)
-        yield DnsResponseSend(qctx.response)
-
-
 def main() -> None:
     server = AsyncDnsServer()
     server.install_response_handlers(
diff --git a/bin/tests/system/dnssec_cname_response/ans2/ans.py b/bin/tests/system/dnssec_cname_response/ans2/ans.py
index 1ce86b2865..e3503f7599 100644
--- a/bin/tests/system/dnssec_cname_response/ans2/ans.py
+++ b/bin/tests/system/dnssec_cname_response/ans2/ans.py
@@ -80,10 +80,6 @@ class ExampleMetatypeCnameHandler(CnameHandler):
     )


-class SecureDsCnameHandler(CnameHandler):
-    matcher = Domain("secure.") & Qtype(dns.rdatatype.DS)
-
-
 class InsecureApexCnameHandler(CnameHandler):
     """
     Synthesize an apex CNAME, which conflicts with SOA/NS in a zone file.
@@ -92,6 +88,10 @@ class InsecureApexCnameHandler(CnameHandler):
     matcher = Qname("insecure.parent.") & Qtype(dns.rdatatype.A)


+class SecureDsCnameHandler(CnameHandler):
+    matcher = Domain("secure.") & Qtype(dns.rdatatype.DS)
+
+
 def soa_with_rrsig(zone: dns.zone.Zone) -> list[dns.rrset.RRset]:
     assert zone.origin
     return rrset_with_rrsig(zone, zone.origin, dns.rdatatype.SOA)
@@ -112,6 +112,23 @@ class NoNameIn(Matcher):
         return f"no name in {self._zone.origin}"


+class NxdomainHandler(SingleResponseHandler):
+    """
+    Answer NXDOMAIN from a signed zone, with its SOA.
+    """
+
+    rcode = dns.rcode.NXDOMAIN
+
+    def __init__(self, zone: dns.zone.Zone) -> None:
+        self._zone = zone
+        assert self._zone.origin
+        self.matcher = Domain(self._zone.origin) & NoNameIn(zone)
+
+    @property
+    def authority(self) -> Sequence[dns.rrset.RRset]:
+        return soa_with_rrsig(self._zone)
+
+
 class NoDataIn(Matcher):
     """
     Match queries the given zone holds no rdataset for.
@@ -130,9 +147,9 @@ class NoDataIn(Matcher):
         return f"no data in {self._zone.origin}"


-class NxdomainHandler(SingleResponseHandler):
+class StuffedNxdomainHandler(SingleResponseHandler):
     """
-    Answer NXDOMAIN from a signed zone, with its SOA.
+    Answer NXDOMAIN with every NSEC3 RRset from a signed zone.
     """

     rcode = dns.rcode.NXDOMAIN
@@ -140,11 +157,15 @@ class NxdomainHandler(SingleResponseHandler):
     def __init__(self, zone: dns.zone.Zone) -> None:
         self._zone = zone
         assert self._zone.origin
-        self.matcher = Domain(self._zone.origin) & NoNameIn(zone)
+        self.matcher = Domain(self._zone.origin) & NoDataIn(zone)

     @property
     def authority(self) -> Sequence[dns.rrset.RRset]:
-        return soa_with_rrsig(self._zone)
+        assert self._zone.origin
+        authority = rrset_with_rrsig(self._zone, self._zone.origin, dns.rdatatype.SOA)
+        for name, _ in self._zone.iterate_rdatasets(dns.rdatatype.NSEC3):
+            authority.extend(rrset_with_rrsig(self._zone, name, dns.rdatatype.NSEC3))
+        return authority


 class NodataHandler(SingleResponseHandler):
@@ -182,27 +203,6 @@ class SignedZoneHandler(ResponseHandler):
         yield DnsResponseSend(qctx.response)


-class StuffedNxdomainHandler(SingleResponseHandler):
-    """
-    Answer NXDOMAIN with every NSEC3 RRset from a signed zone.
-    """
-
-    rcode = dns.rcode.NXDOMAIN
-
-    def __init__(self, zone: dns.zone.Zone) -> None:
-        self._zone = zone
-        assert self._zone.origin
-        self.matcher = Domain(self._zone.origin) & NoDataIn(zone)
-
-    @property
-    def authority(self) -> Sequence[dns.rrset.RRset]:
-        assert self._zone.origin
-        authority = rrset_with_rrsig(self._zone, self._zone.origin, dns.rdatatype.SOA)
-        for name, _ in self._zone.iterate_rdatasets(dns.rdatatype.NSEC3):
-            authority.extend(rrset_with_rrsig(self._zone, name, dns.rdatatype.NSEC3))
-        return authority
-
-
 def main() -> None:
     server = AsyncDnsServer(default_rcode=dns.rcode.NOERROR, default_aa=True)
     server.install_response_handlers(
diff --git a/bin/tests/system/dnssec_wildcard/ans1/ans.py b/bin/tests/system/dnssec_wildcard/ans1/ans.py
index 1959a3659b..f5ad454637 100644
--- a/bin/tests/system/dnssec_wildcard/ans1/ans.py
+++ b/bin/tests/system/dnssec_wildcard/ans1/ans.py
@@ -54,23 +54,23 @@ def append_forged_a_rrset_to_additional(qctx: QueryContext, owner_name: str) ->
     # from a wildcard record.


-class WildcardAdditionalHandler(ResponseHandler):
-    matcher = Qname("svc.f043.test.") & Qtype(dns.rdatatype.MX)
+class ParentWildcardHandler(ResponseHandler):
+    matcher = Qname("q.f045.test.") & Qtype(dns.rdatatype.MX)

     async def get_responses(
         self, qctx: QueryContext
     ) -> AsyncGenerator[DnsResponseSend, None]:
-        append_forged_a_rrset_to_additional(qctx, "victim.f043.test.")
+        append_forged_a_rrset_to_additional(qctx, "svc.child.f045.test.")
         yield DnsResponseSend(qctx.response)


-class ParentWildcardHandler(ResponseHandler):
-    matcher = Qname("q.f045.test.") & Qtype(dns.rdatatype.MX)
+class WildcardAdditionalHandler(ResponseHandler):
+    matcher = Qname("svc.f043.test.") & Qtype(dns.rdatatype.MX)

     async def get_responses(
         self, qctx: QueryContext
     ) -> AsyncGenerator[DnsResponseSend, None]:
-        append_forged_a_rrset_to_additional(qctx, "svc.child.f045.test.")
+        append_forged_a_rrset_to_additional(qctx, "victim.f043.test.")
         yield DnsResponseSend(qctx.response)


diff --git a/bin/tests/system/fetchlimit/ans4/ans.py b/bin/tests/system/fetchlimit/ans4/ans.py
index 8db02f9869..f22e3897f6 100644
--- a/bin/tests/system/fetchlimit/ans4/ans.py
+++ b/bin/tests/system/fetchlimit/ans4/ans.py
@@ -48,6 +48,11 @@ class AHandler(ResponseHandler):
         yield DnsResponseSend(qctx.response, delay=self.delay)


+class DelayedAHandler(AHandler):
+    matcher = LeftmostLabelPrefix(b"latency") & Qtype(dns.rdatatype.A)
+    delay = 0.05
+
+
 class AaaaHandler(ResponseHandler):
     matcher: Matcher = Qtype(dns.rdatatype.AAAA)
     delay = 0.0
@@ -60,11 +65,6 @@ class AaaaHandler(ResponseHandler):
         yield DnsResponseSend(qctx.response, delay=self.delay)


-class DelayedAHandler(AHandler):
-    matcher = LeftmostLabelPrefix(b"latency") & Qtype(dns.rdatatype.A)
-    delay = 0.05
-
-
 class DelayedAaaaHandler(AaaaHandler):
     matcher = LeftmostLabelPrefix(b"latency") & Qtype(dns.rdatatype.AAAA)
     delay = 0.05
diff --git a/bin/tests/system/forward/ans6/ans.py b/bin/tests/system/forward/ans6/ans.py
index 7923849a08..d16a946ca4 100644
--- a/bin/tests/system/forward/ans6/ans.py
+++ b/bin/tests/system/forward/ans6/ans.py
@@ -49,18 +49,6 @@ def soa(owner: dns.name.Name | str) -> dns.rrset.RRset:
     return rrset(owner, dns.rdatatype.SOA, ". . 0 0 0 0 0")


-class Ns1AHandler(SingleResponseHandler):
-    matcher = Qname(NS1) & Qtype(dns.rdatatype.A)
-    answer = [a(NS1)]
-    edns = None
-
-
-class Ns1AaaaHandler(SingleResponseHandler):
-    matcher = Qname(NS1) & Qtype(dns.rdatatype.AAAA)
-    answer = [aaaa(NS1)]
-    edns = None
-
-
 class SldDelegationHandler(ResponseHandler):
     """
     Delegate every NS query at or below sld.tld. to ns1.sld.tld., copying the
@@ -79,6 +67,18 @@ class SldDelegationHandler(ResponseHandler):
         yield DnsResponseSend(qctx.response)


+class Ns1AHandler(SingleResponseHandler):
+    matcher = Qname(NS1) & Qtype(dns.rdatatype.A)
+    answer = [a(NS1)]
+    edns = None
+
+
+class Ns1AaaaHandler(SingleResponseHandler):
+    matcher = Qname(NS1) & Qtype(dns.rdatatype.AAAA)
+    answer = [aaaa(NS1)]
+    edns = None
+
+
 class NegativeSoaHandler(ResponseHandler):
     async def get_responses(
         self, qctx: QueryContext
diff --git a/bin/tests/system/ixfr/ans2/ans.py b/bin/tests/system/ixfr/ans2/ans.py
index 24c595e8c5..9a18fb4ede 100644
--- a/bin/tests/system/ixfr/ans2/ans.py
+++ b/bin/tests/system/ixfr/ans2/ans.py
@@ -77,10 +77,6 @@ class SoaHandler(SingleResponseHandler):
         return [soa(self._serial)]


-class IxfrHandler(SingleResponseHandler, abc.ABC):
-    matcher = Qtype(dns.rdatatype.IXFR)
-
-
 class InitialAxfrHandler(AxfrHandler):
     initial_soa = soa(1)
     zone_contents = (
@@ -92,6 +88,10 @@ class InitialAxfrHandler(AxfrHandler):
     final_soa = soa(1)


+class IxfrHandler(SingleResponseHandler, abc.ABC):
+    matcher = Qtype(dns.rdatatype.IXFR)
+
+
 class SuccessfulIxfrHandler(IxfrHandler):
     answer = (
         soa(3),
diff --git a/bin/tests/system/nsec3/ans7/ans.py b/bin/tests/system/nsec3/ans7/ans.py
index 13c8601011..7d77461dea 100644
--- a/bin/tests/system/nsec3/ans7/ans.py
+++ b/bin/tests/system/nsec3/ans7/ans.py
@@ -175,42 +175,6 @@ class Attack:
 ATTACK = Attack()


-class RelayForwarder(ForwarderHandler):
-    """
-    Relay the given query types -- or every query, if none are given -- to the
-    real authoritative server for evil.test.
-    """
-
-    target = NS6.ip
-
-    def __init__(self, *qtypes: dns.rdatatype.RdataType) -> None:
-        super().__init__()
-        self.matcher = Qtype(*qtypes) if qtypes else Always()
-
-
-class DsInjector(ResponseHandlerWrapper):
-    """
-    Inject the crafted NSEC3 at position 0 of the DS response's authority.
-    """
-
-    def _modify_response(
-        self, qctx: QueryContext, response_action: ResponseAction
-    ) -> None:
-        assert isinstance(
-            response_action, DnsResponseSend
-        ), "DsInjector can only wrap handlers that yield DnsResponseSend"
-        response = response_action.response
-        assert response.rcode() == dns.rcode.NXDOMAIN, "expected an opt-out denial"
-        response.set_rcode(dns.rcode.NOERROR)
-
-        authority = [ATTACK.crafted_nsec3, ATTACK.crafted_rrsig]
-        for rrset in response.authority:
-            if ATTACK.covers_inject(rrset.name):
-                continue
-            authority.append(rrset)
-        response.authority = authority
-
-
 class ProofBreaker(ResponseHandlerWrapper):
     """
     Overrun the modify-target NSEC3 in the A response and re-sign it.
@@ -261,6 +225,42 @@ class ProofBreaker(ResponseHandlerWrapper):
         return resigned


+class DsInjector(ResponseHandlerWrapper):
+    """
+    Inject the crafted NSEC3 at position 0 of the DS response's authority.
+    """
+
+    def _modify_response(
+        self, qctx: QueryContext, response_action: ResponseAction
+    ) -> None:
+        assert isinstance(
+            response_action, DnsResponseSend
+        ), "DsInjector can only wrap handlers that yield DnsResponseSend"
+        response = response_action.response
+        assert response.rcode() == dns.rcode.NXDOMAIN, "expected an opt-out denial"
+        response.set_rcode(dns.rcode.NOERROR)
+
+        authority = [ATTACK.crafted_nsec3, ATTACK.crafted_rrsig]
+        for rrset in response.authority:
+            if ATTACK.covers_inject(rrset.name):
+                continue
+            authority.append(rrset)
+        response.authority = authority
+
+
+class RelayForwarder(ForwarderHandler):
+    """
+    Relay the given query types -- or every query, if none are given -- to the
+    real authoritative server for evil.test.
+    """
+
+    target = NS6.ip
+
+    def __init__(self, *qtypes: dns.rdatatype.RdataType) -> None:
+        super().__init__()
+        self.matcher = Qtype(*qtypes) if qtypes else Always()
+
+
 def main() -> None:
     server = AsyncDnsServer(default_rcode=dns.rcode.NOERROR)
     server.install_response_handlers(
diff --git a/bin/tests/system/qmin/ans2/ans.py b/bin/tests/system/qmin/ans2/ans.py
index c4c525f699..fa4f25ba26 100644
--- a/bin/tests/system/qmin/ans2/ans.py
+++ b/bin/tests/system/qmin/ans2/ans.py
@@ -39,25 +39,6 @@ def rrset(
     return dns.rrset.from_text(owner, ttl, dns.rdataclass.IN, rdtype, rdata)


-class QueryLogger(QueryLogHandler):
-    matcher = Domain("1.0.0.2.ip6.arpa.", "fwd.", "good.", "stale.")
-
-
-class BadHandler(EntRcodeChanger):
-    matcher = Domain("bad.")
-    rcode = dns.rcode.NXDOMAIN
-
-
-class UglyHandler(EntRcodeChanger):
-    matcher = Domain("ugly.")
-    rcode = dns.rcode.FORMERR
-
-
-class SlowHandler(DelayedResponseHandler):
-    matcher = Domain("slow.")
-    delay = 0.2
-
-
 def send_delegation(
     qctx: QueryContext, zone_cut: dns.name.Name, target_addr: str
 ) -> DnsResponseSend:
@@ -107,6 +88,25 @@ class BStaleDelegationHandler(StaleDelegationHandler):
     address = ANS4.ip


+class BadHandler(EntRcodeChanger):
+    matcher = Domain("bad.")
+    rcode = dns.rcode.NXDOMAIN
+
+
+class QueryLogger(QueryLogHandler):
+    matcher = Domain("1.0.0.2.ip6.arpa.", "fwd.", "good.", "stale.")
+
+
+class SlowHandler(DelayedResponseHandler):
+    matcher = Domain("slow.")
+    delay = 0.2
+
+
+class UglyHandler(EntRcodeChanger):
+    matcher = Domain("ugly.")
+    rcode = dns.rcode.FORMERR
+
+
 def main() -> None:
     server = AsyncDnsServer()
     server.install_response_handlers(ABStaleDelegationHandler())
diff --git a/bin/tests/system/qmin/ans3/ans.py b/bin/tests/system/qmin/ans3/ans.py
index bc6787cec0..ba1d3cfaf1 100644
--- a/bin/tests/system/qmin/ans3/ans.py
+++ b/bin/tests/system/qmin/ans3/ans.py
@@ -26,16 +26,16 @@ class ZoopBoingBadHandler(EntRcodeChanger):
     rcode = dns.rcode.NXDOMAIN


-class ZoopBoingUglyHandler(EntRcodeChanger):
-    matcher = Domain("zoop.boing.ugly.")
-    rcode = dns.rcode.FORMERR
-
-
 class ZoopBoingSlowHandler(DelayedResponseHandler):
     matcher = Domain("zoop.boing.slow.")
     delay = 0.4


+class ZoopBoingUglyHandler(EntRcodeChanger):
+    matcher = Domain("zoop.boing.ugly.")
+    rcode = dns.rcode.FORMERR
+
+
 def main() -> None:
     server = AsyncDnsServer()
     server.install_response_handlers(
diff --git a/bin/tests/system/qmin/ans4/ans.py b/bin/tests/system/qmin/ans4/ans.py
index 7d2b5ecf42..d30a18ae0e 100644
--- a/bin/tests/system/qmin/ans4/ans.py
+++ b/bin/tests/system/qmin/ans4/ans.py
@@ -26,6 +26,21 @@ from ..qmin_ans import (
 )


+class IckyPtangZoopBoingBadHandler(EntRcodeChanger):
+    matcher = Domain("icky.ptang.zoop.boing.bad.")
+    rcode = dns.rcode.NXDOMAIN
+
+
+class IckyPtangZoopBoingSlowHandler(DelayedResponseHandler):
+    matcher = Domain("icky.ptang.zoop.boing.slow.")
+    delay = 0.4
+
+
+class IckyPtangZoopBoingUglyHandler(EntRcodeChanger):
+    matcher = Domain("icky.ptang.zoop.boing.ugly.")
+    rcode = dns.rcode.FORMERR
+
+
 class QueryLogger(QueryLogHandler):
     matcher = Domain("1.1.1.1.8.2.6.0.1.0.0.2.ip6.arpa.", "icky.ptang.zoop.boing.good.")

@@ -65,21 +80,6 @@ class StaleHandler(ResponseHandler):
         yield DnsResponseSend(qctx.response)


-class IckyPtangZoopBoingBadHandler(EntRcodeChanger):
-    matcher = Domain("icky.ptang.zoop.boing.bad.")
-    rcode = dns.rcode.NXDOMAIN
-
-
-class IckyPtangZoopBoingUglyHandler(EntRcodeChanger):
-    matcher = Domain("icky.ptang.zoop.boing.ugly.")
-    rcode = dns.rcode.FORMERR
-
-
-class IckyPtangZoopBoingSlowHandler(DelayedResponseHandler):
-    matcher = Domain("icky.ptang.zoop.boing.slow.")
-    delay = 0.4
-
-
 def main() -> None:
     server = AsyncDnsServer()
     server.install_response_handlers(
diff --git a/bin/tests/system/resend_loop/ans3/ans.py b/bin/tests/system/resend_loop/ans3/ans.py
index 39701fe26c..822ed8a33b 100644
--- a/bin/tests/system/resend_loop/ans3/ans.py
+++ b/bin/tests/system/resend_loop/ans3/ans.py
@@ -54,6 +54,12 @@ class ExampleNsHandler(SingleResponseHandler):
     additional = [a(f"ns.{matcher.of(Qname).qname}", ANS3.ip)]


+class TestDotComServFailHandler(SingleResponseHandler):
+    matcher = Qname("test.com.")
+    authoritative = False
+    rcode = dns.rcode.SERVFAIL
+
+
 class WithCookie(Matcher):
     """
     Match queries carrying an EDNS COOKIE option; the option of the last
@@ -102,12 +108,6 @@ class ExampleServfailHandler(SingleResponseHandler):
     rcode = dns.rcode.SERVFAIL


-class TestDotComServFailHandler(SingleResponseHandler):
-    matcher = Qname("test.com.")
-    authoritative = False
-    rcode = dns.rcode.SERVFAIL
-
-
 def main() -> None:
     server = AsyncDnsServer(default_aa=True, default_rcode=dns.rcode.NOERROR)
     server.install_response_handlers(
diff --git a/bin/tests/system/statschannel/ans5/ans.py b/bin/tests/system/statschannel/ans5/ans.py
index 052b6c17c2..5b1b896177 100644
--- a/bin/tests/system/statschannel/ans5/ans.py
+++ b/bin/tests/system/statschannel/ans5/ans.py
@@ -59,6 +59,14 @@ class AHandler(ResponseHandler):
         yield DnsResponseSend(qctx.response, delay=self.delay)


+class DelayedAHandler(AHandler):
+    matcher = Domain("latency.example2.") & DelayLabel() & Qtype(dns.rdatatype.A)
+
+    @property
+    def delay(self) -> float:
+        return int(self.matcher.of(DelayLabel).matched_label) / 1000
+
+
 class AaaaHandler(ResponseHandler):
     matcher: Matcher = Qtype(dns.rdatatype.AAAA)

@@ -74,14 +82,6 @@ class AaaaHandler(ResponseHandler):
         yield DnsResponseSend(qctx.response, delay=self.delay)


-class DelayedAHandler(AHandler):
-    matcher = Domain("latency.example2.") & DelayLabel() & Qtype(dns.rdatatype.A)
-
-    @property
-    def delay(self) -> float:
-        return int(self.matcher.of(DelayLabel).matched_label) / 1000
-
-
 class DelayedAaaaHandler(AaaaHandler):
     matcher = Domain("latency.example2.") & DelayLabel() & Qtype(dns.rdatatype.AAAA)

diff --git a/bin/tests/system/xfer/ans11/ans.py b/bin/tests/system/xfer/ans11/ans.py
index ac12292e46..8f0bf6ce4d 100644
--- a/bin/tests/system/xfer/ans11/ans.py
+++ b/bin/tests/system/xfer/ans11/ans.py
@@ -127,14 +127,6 @@ class InitialSoaHandler(TransferHandler, SingleResponseHandler):
         self.matcher = Qtype(dns.rdatatype.SOA) & ~InitialAxfrServed(progress)


-class RefreshSoaHandler(TransferHandler, SingleResponseHandler):
-    answer = [soa(4)]
-
-    def __init__(self, progress: TransferState) -> None:
-        super().__init__(progress)
-        self.matcher = Qtype(dns.rdatatype.SOA) & InitialAxfrServed(progress)
-
-
 class InitialAxfrHandler(TransferHandler, AxfrHandler):
     """
     Serve the initial zone (serial 1) and mark the transfer as done.
@@ -155,6 +147,14 @@ class InitialAxfrHandler(TransferHandler, AxfrHandler):
             yield action


+class RefreshSoaHandler(TransferHandler, SingleResponseHandler):
+    answer = [soa(4)]
+
+    def __init__(self, progress: TransferState) -> None:
+        super().__init__(progress)
+        self.matcher = Qtype(dns.rdatatype.SOA) & InitialAxfrServed(progress)
+
+
 class TruncatedIxfrHandler(ResponseHandler):
     """
     Set TC on an IXFR received over UDP to force the secondary to retry over TCP.
diff --git a/bin/tests/system/xfer/ans5/ans.py b/bin/tests/system/xfer/ans5/ans.py
index d11f14f12f..85cda4e76d 100644
--- a/bin/tests/system/xfer/ans5/ans.py
+++ b/bin/tests/system/xfer/ans5/ans.py
@@ -39,11 +39,6 @@ from ..xfer_ans import rrset

 GOOD_KEY_DATA = "LSAnCU+Z"
 DEFAULT_KEY = dns.tsig.Key("tsig_key", GOOD_KEY_DATA, ALG_VARS["DEFAULT_HMAC"])
-BAD_KEY = dns.tsig.Key("bad_key", GOOD_KEY_DATA, ALG_VARS["DEFAULT_HMAC"])
-UNUSED_KEY = dns.tsig.Key("unused_key", GOOD_KEY_DATA, ALG_VARS["DEFAULT_HMAC"])
-KEYRING = {key.name: key for key in (DEFAULT_KEY, BAD_KEY, UNUSED_KEY)}
-
-KEY_WITH_BAD_DATA = dns.tsig.Key("tsig_key", "abcd1234ffff", ALG_VARS["DEFAULT_HMAC"])


 class SignResponses(ResponseHandlerWrapper):
@@ -126,26 +121,6 @@ class SignFirstAndLastResponses(ResponseHandlerWrapper):
         return f"SignFirstAndLastResponses({self._inner}, key={self._key})"


-class Add50ToMessageIdFromSecondResponse(ResponseHandlerWrapper):
-    def __init__(self, inner: ResponseHandler) -> None:
-        super().__init__(inner)
-        self._first_yielded = False
-
-    async def _on_query_received(self, qctx: QueryContext) -> None:
-        self._first_yielded = False
-
-    def _modify_response(
-        self, qctx: QueryContext, response_action: ResponseAction
-    ) -> None:
-        if self._first_yielded:
-            assert isinstance(
-                response_action, DnsResponseSend
-            ), "Add50ToMessageIdFromSecondResponse can only wrap handlers that yield DnsResponseSend from the second response onward"
-            response_action.response.id = (response_action.response.id + 50) % 65536
-        else:
-            self._first_yielded = True
-
-
 class ClearTsig(ResponseHandlerWrapper):
     def _modify_response(
         self, qctx: QueryContext, response_action: ResponseAction
@@ -156,6 +131,13 @@ class ClearTsig(ResponseHandlerWrapper):
         response_action.response.tsig = None


+BAD_KEY = dns.tsig.Key("bad_key", GOOD_KEY_DATA, ALG_VARS["DEFAULT_HMAC"])
+UNUSED_KEY = dns.tsig.Key("unused_key", GOOD_KEY_DATA, ALG_VARS["DEFAULT_HMAC"])
+KEYRING = {key.name: key for key in (DEFAULT_KEY, BAD_KEY, UNUSED_KEY)}
+
+KEY_WITH_BAD_DATA = dns.tsig.Key("tsig_key", "abcd1234ffff", ALG_VARS["DEFAULT_HMAC"])
+
+
 def soa(
     serial: int,
     *,
@@ -227,6 +209,26 @@ class XferAxfrHandler(AxfrHandler):
         return soa(self._soa_serial)


+class Add50ToMessageIdFromSecondResponse(ResponseHandlerWrapper):
+    def __init__(self, inner: ResponseHandler) -> None:
+        super().__init__(inner)
+        self._first_yielded = False
+
+    async def _on_query_received(self, qctx: QueryContext) -> None:
+        self._first_yielded = False
+
+    def _modify_response(
+        self, qctx: QueryContext, response_action: ResponseAction
+    ) -> None:
+        if self._first_yielded:
+            assert isinstance(
+                response_action, DnsResponseSend
+            ), "Add50ToMessageIdFromSecondResponse can only wrap handlers that yield DnsResponseSend from the second response onward"
+            response_action.response.id = (response_action.response.id + 50) % 65536
+        else:
+            self._first_yielded = True
+
+
 class AboveApexAxfrHandler(XferAxfrHandler):
     @property
     def zone_contents(self) -> Collection[dns.rrset.RRset]:
@@ -235,6 +237,23 @@ class AboveApexAxfrHandler(XferAxfrHandler):
         return [*super().zone_contents, above_apex_ns]


+class AxfrEdnsRcodeHandler(SingleResponseHandler):
+    matcher = Qtype(dns.rdatatype.AXFR) & Edns()
+
+
+class AxfrEdnsFormerrHandler(AxfrEdnsRcodeHandler):
+    rcode = dns.rcode.FORMERR
+
+
+class AxfrEdnsNotimpHandler(AxfrEdnsRcodeHandler):
+    rcode = dns.rcode.NOTIMP
+
+
+class IxfrNotimpHandler(SingleResponseHandler):
+    matcher = Qtype(dns.rdatatype.IXFR)
+    rcode = dns.rcode.NOTIMP
+
+
 class WrongQnameInFinalSoa(ResponseHandlerWrapper):
     def __init__(self, inner: XferAxfrHandler) -> None:
         super().__init__(inner)
@@ -251,23 +270,6 @@ class WrongQnameInFinalSoa(ResponseHandlerWrapper):
         self._messages_until_final_soa -= 1


-class IxfrNotimpHandler(SingleResponseHandler):
-    matcher = Qtype(dns.rdatatype.IXFR)
-    rcode = dns.rcode.NOTIMP
-
-
-class AxfrEdnsRcodeHandler(SingleResponseHandler):
-    matcher = Qtype(dns.rdatatype.AXFR) & Edns()
-
-
-class AxfrEdnsFormerrHandler(AxfrEdnsRcodeHandler):
-    rcode = dns.rcode.FORMERR
-
-
-class AxfrEdnsNotimpHandler(AxfrEdnsRcodeHandler):
-    rcode = dns.rcode.NOTIMP
-
-
 def main() -> None:
     server = ControllableAsyncDnsServer(
         default_aa=True, default_rcode=dns.rcode.NOERROR, keyring=KEYRING
diff --git a/bin/tests/system/xfer/ans9/ans.py b/bin/tests/system/xfer/ans9/ans.py
index f10d2b6f74..a467383bed 100644
--- a/bin/tests/system/xfer/ans9/ans.py
+++ b/bin/tests/system/xfer/ans9/ans.py
@@ -103,19 +103,32 @@ class ZoneAxfrHandler(AxfrHandler, SerialCounted, abc.ABC):
         return soa(self.zone, self._serials.serial)


-class ReconfigAxfrHandler(ZoneAxfrHandler):
-    zone = "xfr-and-reconfig."
+class OverrunAxfrHandler(ZoneAxfrHandler):
+    """
+    Serve the malformed PRIVATEDNS DNSKEY overrun; see OVERRUN_DNSKEY.
+    """
+
+    zone = "private-dns-overrun."
+
+    # The malformed DNSKEY's algorithm identifier finishes on a 00 byte in the
+    # record that follows it in the same message.  That following record, the
+    # well-formed DNSKEY, starts with a compression pointer followed by the
+    # type, which starts with 00.
+    OVERRUN_DNSKEY = "\\# 12 00 00 00 fd 09 00 00 00 00 00 00 00"
+    WELL_FORMED_DNSKEY = "\\# 12 00 00 00 fd 06 00 00 00 00 00 00 00"

     @property
     def zone_contents(self) -> Collection[dns.rrset.RRset]:
         return [
             ns(self.zone),
             txt(self.zone),
+            dnskey(self.zone, self.OVERRUN_DNSKEY),
+            dnskey(self.zone, self.WELL_FORMED_DNSKEY),
         ]


-class RetryAxfrHandler(ZoneAxfrHandler):
-    zone = "retry-too-big."
+class ReconfigAxfrHandler(ZoneAxfrHandler):
+    zone = "xfr-and-reconfig."

     @property
     def zone_contents(self) -> Collection[dns.rrset.RRset]:
@@ -125,27 +138,14 @@ class RetryAxfrHandler(ZoneAxfrHandler):
         ]


-class OverrunAxfrHandler(ZoneAxfrHandler):
-    """
-    Serve the malformed PRIVATEDNS DNSKEY overrun; see OVERRUN_DNSKEY.
-    """
-
-    zone = "private-dns-overrun."
-
-    # The malformed DNSKEY's algorithm identifier finishes on a 00 byte in the
-    # record that follows it in the same message.  That following record, the
-    # well-formed DNSKEY, starts with a compression pointer followed by the
-    # type, which starts with 00.
-    OVERRUN_DNSKEY = "\\# 12 00 00 00 fd 09 00 00 00 00 00 00 00"
-    WELL_FORMED_DNSKEY = "\\# 12 00 00 00 fd 06 00 00 00 00 00 00 00"
+class RetryAxfrHandler(ZoneAxfrHandler):
+    zone = "retry-too-big."

     @property
     def zone_contents(self) -> Collection[dns.rrset.RRset]:
         return [
             ns(self.zone),
             txt(self.zone),
-            dnskey(self.zone, self.OVERRUN_DNSKEY),
-            dnskey(self.zone, self.WELL_FORMED_DNSKEY),
         ]