You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iggy.apache.org by gk...@apache.org on 2026/10/13 19:04:39 UTC

(iggy) branch mtls_kafka_proxy created (now 2b987dc65)

This is an automated email from the ASF dual-hosted git repository.

numinnex pushed a change to branch mtls_kafka_proxy
in repository https://gitbox.apache.org/repos/asf/iggy.git


      at 2b987dc65 feat(gateways): add TLS listeners and mTLS client identities to Kafka gateway

This branch includes the following new commits:

     new 4b64f7bc7 temp
     new 2b987dc65 feat(gateways): add TLS listeners and mTLS client identities to Kafka gateway

The 2 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.



(iggy) 01/02: temp

Posted by gk...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

numinnex pushed a commit to branch mtls_kafka_proxy
in repository https://gitbox.apache.org/repos/asf/iggy.git

commit 4b64f7bc7c585ce475721aff24ff6f13d089c687
Author: Grzegorz Koszyk <g....@gmail.com>
AuthorDate: Tue Oct 13 19:23:18 2026 +0200

    temp
---
 Cargo.lock                                         |   6 +
 Cargo.toml                                         |   1 +
 gateways/kafka/Cargo.toml                          |   7 +
 gateways/kafka/Dockerfile                          |   2 +-
 gateways/kafka/README.md                           |  93 ++-
 gateways/kafka/docker-compose.yml                  |   2 +-
 gateways/kafka/docs/AUTHENTICATION.md              |  97 ++-
 gateways/kafka/docs/MANUAL_TESTING.md              | 129 +++
 gateways/kafka/docs/SCOPE.md                       |  17 +-
 gateways/kafka/docs/TEST_SUITE.md                  |  12 +-
 gateways/kafka/src/auth.rs                         | 116 ++-
 gateways/kafka/src/bridge/config.rs                |  75 ++
 .../kafka/src/bridge/iggy_bridge/group_offsets.rs  |   3 +-
 gateways/kafka/src/bridge/iggy_bridge/mod.rs       |  27 +-
 gateways/kafka/src/bridge/mod.rs                   |   2 +-
 gateways/kafka/src/lib.rs                          |   2 +
 gateways/kafka/src/listener.rs                     | 439 +++++++++++
 gateways/kafka/src/main.rs                         | 526 +++++++++++--
 gateways/kafka/src/protocol/api.rs                 |  90 ++-
 .../kafka/src/protocol/handlers/api_versions.rs    |  65 +-
 .../src/protocol/handlers/find_coordinator.rs      |  15 +-
 gateways/kafka/src/protocol/handlers/metadata.rs   |  19 +-
 gateways/kafka/src/protocol/handlers/mod.rs        |   8 +-
 .../kafka/src/protocol/handlers/offset_commit.rs   |   6 +-
 .../kafka/src/protocol/handlers/offset_fetch.rs    |   5 +-
 gateways/kafka/src/server.rs                       | 866 +++++++++++++++------
 gateways/kafka/src/tls/identity.rs                 | 528 +++++++++++++
 gateways/kafka/src/tls/mod.rs                      | 505 ++++++++++++
 .../kafka/tests/bridge_iggy_integration_tests.rs   |  36 +-
 gateways/kafka/tests/broker_advertise_tests.rs     |  55 +-
 gateways/kafka/tests/common/certs.rs               | 178 +++++
 gateways/kafka/tests/common/iggy_server.rs         |  34 +-
 gateways/kafka/tests/common/server.rs              |  66 +-
 gateways/kafka/tests/common/tcp.rs                 |  15 +-
 gateways/kafka/tests/configs_handler_tests.rs      |   2 -
 gateways/kafka/tests/configs_java_client_tests.rs  |  15 +-
 gateways/kafka/tests/configs_real_bridge_tests.rs  |   6 +-
 gateways/kafka/tests/consumer_group_tests.rs       |   2 -
 .../kafka/tests/create_topics_real_bridge_tests.rs |   8 +-
 .../kafka/tests/delete_topics_real_bridge_tests.rs |   6 +-
 gateways/kafka/tests/fetch_real_bridge_tests.rs    |   6 +-
 gateways/kafka/tests/idempotence_tests.rs          |   5 -
 gateways/kafka/tests/kafka_client_e2e_tests.rs     | 367 ++++++++-
 .../kafka/tests/list_offsets_real_bridge_tests.rs  |   4 +-
 gateways/kafka/tests/metadata_real_bridge_tests.rs |  20 +-
 gateways/kafka/tests/offsets_real_bridge_tests.rs  |   6 +-
 gateways/kafka/tests/produce_real_bridge_tests.rs  |   8 +-
 gateways/kafka/tests/sasl_tests.rs                 |  17 +-
 gateways/kafka/tests/tls_listener_tests.rs         | 677 ++++++++++++++++
 49 files changed, 4601 insertions(+), 595 deletions(-)

diff --git a/Cargo.lock b/Cargo.lock
index c304f2066..cf4b6d4e7 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -7111,6 +7111,7 @@ name = "iggy-gateway-kafka"
 version = "0.1.0"
 dependencies = [
  "anyhow",
+ "arc-swap",
  "async-trait",
  "bytes",
  "crc32c",
@@ -7120,6 +7121,9 @@ dependencies = [
  "kafka-protocol",
  "libc",
  "lz4",
+ "rcgen",
+ "regex",
+ "rustls",
  "secrecy",
  "serde",
  "serde_json",
@@ -7129,12 +7133,14 @@ dependencies = [
  "tempfile",
  "thiserror 2.0.20",
  "tokio",
+ "tokio-rustls",
  "tokio-util",
  "toml 1.1.6+spec-1.1.0",
  "tracing",
  "tracing-appender",
  "tracing-subscriber",
  "uuid",
+ "x509-parser 0.18.1",
  "zstd 0.13.3",
 ]
 
diff --git a/Cargo.toml b/Cargo.toml
index 752018bc0..34b32f0d3 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -391,6 +391,7 @@ web-sys = { version = "0.3", features = [
 webpki-roots = "1.0.9"
 windows-native-keyring-store = "1.1.0"
 wiremock = "0.6"
+x509-parser = "0.18.1"
 yew = { version = "0.23", features = ["csr"] }
 yew-router = "0.20"
 zbus-secret-service-keyring-store = { version = "1.0.1", features = ["rt-async-io-crypto-rust"] }
diff --git a/gateways/kafka/Cargo.toml b/gateways/kafka/Cargo.toml
index 17161adeb..0451b073b 100644
--- a/gateways/kafka/Cargo.toml
+++ b/gateways/kafka/Cargo.toml
@@ -35,6 +35,7 @@ path = "src/main.rs"
 [dependencies]
 # Required by kafka-protocol: its custom-decompression hook is typed on anyhow::Result.
 anyhow = { workspace = true }
+arc-swap = { workspace = true }
 async-trait = { workspace = true }
 bytes = { workspace = true }
 # The four codecs are driven from `records::decompress` rather than through kafka-protocol,
@@ -46,6 +47,8 @@ iggy = { workspace = true }
 kafka-protocol = { workspace = true, features = ["gzip", "lz4", "snappy", "zstd"] }
 libc = { workspace = true }
 lz4 = { workspace = true }
+regex = { workspace = true }
+rustls = { workspace = true }
 secrecy = { workspace = true }
 serde = { workspace = true }
 snap = { workspace = true }
@@ -60,12 +63,14 @@ tokio = { workspace = true, features = [
     "sync",
     "signal",
 ] }
+tokio-rustls = { workspace = true }
 tokio-util = { workspace = true, features = ["rt"] }
 toml = { workspace = true }
 tracing = { workspace = true }
 tracing-appender = { workspace = true }
 tracing-subscriber = { workspace = true }
 uuid = { workspace = true }
+x509-parser = { workspace = true }
 zstd = { workspace = true }
 
 [dev-dependencies]
@@ -73,6 +78,8 @@ zstd = { workspace = true }
 crc32c = { workspace = true }
 # The client half, so a test encodes requests and decodes responses the way a consumer does.
 kafka-protocol = { workspace = true, features = ["client"] }
+# Certificates for the TLS listener tests, minted per test so nothing in the tree expires.
+rcgen = { workspace = true }
 # Reads the JSON events that kafka-verifiable-consumer.sh prints.
 serde_json = { workspace = true }
 serial_test = { workspace = true }
diff --git a/gateways/kafka/Dockerfile b/gateways/kafka/Dockerfile
index 63fa36aed..473707fe1 100644
--- a/gateways/kafka/Dockerfile
+++ b/gateways/kafka/Dockerfile
@@ -56,7 +56,7 @@ COPY --from=builder /iggy-gateway-kafka .
 
 ENV IGGY_KAFKA_BIND_ADDR=0.0.0.0:9093
 # No baked IGGY_KAFKA_ADVERTISED_HOST default: wildcard bind means the gateway cannot derive
-# its own advertised host (server.rs's BrokerAdvertise::from_server_config refuses to start
+# its own advertised host (listener.rs's BrokerAdvertise::for_listener refuses to start
 # without one), and that refusal is deliberate - it forces whoever runs this image to say what
 # host a client can actually reach it on, rather than silently advertising "localhost" to a
 # client on a different machine. docker-compose.yml sets it explicitly for this quick start.
diff --git a/gateways/kafka/README.md b/gateways/kafka/README.md
index 3b88850b7..f7d05e126 100644
--- a/gateways/kafka/README.md
+++ b/gateways/kafka/README.md
@@ -41,13 +41,21 @@ Foundation layer for [apache/iggy#3421](https://github.com/apache/iggy/issues/34
 cargo run -p iggy-gateway-kafka
 ```
 
-Default bind: `127.0.0.1:9093`. Environment variables:
+Default bind: a `PLAINTEXT` listener on `127.0.0.1:9093`. Environment variables:
 
 | Variable | Default | Description |
 | --- | --- | --- |
-| `IGGY_KAFKA_BIND_ADDR` | `127.0.0.1:9093` | TCP address to listen on |
-| `IGGY_KAFKA_ADVERTISED_HOST` | bind IP | Hostname/IP clients use to reach this broker (required when binding to `0.0.0.0`/`::`) |
-| `IGGY_KAFKA_ADVERTISED_PORT` | bind port | Port advertised in Metadata responses |
+| `IGGY_KAFKA_LISTENERS` | unset | Kafka-style listener list, `PROTOCOL://ip:port` entries separated by commas, one per security protocol: `PLAINTEXT`, `SSL`, `SASL_PLAINTEXT`, `SASL_SSL`. Takes precedence over the three single-listener address variables below (the image bakes `IGGY_KAFKA_BIND_ADDR` in, so they are ignored with a warning) and is refused beside `IGGY_KAFKA_SASL_ENABLED`, since the listener protocols say where SASL runs. See [Listeners and TLS](#listeners-and-tls-4510) |
+| `IGGY_KAFKA_ADVERTISED_LISTENERS` | bind address of each listener | `PROTOCOL://host:port` per listener, the address clients are pointed back at. Required for any listener bound to `0.0.0.0`/`::` |
+| `IGGY_KAFKA_BIND_ADDR` | `127.0.0.1:9093` | Single-listener form: TCP address to listen on |
+| `IGGY_KAFKA_ADVERTISED_HOST` | bind IP | Single-listener form: hostname/IP clients use to reach this broker (required when binding to `0.0.0.0`/`::`) |
+| `IGGY_KAFKA_ADVERTISED_PORT` | bind port | Single-listener form: port advertised in Metadata responses |
+| `IGGY_KAFKA_TLS_CERT_FILE` | unset | PEM certificate chain for every `SSL` and `SASL_SSL` listener, leaf first. Required when one exists, refused when none does |
+| `IGGY_KAFKA_TLS_KEY_FILE` | unset | PEM private key for the certificate (PKCS#8, PKCS#1 or SEC1) |
+| `IGGY_KAFKA_TLS_CLIENT_AUTH` | `none` | Kafka's `ssl.client.auth`: `none`, `requested` or `required`. On an `SSL` listener a verified client certificate names the Iggy user; on `SASL_SSL` it only gates the transport |
+| `IGGY_KAFKA_TLS_CLIENT_CA_FILE` | unset | PEM roots client certificates must chain to. Required with `requested` or `required`, refused with `none` |
+| `IGGY_KAFKA_TLS_PRINCIPAL_MAPPING_RULES` | `DEFAULT` | Kafka's `ssl.principal.mapping.rules`, turning a client certificate's subject into an Iggy username. Only with client authentication on an `SSL` listener |
+| `IGGY_KAFKA_TLS_RELOAD_INTERVAL_SECS` | `60` | How often the certificate, key and client CA files are re-read; a change goes live for new connections without a restart. `0` never re-reads them |
 | `IGGY_KAFKA_MAX_CONNECTIONS` | `1024` | Maximum concurrent connections before new ones are rejected |
 | `IGGY_KAFKA_MAX_FRAME_SIZE` | `8388608` | Maximum accepted request frame size in bytes |
 | `IGGY_KAFKA_IDLE_TIMEOUT_SECS` | `600` | Seconds a connection may sit idle before the next frame's length prefix arrives |
@@ -56,7 +64,7 @@ Default bind: `127.0.0.1:9093`. Environment variables:
 | `IGGY_KAFKA_SHUTDOWN_DRAIN_TIMEOUT_SECS` | `25` | Seconds graceful shutdown waits for in-flight connections before abandoning them |
 | `IGGY_KAFKA_INSTANCE_ID` | `0` | This gateway's number among the gateways fronting one Iggy cluster. It is the high half of every producer id `InitProducerId` hands out, and Kafka requires those to be cluster-unique, so give every gateway its own value. A single gateway can leave it at `0`. |
 | `IGGY_KAFKA_BRIDGE_ENABLED` | `false` | Connect the Iggy bridge at startup. While false every API answers with its stub, and the `IGGY_KAFKA_IGGY_*` variables below are read by nothing. A failed connection is fatal, not a downgrade to stubs. |
-| `IGGY_KAFKA_SASL_ENABLED` | `false` | Require SASL/PLAIN authentication before serving any other API (`true` or `false`, nothing else) |
+| `IGGY_KAFKA_SASL_ENABLED` | `false` | Single-listener form: require SASL/PLAIN before serving any other API (`true` or `false`, nothing else). With `IGGY_KAFKA_LISTENERS`, a `SASL_PLAINTEXT` or `SASL_SSL` listener says the same |
 | `IGGY_KAFKA_PRE_AUTH_TIMEOUT_SECS` | `15` | Seconds an unauthenticated connection may sit between frames. Waiting for an authentication slot and the verification itself each get this budget, the verification's starting once it holds a slot. Separate from the 10-minute idle timeout that applies once authenticated |
 | `IGGY_KAFKA_MAX_CONCURRENT_AUTHENTICATIONS` | `4` | Credential verifications the gateway runs at once, across all connections. Each costs a password hash on an Iggy shard thread. This bounds the gateway's side only: a check that times out frees its slot while its hash keeps running inside Iggy. Size it below the Iggy node's shard count |
 
@@ -240,10 +248,65 @@ Limits:
   in Iggy ([docs/OFFSET_STORAGE.md](docs/OFFSET_STORAGE.md#limits)).
 - Delivery is at-least-once. A consumer that stops before it commits reads those records again.
 
+## Listeners and TLS ([#4510](https://github.com/apache/iggy/issues/4510))
+
+The gateway binds one listener per Kafka security protocol, named the way Kafka's own `listeners`
+and `advertised.listeners` are. A client is pointed back, in Metadata and FindCoordinator, at the
+listener it connected through and no other, so a client on the TLS port never learns the plaintext
+one.
+
+```bash
+IGGY_KAFKA_LISTENERS=PLAINTEXT://127.0.0.1:9093,SSL://0.0.0.0:9094,SASL_SSL://0.0.0.0:9095 \
+  IGGY_KAFKA_ADVERTISED_LISTENERS=SSL://kafka.example.com:9094,SASL_SSL://kafka.example.com:9095 \
+  IGGY_KAFKA_TLS_CERT_FILE=/etc/iggy/kafka.pem IGGY_KAFKA_TLS_KEY_FILE=/etc/iggy/kafka.key \
+  cargo run -p iggy-gateway-kafka
+```
+
+TLS is rustls. One certificate serves every `SSL` and `SASL_SSL` listener, and the files are
+re-read every `IGGY_KAFKA_TLS_RELOAD_INTERVAL_SECS`: a rotated certificate takes effect for new
+connections without a restart, a half-written rotation or a key that does not match leaves the
+previous material serving and logs an error. There is no self-signed mode; mint a certificate
+(`docs/MANUAL_TESTING.md` has an `openssl` recipe) and give the Kafka client the CA.
+
+```bash
+kcat -b kafka.example.com:9094 -X security.protocol=SSL -X ssl.ca.location=ca.pem -L
+kcat -b kafka.example.com:9095 -X security.protocol=SASL_SSL -X ssl.ca.location=ca.pem \
+     -X sasl.mechanisms=PLAIN -X sasl.username=alice -X sasl.password=s3cret -L
+```
+
+### Client certificates (mTLS)
+
+`IGGY_KAFKA_TLS_CLIENT_AUTH=required` (or `requested`) makes every TLS listener verify client
+certificates against `IGGY_KAFKA_TLS_CLIENT_CA_FILE`. What a verified certificate means depends on
+the listener, as it does on a Kafka broker:
+
+- On an `SSL` listener the certificate names the principal. Its subject, rendered the way Java
+  does (`CN=alice,OU=eng,O=Example`), goes through `IGGY_KAFKA_TLS_PRINCIPAL_MAPPING_RULES`, and
+  the result must be the name of an active Iggy user. The gateway looks the user up through the
+  bridge's own session, so the bridge is required and its Iggy user needs `read_users`. A
+  certificate naming no such user is closed after the handshake, with the name in the gateway's
+  log at `warn`. With `requested`, a client that presents no certificate is Kafka's `ANONYMOUS`
+  principal and is served as the bridge's user, exactly as on a plaintext listener.
+- On a `SASL_SSL` listener the certificate only gates the transport. SASL names the principal and
+  the subject is never mapped.
+
+The rules are Kafka's syntax, tried in order: `RULE:pattern/replacement/[LU]` applies when the
+pattern matches the whole subject, `DEFAULT` keeps the subject as is. A raw subject is not a valid
+Iggy username, so a deployment that maps identities sets at least one rule:
+
+```bash
+IGGY_KAFKA_TLS_PRINCIPAL_MAPPING_RULES='RULE:^CN=([^,]+),OU=services.*$/svc-$1/L,RULE:^CN=([^,]+).*$/$1/'
+```
+
+Acting as the mapped user on the data plane is
+[#4518](https://github.com/apache/iggy/issues/4518); today the identity gates admission and
+answers `DescribeAcls`, as a SASL identity does.
+
 ## Authentication ([#3549](https://github.com/apache/iggy/issues/3549))
 
-Off by default. With `IGGY_KAFKA_SASL_ENABLED=true` the gateway requires SASL/PLAIN before it serves
-any other API, and it verifies the credentials by logging into Iggy with them.
+Off by default. With a `SASL_PLAINTEXT` or `SASL_SSL` listener (or `IGGY_KAFKA_SASL_ENABLED=true`
+in the single-listener form) the gateway requires SASL/PLAIN before it serves any other API on
+that listener, and it verifies the credentials by logging into Iggy with them.
 
 The username and password a Kafka client sends are an **Iggy** username and password. There is no
 mapping table and no credential store in the gateway: create an Iggy user for each Kafka principal
@@ -254,13 +317,12 @@ IGGY_KAFKA_SASL_ENABLED=true IGGY_KAFKA_IGGY_ADDR=127.0.0.1:8090 cargo run -p ig
 ```
 
 Transport security to Iggy is configured separately from the Kafka side, because the two protect
-different hops. These variables cover only the connection the credential check makes, and are
-refused while SASL is off. The bridge's own client connects without TLS at any setting, and that
-connection carries `IGGY_KAFKA_IGGY_PASSWORD` in the clear:
+different hops. These variables cover every connection the gateway makes to Iggy, the credential
+check's and the bridge's alike, and are refused while neither SASL nor the bridge is on:
 
 | Variable | Default | Description |
 | --- | --- | --- |
-| `IGGY_KAFKA_IGGY_TLS_ENABLED` | `false` | Encrypt the credential check's connection to Iggy (`true` or `false`, nothing else). The bridge connection is not covered. Required if the Iggy server only accepts TLS, otherwise every verification fails as unreachable |
+| `IGGY_KAFKA_IGGY_TLS_ENABLED` | `false` | Encrypt the gateway's connections to Iggy (`true` or `false`, nothing else). Required if the Iggy server only accepts TLS, otherwise the bridge fails to connect and every verification fails as unreachable |
 | `IGGY_KAFKA_IGGY_TLS_DOMAIN` | derived from the address | Name checked against the Iggy server certificate |
 | `IGGY_KAFKA_IGGY_TLS_CA_FILE` | SDK bundled roots | PEM roots to trust. Note the SDK does not use the system trust store |
 
@@ -273,10 +335,11 @@ kcat -b 127.0.0.1:9093 -X security.protocol=SASL_PLAINTEXT -X sasl.mechanisms=PL
 
 Four things to know before switching it on:
 
-- **PLAIN sends the password in the clear**, on the Kafka hop and on the Iggy hop. The gateway
-  listener has no TLS yet, so this is only safe on a trusted network until that lands. SCRAM cannot
-  be offered at all, because Iggy stores one Argon2 hash per user and SCRAM needs PBKDF2-derived
-  keys that cannot come from it.
+- **PLAIN sends the password in the clear** unless the hop is encrypted: a `SASL_SSL` listener on
+  the Kafka side, `IGGY_KAFKA_IGGY_TLS_ENABLED=true` on the Iggy side. A `SASL_PLAINTEXT` listener
+  is only safe on a trusted network, and the gateway says so at startup. SCRAM cannot be offered at
+  all, because Iggy stores one Argon2 hash per user and SCRAM needs PBKDF2-derived keys that cannot
+  come from it.
 - **Enabling it breaks every existing client at once.** The two SASL keys appear in the
   `ApiVersions` advertisement only while it is on, and unauthenticated clients are refused.
 - **Every connection costs a login**, meaning one password hash on an Iggy shard thread and one
diff --git a/gateways/kafka/docker-compose.yml b/gateways/kafka/docker-compose.yml
index af1c11a03..fff7bcb65 100644
--- a/gateways/kafka/docker-compose.yml
+++ b/gateways/kafka/docker-compose.yml
@@ -104,7 +104,7 @@ services:
     environment:
       - IGGY_KAFKA_BIND_ADDR=0.0.0.0:9093
       # Binding the wildcard address above means the gateway cannot derive its own advertised
-      # host (server.rs::BrokerAdvertise::from_server_config refuses to start without this) -
+      # host (listener.rs::BrokerAdvertise::for_listener refuses to start without this) -
       # same requirement root docker-compose.yml's IGGY_NODE_ADVERTISED_ADDRESS already carries
       # for iggy-server, for the same reason: the value a Kafka client's Metadata response
       # points it back at has to be reachable from outside the container.
diff --git a/gateways/kafka/docs/AUTHENTICATION.md b/gateways/kafka/docs/AUTHENTICATION.md
index 67b27e29c..643642ba0 100644
--- a/gateways/kafka/docs/AUTHENTICATION.md
+++ b/gateways/kafka/docs/AUTHENTICATION.md
@@ -1,13 +1,15 @@
 # Kafka authentication and Iggy identity
 
-Status: implemented. Answers [#3549](https://github.com/apache/iggy/issues/3549). The gateway listener
-still has no TLS, so PLAIN stays confined to a trusted network until that lands (see
-[Transport security](#transport-security)). The mechanism choice below is forced by how Iggy stores
-credentials, not preferred.
+Status: implemented. Answers [#3549](https://github.com/apache/iggy/issues/3549), and
+[#4510](https://github.com/apache/iggy/issues/4510) for the transport: a `SASL_SSL` listener
+encrypts the Kafka hop and `IGGY_KAFKA_IGGY_TLS_ENABLED` the Iggy hop, so PLAIN leaves the trusted
+network only inside TLS (see [Transport security](#transport-security)). A client certificate on an
+`SSL` listener names a principal too (see [Client certificates](#client-certificates)). The
+mechanism choice below is forced by how Iggy stores credentials, not preferred.
 
 ## Decision
 
-Four parts.
+Five parts.
 
 **Mechanism: SASL/PLAIN only.** SCRAM cannot be implemented against Iggy's credential store at all, and
 nothing else in Kafka's mechanism set maps without new server-side storage.
@@ -26,6 +28,12 @@ to carry the authenticated Iggy identity onto the data plane and let the server'
 decide what it can do. That is later work: today the verified client is shut down as soon as the credential
 clears, and nothing carries the principal past authentication.
 
+**A client certificate is an identity too, with the same reach.** On an `SSL` listener that verifies client
+certificates, the subject maps to an Iggy username through Kafka's `ssl.principal.mapping.rules` and the
+gateway confirms the user exists. Nothing is logged into on the client's behalf, since Iggy's own transports
+take no certificate ([#3930](https://github.com/apache/iggy/issues/3930)); the principal gates admission and
+answers `DescribeAcls`, exactly as a SASL one does, and acting as it on the data plane is the same later work.
+
 ## Why SCRAM is out
 
 Iggy stores exactly one credential per user, an Argon2id PHC string (`core/metadata/src/stm/user.rs:57`,
@@ -195,24 +203,63 @@ rather than leaving an operator to discover it.
 
 ## Transport security
 
-SASL/PLAIN puts the password in the clear on the wire, and so does Iggy's own login. Both hops need TLS.
-
-The gateway listener has no TLS at all today, which makes a TLS listener a prerequisite rather than a
-follow-up. The Iggy side already supports it on both ends (client at
-`core/common/src/types/configuration/tcp_config/tcp_client_config.rs:30`, server at
-`core/configs/src/server_config/tcp.rs:31`), shipped disabled.
-
-The two hops are configured independently. `IGGY_KAFKA_IGGY_TLS_ENABLED` and its companions encrypt
-only the connection the credential check makes to Iggy, and are what make SASL usable at all against a
-TLS-only Iggy server, where every verification would otherwise fail as unreachable. The bridge's own
-client has no TLS at any setting, so the bridge hop stays unencrypted and carries
-`IGGY_KAFKA_IGGY_PASSWORD` in the clear. The Kafka-side listener is the other half still missing.
-
-Two limits worth recording. There is no mTLS anywhere in the tree, every rustls config uses
-`with_no_client_auth()`, so certificate-based Kafka client authentication cannot map to an Iggy identity
-without an external terminator. And an Iggy password is capped at 100 bytes with a `u8` length prefix on
-the wire (`core/common/src/http/users/defaults.rs:20`), so a Kafka client with a longer PLAIN secret is
-rejected.
+SASL/PLAIN puts the password in the clear on the wire, and so does Iggy's own login. Both hops need TLS,
+and the two are configured independently because they protect different hops.
+
+**The Kafka hop** is a listener's security protocol. The gateway binds one listener per protocol, the way
+Kafka's `listeners` does (`IGGY_KAFKA_LISTENERS`), and `SASL_SSL` is the one for PLAIN outside a trusted
+network. TLS is rustls, one certificate for every `SSL` and `SASL_SSL` listener
+(`IGGY_KAFKA_TLS_CERT_FILE`, `IGGY_KAFKA_TLS_KEY_FILE`), re-read on an interval so a rotation goes live
+without a restart. Each listener advertises its own address, so a client on the TLS port is never
+pointed at the plaintext one. A `SASL_PLAINTEXT` listener still exists for trusted networks, and the
+gateway warns at startup that it carries the password in the clear.
+
+**The Iggy hop** is `IGGY_KAFKA_IGGY_TLS_ENABLED` and its companions. They cover every connection the
+gateway makes to Iggy: the credential check's and the bridge's, which carries `IGGY_KAFKA_IGGY_PASSWORD`.
+They are what make SASL usable against a TLS-only Iggy server at all, where every verification would
+otherwise fail as unreachable, and are refused while nothing dials Iggy.
+
+Two limits worth recording. Iggy's own transports take no client certificate
+([#3930](https://github.com/apache/iggy/issues/3930)), so a certificate identity on the Kafka side is
+verified by the gateway and looked up through the bridge's session rather than presented to Iggy. And an
+Iggy password is capped at 100 bytes with a `u8` length prefix on the wire
+(`core/common/src/http/users/defaults.rs:20`), so a Kafka client with a longer PLAIN secret is rejected.
+
+## Client certificates
+
+`IGGY_KAFKA_TLS_CLIENT_AUTH` is Kafka's `ssl.client.auth`: `none`, `requested` or `required`. With it on,
+every TLS listener verifies the client certificate against `IGGY_KAFKA_TLS_CLIENT_CA_FILE` during the
+handshake, and what a verified certificate means follows the listener, as it does on a Kafka broker.
+
+On a `SASL_SSL` listener the certificate gates the transport only. SASL names the principal, and the
+subject is never mapped: Kafka does the same, and a deployment that wants certificate identities uses
+`SSL`.
+
+On an `SSL` listener the certificate names the principal, in three steps the connection takes before its
+first frame:
+
+1. **Render the subject** the way Java's `X500Principal.getName()` does, RFC 2253 with the most specific
+   RDN first and no spaces: `CN=alice,OU=eng,O=Example`. Operators write mapping rules against Java's
+   rendering, so the gateway matches it, keyword set and escaping included.
+2. **Map it** through `IGGY_KAFKA_TLS_PRINCIPAL_MAPPING_RULES`, Kafka's `ssl.principal.mapping.rules`
+   syntax: `RULE:pattern/replacement/[LU]` applies when the pattern matches the whole subject, `DEFAULT`
+   keeps it, the first match wins, and a subject no rule matches closes the connection. The default is
+   `DEFAULT`, which is not a valid Iggy username, so a deployment sets at least one rule.
+3. **Look the name up** through the bridge's own session. The user must exist and be active, or the
+   connection is closed after the handshake with the name in the log at `warn`: a certificate the CA signed
+   for an account that does not exist is a provisioning mistake, not something the client can correct. The
+   bridge is therefore required for certificate identities, and its Iggy user needs `read_users`. A failed
+   lookup, including one refused for want of that permission, closes the connection too and never admits
+   the name unchecked.
+
+With `requested`, a client that presents no certificate is Kafka's `ANONYMOUS` principal: served as the
+bridge's user, the way a plaintext listener serves everyone, and described by `DescribeAcls` as holding
+nothing. With `required`, rustls fails the handshake instead.
+
+The principal a certificate yields is the same `AuthenticatedPrincipal` a SASL login yields, with its
+permissions read at admission, so everything written about the SASL identity above holds: it is a snapshot,
+it is not cached across connections, and nothing acts as it on the data plane yet
+([#4518](https://github.com/apache/iggy/issues/4518)).
 
 ## Re-authentication
 
@@ -229,7 +276,9 @@ has to resolve it first.
 
 - SCRAM-SHA-256 and SCRAM-SHA-512, blocked on credential storage that does not exist.
 - SASL/OAUTHBEARER and GSSAPI.
-- mTLS and certificate-based identity.
+- Presenting a client certificate to Iggy's own transports, which take none
+  ([#3930](https://github.com/apache/iggy/issues/3930)); the gateway verifies it and looks the user up
+  instead.
 - Authorization. No handler asks Iggy about permissions yet, since the verified identity is not carried
   onto the data plane; SASL is an admission gate only. The `DescribeAcls` and `CreateAcls` API keys also
   stay unimplemented.
diff --git a/gateways/kafka/docs/MANUAL_TESTING.md b/gateways/kafka/docs/MANUAL_TESTING.md
index 36a6602cc..9354ad493 100644
--- a/gateways/kafka/docs/MANUAL_TESTING.md
+++ b/gateways/kafka/docs/MANUAL_TESTING.md
@@ -181,6 +181,135 @@ Latency grows with concurrency while throughput flattens, which is what a server
 shard threads with no blocking pool predicts. No failures at any level. Re-measure before quoting
 these anywhere: a release build will be substantially faster.
 
+### Category U — TLS listeners and client certificates
+
+Needs a running Iggy as in category S. Mint a CA, a server certificate for `127.0.0.1` and two client
+certificates, one for an Iggy user and one for a name no user has:
+
+```bash
+cd /tmp && mkdir -p certs && cd certs
+openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 2 \
+  -subj '/CN=iggy kafka test CA' -keyout ca.key -out ca.pem
+openssl req -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -subj '/CN=gateway' \
+  -addext 'subjectAltName=IP:127.0.0.1,DNS:localhost' -keyout server.key -out server.csr
+openssl x509 -req -in server.csr -CA ca.pem -CAkey ca.key -CAcreateserial -days 2 -copy_extensions copy \
+  -out server.pem
+for name in iggy nobody; do
+  openssl req -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -subj "/O=Example/CN=$name" \
+    -keyout $name.key -out $name.csr
+  openssl x509 -req -in $name.csr -CA ca.pem -CAkey ca.key -CAcreateserial -days 2 -out $name.pem
+done
+```
+
+Then a gateway with every listener, bridged (the bridge looks certificate identities up), with client
+certificates requested and the common name as the Iggy username:
+
+```bash
+IGGY_KAFKA_LISTENERS=PLAINTEXT://127.0.0.1:9093,SSL://127.0.0.1:9094,SASL_SSL://127.0.0.1:9095 \
+  IGGY_KAFKA_TLS_CERT_FILE=/tmp/certs/server.pem IGGY_KAFKA_TLS_KEY_FILE=/tmp/certs/server.key \
+  IGGY_KAFKA_TLS_CLIENT_AUTH=requested IGGY_KAFKA_TLS_CLIENT_CA_FILE=/tmp/certs/ca.pem \
+  IGGY_KAFKA_TLS_PRINCIPAL_MAPPING_RULES='RULE:^CN=([^,]+).*$/$1/' \
+  IGGY_KAFKA_TLS_RELOAD_INTERVAL_SECS=5 \
+  IGGY_KAFKA_BRIDGE_ENABLED=true IGGY_KAFKA_IGGY_ADDR=127.0.0.1:8090 \
+  IGGY_KAFKA_IGGY_USERNAME=iggy IGGY_KAFKA_IGGY_PASSWORD=iggy \
+  RUST_LOG=debug cargo run -p iggy-gateway-kafka
+```
+
+`KC` below is `docker run --rm --network host -v /tmp/certs:/certs:ro edenhill/kcat:1.7.1`, and
+`KAFKA` is `docker run --rm --network host -v /tmp/certs:/certs:ro -v /tmp/client.properties:/tmp/client.properties:ro apache/kafka:3.9.0`.
+
+| ID | Test | Command | Pass criteria | Last run |
+| ---- | ------ | --------- | --------------- | ---------- |
+| U1 | kcat, SSL | `KC -b 127.0.0.1:9094 -X security.protocol=SSL -X ssl.ca.location=/certs/ca.pem -L` | Metadata returned, broker `127.0.0.1:9094` | Pass |
+| U2 | kcat, SASL_SSL | `KC -b 127.0.0.1:9095 -X security.protocol=SASL_SSL -X ssl.ca.location=/certs/ca.pem -X sasl.mechanisms=PLAIN -X sasl.username=iggy -X sasl.password=iggy -L` | Metadata returned, broker `127.0.0.1:9095` | Pass |
+| U3 | kcat, client certificate | U1 plus `-X ssl.certificate.location=/certs/iggy.pem -X ssl.key.location=/certs/iggy.key` | Metadata returned; gateway log says `client certificate authenticated` with `username=iggy` | Pass |
+| U4 | kcat, unknown identity | U3 with `nobody.pem`/`nobody.key` | No metadata, connection closed; gateway log warns `names no active Iggy user` | Pass |
+| U5 | plaintext on the TLS port | `KC -b 127.0.0.1:9094 -L` | No metadata; librdkafka reports the connection closed | Pass |
+| U6 | Java, SSL | `client.properties` with `security.protocol=SSL`, `ssl.truststore.type=PEM`, `ssl.truststore.location=/certs/ca.pem`; `KAFKA /opt/kafka/bin/kafka-broker-api-versions.sh --bootstrap-server 127.0.0.1:9094 --command-config /tmp/client.properties` | Lists the APIs of `127.0.0.1:9094`, with `SaslHandshake(17): UNSUPPORTED` | Pass |
+| U7 | Java, SASL_SSL | U6 with `security.protocol=SASL_SSL` and the S5 `sasl.*` lines, port 9095 | `SaslHandshake(17): 0 to 1 [usable: 1]` | Pass |
+| U8 | Java, client certificate | U6 plus `ssl.keystore.type=PEM`, `ssl.keystore.location=/certs/iggy-bundle.pem` (the key followed by the certificate in one file); `kafka-acls.sh ... --list` | Bindings with `principal=User:iggy` | Pass |
+| U9 | franz-go | see below | Metadata through SSL, SASL_SSL and with a client certificate | Pass |
+| U10 | Reload | Re-mint `server.pem`/`server.key` from a new CSR, wait past the interval, `openssl s_client -connect 127.0.0.1:9094 -CAfile /tmp/certs/ca.pem </dev/null 2>/dev/null \| openssl x509 -noout -serial` | The new serial, without restarting the gateway; log says `TLS certificate reloaded` | Pass |
+
+U1 to U8 and U10 are automated in `tests/kafka_client_e2e_tests.rs` and `tests/tls_listener_tests.rs`.
+U9 is manual, since the suite pulls no Go image. The program, with
+`go mod init probe && go get github.com/twmb/franz-go && go mod tidy` first, dials the broker in
+its first argument, presents the client certificate and key in its second and third when given,
+and authenticates with PLAIN when `SASL_USER` and `SASL_PASS` are set:
+
+```go
+package main
+
+import (
+    "context"
+    "crypto/tls"
+    "crypto/x509"
+    "fmt"
+    "os"
+
+    "github.com/twmb/franz-go/pkg/kgo"
+    "github.com/twmb/franz-go/pkg/kmsg"
+    "github.com/twmb/franz-go/pkg/sasl/plain"
+)
+
+func main() {
+    ca, err := os.ReadFile(os.Getenv("CA_FILE"))
+    if err != nil {
+        panic(err)
+    }
+    pool := x509.NewCertPool()
+    pool.AppendCertsFromPEM(ca)
+    cfg := &tls.Config{RootCAs: pool, ServerName: "localhost"}
+    if len(os.Args) > 3 {
+        cert, err := tls.LoadX509KeyPair(os.Args[2], os.Args[3])
+        if err != nil {
+            panic(err)
+        }
+        cfg.Certificates = []tls.Certificate{cert}
+    }
+    opts := []kgo.Opt{kgo.SeedBrokers(os.Args[1]), kgo.DialTLSConfig(cfg)}
+    if user := os.Getenv("SASL_USER"); user != "" {
+        opts = append(opts, kgo.SASL(plain.Auth{User: user, Pass: os.Getenv("SASL_PASS")}.AsMechanism()))
+    }
+    client, err := kgo.NewClient(opts...)
+    if err != nil {
+        panic(err)
+    }
+    defer client.Close()
+    req := kmsg.NewPtrMetadataRequest()
+    resp, err := req.RequestWith(context.Background(), client)
+    if err != nil {
+        fmt.Println("ERROR:", err)
+        os.Exit(1)
+    }
+    for _, b := range resp.Brokers {
+        fmt.Printf("broker %d at %s:%d\n", b.NodeID, b.Host, b.Port)
+    }
+    acls := kmsg.NewPtrDescribeACLsRequest()
+    acls.ResourceType = 1
+    acls.ResourcePatternType = 1
+    acls.Operation = 1
+    acls.PermissionType = 1
+    aresp, err := acls.RequestWith(context.Background(), client)
+    if err != nil {
+        fmt.Println("describe acls error:", err)
+        return
+    }
+    for _, r := range aresp.Resources {
+        for _, a := range r.ACLs {
+            fmt.Printf("acl %s %s on %s %s\n", a.Principal, a.Operation, r.ResourceType, r.ResourceName)
+        }
+    }
+}
+```
+
+Run it four ways, with `CA_FILE=/tmp/certs/ca.pem` exported: `go run . 127.0.0.1:19094`,
+`SASL_USER=iggy SASL_PASS=iggy go run . 127.0.0.1:19095`,
+`go run . 127.0.0.1:19094 /tmp/certs/iggy.pem /tmp/certs/iggy.key` and the same with
+`nobody.pem`/`nobody.key`. The first three print the one broker on the port they dialed, the SASL
+and certificate runs also list `User:iggy`'s bindings, and the last reports the broker closing the
+connection during `ApiVersions`.
+
 ### Category A — Smoke tests (must pass before check-in)
 
 The gateway binds `:9093` by default; `kafka-message-gen`'s own default is `:9092` (a real Kafka
diff --git a/gateways/kafka/docs/SCOPE.md b/gateways/kafka/docs/SCOPE.md
index 91d2e7e36..b2ccf794a 100644
--- a/gateways/kafka/docs/SCOPE.md
+++ b/gateways/kafka/docs/SCOPE.md
@@ -14,7 +14,7 @@ once you configure a bridge ([#3535](https://github.com/apache/iggy/issues/3535)
 
 | Deliverable | Status | Location |
 | ------------- | -------- | ---------- |
-| TCP listener on `127.0.0.1:9093` (configurable) | Done | `src/server.rs`, `src/main.rs` |
+| TCP listener on `127.0.0.1:9093` (configurable), one listener per security protocol with TLS on the `SSL` ones | Done | `src/server.rs`, `src/listener.rs`, `src/tls/`, `src/main.rs` |
 | Length-prefixed frame read/write with `max_frame_size` cap | Done | `src/server.rs` |
 | Request header v1/v2 auto-detection | Done | `src/protocol/header.rs` (delegates to `kafka_protocol::messages::ApiKey`) |
 | Version negotiation firewall (`SUPPORTED_RANGES`) | Done | `src/protocol/api.rs` |
@@ -50,7 +50,7 @@ it knows the server supports flexible encoding.
 | API key | Name | Min version | Max version | Valid versions | Behavior |
 | --------- | ------ | ------------- | ------------- | ---------------- | ---------- |
 | 18 | ApiVersions | 0 | 3 | 0, 1, 2, 3 | Advertise supported ranges; flexible encoding at v3+ |
-| 3 | Metadata | 0 | 9 | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 | Decode topic list count; stub broker host from `advertised_host` or the bound `local_addr` IP; flexible encoding at v9+ |
+| 3 | Metadata | 0 | 9 | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 | Decode topic list count; stub broker host from the listener's advertised address or its bound IP; flexible encoding at v9+ |
 | 0 | Produce | 3 | 9 | 3, 4, 5, 6, 7, 8, 9 | With a bridge: one `send_messages` per partition. Without one: stub returns `NOT_LEADER_OR_FOLLOWER` (6) |
 | 1 | Fetch | 4 | 12 | 4, 5, 6, 7, 8, 9, 10, 11, 12 | With a bridge: shared topic probes, paged `poll_messages` per partition with records, wait up to `max_wait_ms` (max 18 s). Without one: stub returns `NOT_LEADER_OR_FOLLOWER` (6) |
 | 2 | ListOffsets | 1 | 6 | 1, 2, 3, 4, 5, 6 | Decode request; stub response |
@@ -107,9 +107,9 @@ All API keys not listed above close the connection (see Governance model above)
 
 | API key | Name | Notes |
 | --------- | ------ | ------- |
-| 17 | SaslHandshake | Implemented behind `IGGY_KAFKA_SASL_ENABLED`, advertised only while it is on ([`AUTHENTICATION.md`](AUTHENTICATION.md)) |
-| 29 | DescribeAcls | Implemented behind `IGGY_KAFKA_SASL_ENABLED`, advertised only while it is on ([`ACL_MAPPING.md`](ACL_MAPPING.md)) |
-| 36 | SaslAuthenticate | Implemented behind `IGGY_KAFKA_SASL_ENABLED`, advertised only while it is on ([`AUTHENTICATION.md`](AUTHENTICATION.md)) |
+| 17 | SaslHandshake | Implemented on `SASL_PLAINTEXT` and `SASL_SSL` listeners, advertised only there ([`AUTHENTICATION.md`](AUTHENTICATION.md)) |
+| 29 | DescribeAcls | Implemented on listeners that name a principal: the SASL ones, and `SSL` with client certificates; advertised only there ([`ACL_MAPPING.md`](ACL_MAPPING.md)) |
+| 36 | SaslAuthenticate | Implemented on `SASL_PLAINTEXT` and `SASL_SSL` listeners, advertised only there ([`AUTHENTICATION.md`](AUTHENTICATION.md)) |
 | 24, 25, 26, 28 | AddPartitionsToTxn, AddOffsetsToTxn, EndTxn, TxnOffsetCommit | Transactions - not supported, see below |
 | 23, 27, 30, 31, 34, 35, 37+ | `OffsetForLeaderEpoch`, `WriteTxnMarkers`, `CreateAcls`/`DeleteAcls`, IncrementalAlterConfigs (44), etc. | Later issues |
 | 21 | DeleteRecords | Not advertised on purpose, see below |
@@ -423,7 +423,12 @@ Authentication design ([#3549](https://github.com/apache/iggy/issues/3549)):
 - [x] `DescribeAcls` (29), rendering the authenticated principal's Iggy permissions as Kafka ACL
       bindings ([`ACL_MAPPING.md`](ACL_MAPPING.md)). Read only: `CreateAcls` (30) and `DeleteAcls`
       (31) are not implemented and not advertised
-- [ ] TLS on the gateway listener, a prerequisite for using PLAIN outside a trusted network
+- [x] TLS on the gateway listener ([#4510](https://github.com/apache/iggy/issues/4510)):
+      Kafka-style listeners, one per security protocol, each advertising its own address;
+      rustls with certificate reload; client certificates mapped to Iggy users through
+      `ssl.principal.mapping.rules` on an `SSL` listener; TLS on the bridge's own hop to Iggy.
+      Acting as the mapped user on the data plane is
+      [#4518](https://github.com/apache/iggy/issues/4518)
 - [ ] Tune `max_frame_size` per workload (Kafka defaults: ~1 MiB produce, ~50 MiB fetch; current default 8 MiB)
 - [ ] Target **~15–20 API keys** total for a functional bridge — not all 74+ admin keys
 
diff --git a/gateways/kafka/docs/TEST_SUITE.md b/gateways/kafka/docs/TEST_SUITE.md
index 0a62468fd..ff2508361 100644
--- a/gateways/kafka/docs/TEST_SUITE.md
+++ b/gateways/kafka/docs/TEST_SUITE.md
@@ -72,22 +72,24 @@ file under `tests/` anymore.
 | [`fixtures_canary_tests.rs`](../tests/fixtures_canary_tests.rs) | Fails loudly if `KAFKA_FIXTURES_REQUIRED=1` and no `.bin` fixtures exist, so a broken generation step can't leave the fixture-backed suites green-but-empty | Canary only |
 | [`version_firewall_tests.rs`](../tests/version_firewall_tests.rs) | Version boundary matrix, unsupported keys, corrupt bodies | Partial |
 | [`idempotence_tests.rs`](../tests/idempotence_tests.rs) | `InitProducerId` allocation across every supported version, and the transactional refusals on `InitProducerId`/Produce | No |
-| [`broker_advertise_tests.rs`](../tests/broker_advertise_tests.rs) | `BrokerAdvertise::from_server_config` parsing | No |
+| [`broker_advertise_tests.rs`](../tests/broker_advertise_tests.rs) | `BrokerAdvertise::for_listener` parsing and Metadata reflection | No |
 | [`server_integration_tests.rs`](../tests/server_integration_tests.rs) | `read_frame` unit-level I/O | No |
 | [`consumer_group_tests.rs`](../tests/consumer_group_tests.rs) | `FindCoordinator`/`JoinGroup`/`Heartbeat`/`LeaveGroup`/`SyncGroup`/`DescribeGroups`/`ListGroups` against one shared `GatewayState` with paused time, plus two-socket TCP rebalance and leave scenarios | No |
 | [`server_e2e_tests.rs`](../tests/server_e2e_tests.rs) | Full `KafkaGateway` TCP round-trips | Partial |
 | [`listener_robustness_tests.rs`](../tests/listener_robustness_tests.rs) | TCP listener robustness — framing, pipelining, concurrency, connection limits | No |
 | [`sasl_tests.rs`](../tests/sasl_tests.rs) | SASL/PLAIN over a socket — full handshake, every refusal path, and the disabled default. Drives a stub verifier implementing `SaslAuthenticator`, so no Iggy server is needed | No |
-| [`kafka_client_e2e_tests.rs`](../tests/kafka_client_e2e_tests.rs) | **Real Kafka clients** against the whole stack: a spawned `iggy-server`, the gateway in-process with a real authenticator, and kcat / the Java tools from containers. With a bridge, kcat writes records, and kcat and the Java consumer read them back through Fetch. Java consumers in one group resume from their commits, across a gateway restart and a member leaving. The only suite that can catch a client-compatibility bug, [...]
-| [`bridge_iggy_integration_tests.rs`](../tests/bridge_iggy_integration_tests.rs) | `IggyBridge` against a real, spawned `iggy-server` — provisioning idempotency, high watermark, credential/connection edge cases | No (needs the `iggy-server` binary - see Prerequisites) |
+| [`tls_listener_tests.rs`](../tests/tls_listener_tests.rs) | The `SSL` and `SASL_SSL` listeners over a real socket with certificates minted per test: each listener advertising its own port, a plaintext client refused on the TLS port, SASL inside TLS, client certificates mapped to users through a stub `PrincipalResolver` (`required`, `requested`, unknown user, SASL precedence), certificate reload without a restart, and the startup refusals | No |
+| [`kafka_client_e2e_tests.rs`](../tests/kafka_client_e2e_tests.rs) | **Real Kafka clients** against the whole stack: a spawned `iggy-server`, the gateway in-process with a real authenticator, and kcat / the Java tools from containers. With a bridge, kcat writes records, and kcat and the Java consumer read them back through Fetch. Java consumers in one group resume from their commits, across a gateway restart and a member leaving. librdkafka and the Java client connect with `security.pro [...]
+| [`bridge_iggy_integration_tests.rs`](../tests/bridge_iggy_integration_tests.rs) | `IggyBridge` against a real, spawned `iggy-server` — provisioning idempotency, high watermark, credential/connection edge cases, and the bridge dialing a TLS-only server over TLS | No (needs the `iggy-server` binary - see Prerequisites) |
 | [`list_offsets_real_bridge_tests.rs`](../tests/list_offsets_real_bridge_tests.rs) | ListOffsets (key 2) through the whole handler against a real, spawned `iggy-server`: LATEST, EARLIEST, codes 3 and 43 | No (needs the `iggy-server` binary - see Prerequisites) |
 | [`fetch_real_bridge_tests.rs`](../tests/fetch_real_bridge_tests.rs) | Fetch (key 1) through the whole handler against a real, spawned `iggy-server` — records go in through the Iggy SDK or the Produce handler and come back through `kafka_protocol`'s client decoder, at every version, with codes 0, 1, 3, 6, -1 and 70, paged polls, and the wait | No (needs the `iggy-server` binary - see Prerequisites) |
 | [`produce_real_bridge_tests.rs`](../tests/produce_real_bridge_tests.rs) | Produce (key 0) through the whole handler against a real, spawned `iggy-server` — records go in as Kafka wire bytes and come back through the Iggy SDK, plus one error code per partition | No (needs the `iggy-server` binary - see Prerequisites) |
 | [`offsets_real_bridge_tests.rs`](../tests/offsets_real_bridge_tests.rs) | OffsetCommit (key 8) and OffsetFetch (key 9) through the whole handler against a real, spawned `iggy-server`: offsets stored as sent, the Iggy external group key, a negative commit as a delete, -1 for nothing committed, a null topic list, and a gateway restart ([#3542](https://github.com/apache/iggy/issues/3542) acceptance) | No (needs the `iggy-server` binary - see Prerequisites) |
 | [`phase1_e2e_tests.rs`](../tests/phase1_e2e_tests.rs) | [#3539](https://github.com/apache/iggy/issues/3539) acceptance: CreateTopics → Metadata → Produce → ListOffsets over real TCP against the real compiled `iggy-gateway-kafka` binary bridged to a real spawned `iggy-server` - the only suite that spawns the gateway as a process rather than calling `KafkaGateway::run` in-process | No (needs both binaries - see Prerequisites) |
 
-`tests/common/` holds shared helpers (`codec.rs`, `fixtures.rs`, `gateway_process.rs`, `scope.rs`,
-`server.rs`, `iggy_server.rs`, `tcp.rs`, `wire.rs`), compiled per test binary via `#[path]`, not a test binary itself. `codec.rs`
+`tests/common/` holds shared helpers (`certs.rs`, `codec.rs`, `fixtures.rs`, `gateway_process.rs`,
+`scope.rs`, `server.rs`, `iggy_server.rs`, `tcp.rs`, `wire.rs`), compiled per test binary via `#[path]`, not a test binary itself. `certs.rs`
+mints a CA, server and client certificates with `rcgen` per test, so nothing in the tree can expire. `codec.rs`
 is test-only primitive encode/decode scaffolding for hand-building legacy/adversarial wire shapes
 `kafka_protocol`'s spec-correct encoder cannot produce - it is not the gateway's production codec.
 
diff --git a/gateways/kafka/src/auth.rs b/gateways/kafka/src/auth.rs
index 704c1218a..b10742091 100644
--- a/gateways/kafka/src/auth.rs
+++ b/gateways/kafka/src/auth.rs
@@ -29,13 +29,12 @@ use std::time::{Duration, Instant};
 use async_trait::async_trait;
 use iggy::prelude::{
     AutoLogin, Client, Credentials, Identifier, IggyError, Permissions, TcpClient,
-    TcpClientConfigBuilder,
+    TcpClientConfigBuilder, UserStatus,
 };
 use tokio::sync::SemaphorePermit;
 use tracing::{debug, warn};
 
-use crate::bridge::config::DEFAULT_IGGY_ADDR;
-use crate::env::parse_bool;
+use crate::bridge::config::{DEFAULT_IGGY_ADDR, IggyTls};
 use crate::protocol::acl::PrincipalPermissions;
 use crate::protocol::sasl::PlainCredentials;
 
@@ -240,18 +239,21 @@ pub trait SaslAuthenticator: Send + Sync + std::fmt::Debug {
     ) -> Result<AuthenticatedPrincipal, AuthError>;
 }
 
-/// How the verifier reaches Iggy.
+/// Names an Iggy user a listener authenticated by some means other than a password.
 ///
-/// Separate from the gateway's own listener security. A deployment can terminate TLS on the Kafka
-/// side and still speak plain TCP to a co-located Iggy, or the reverse, and the two are configured
-/// independently because they protect different hops.
-#[derive(Debug, Clone, Default)]
-pub struct IggyTls {
-    pub enabled: bool,
-    /// Name checked against the server certificate. Empty means derive it from the address.
-    pub domain: String,
-    /// PEM roots to trust. Unset uses the SDK's bundled roots, not the system trust store.
-    pub ca_file: Option<String>,
+/// An `SSL` listener that verifies client certificates maps each certificate's subject to a
+/// username and asks this whether that user exists and what it may do. The bridge implements it
+/// over its own session; the protocol tests drive the certificate path without an Iggy server
+/// through a stub.
+#[async_trait]
+pub trait PrincipalResolver: Send + Sync {
+    /// Returns the principal when `username` names an active Iggy user.
+    ///
+    /// # Errors
+    ///
+    /// Returns [`AuthError::Rejected`] when no such active user exists and
+    /// [`AuthError::Unavailable`] when Iggy cannot be asked.
+    async fn resolve(&self, username: &str) -> Result<AuthenticatedPrincipal, AuthError>;
 }
 
 /// Verifies credentials by logging into a real Iggy server with them.
@@ -322,30 +324,7 @@ impl IggyAuthenticator {
     pub fn from_env() -> Result<Self, String> {
         let address =
             std::env::var("IGGY_KAFKA_IGGY_ADDR").unwrap_or_else(|_| DEFAULT_IGGY_ADDR.to_string());
-        // Unset reads as off; only a value that is set and unrecognised is an error, which is
-        // what `parse_bool` decides for every switch in this gateway.
-        let enabled = match std::env::var("IGGY_KAFKA_IGGY_TLS_ENABLED") {
-            Ok(raw) => parse_bool("IGGY_KAFKA_IGGY_TLS_ENABLED", &raw)?,
-            Err(_) => false,
-        };
-        let domain = std::env::var("IGGY_KAFKA_IGGY_TLS_DOMAIN").unwrap_or_default();
-        let ca_file = std::env::var("IGGY_KAFKA_IGGY_TLS_CA_FILE").ok();
-        // Configuring TLS material and leaving the switch off is the same "believes TLS is on"
-        // mistake the value check above exists to catch, reached through the unset path instead of
-        // a typo. Silently ignoring it would send credentials in the clear.
-        if !enabled && (!domain.is_empty() || ca_file.is_some()) {
-            return Err(
-                "IGGY_KAFKA_IGGY_TLS_DOMAIN or IGGY_KAFKA_IGGY_TLS_CA_FILE is set but \
-                 IGGY_KAFKA_IGGY_TLS_ENABLED is not true; the connection to Iggy would be in the \
-                 clear despite the TLS configuration"
-                    .to_string(),
-            );
-        }
-        Ok(Self::new(address).with_tls(IggyTls {
-            enabled,
-            domain,
-            ca_file,
-        }))
+        Ok(Self::new(address).with_tls(IggyTls::from_env()?))
     }
 }
 
@@ -431,6 +410,67 @@ impl SaslAuthenticator for IggyAuthenticator {
     }
 }
 
+/// Looks up a user Iggy did not authenticate itself, for a listener where the client's
+/// certificate is the credential.
+///
+/// `client` is a session the gateway holds in its own name, so reading another account's record
+/// needs `read_users` on that session. A record that resolves to nothing is a rejection here,
+/// unlike [`fetch_permissions`]'s empty fallback: there a login had already proven the account
+/// exists, and here nothing has.
+///
+/// # Errors
+///
+/// Returns [`AuthError::Rejected`] when `username` names no active user and
+/// [`AuthError::Unavailable`] when the lookup itself failed, including for want of `read_users`.
+pub(crate) async fn resolve_principal(
+    client: &impl Client,
+    username: &str,
+) -> Result<AuthenticatedPrincipal, AuthError> {
+    let Ok(identifier) = Identifier::named(username) else {
+        debug!(
+            username,
+            "the certificate's mapped name is not a valid Iggy identifier"
+        );
+        return Err(AuthError::Rejected);
+    };
+    let user = match client.get_user(&identifier).await {
+        Ok(Some(user)) => user,
+        Ok(None) => {
+            debug!(
+                username,
+                "the certificate's mapped name is not an Iggy user"
+            );
+            return Err(AuthError::Rejected);
+        }
+        Err(IggyError::Unauthorized) => {
+            // Not a rejection: the account may well exist. The session doing the lookup lacks
+            // `read_users`, which is the operator's to fix, and reporting it as an unknown user
+            // would send them to provision an account they already have.
+            warn!(
+                "the bridge's Iggy user lacks read_users, so certificate identities cannot be resolved"
+            );
+            return Err(AuthError::Unavailable);
+        }
+        Err(error) => {
+            warn!(%error, "could not look up the certificate's Iggy user");
+            return Err(AuthError::Unavailable);
+        }
+    };
+    if user.status != UserStatus::Active {
+        debug!(username, "the certificate names an inactive Iggy user");
+        return Err(AuthError::Rejected);
+    }
+    Ok(AuthenticatedPrincipal {
+        username: username.to_string(),
+        permissions: user
+            .permissions
+            .as_ref()
+            .map(PrincipalPermissions::from)
+            .unwrap_or_default(),
+        permissions_known: true,
+    })
+}
+
 /// How the permission read after a login ended.
 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
 enum PermissionRead {
diff --git a/gateways/kafka/src/bridge/config.rs b/gateways/kafka/src/bridge/config.rs
index 8e8de7af1..ed66894a5 100644
--- a/gateways/kafka/src/bridge/config.rs
+++ b/gateways/kafka/src/bridge/config.rs
@@ -23,6 +23,7 @@ use tracing::warn;
 
 use crate::bridge::error::BridgeError;
 use crate::bridge::topic_map::{TopicMapping, validate_identifier_name};
+use crate::env::parse_bool;
 
 /// Iggy address used when `IGGY_KAFKA_IGGY_ADDR` is unset.
 ///
@@ -37,6 +38,64 @@ const DEFAULT_IGGY_USERNAME: &str = "iggy";
 /// Iggy's default `message_bus.max_message_size`.
 pub const DEFAULT_MAX_MESSAGE_SIZE: u64 = 64 * 1024 * 1024;
 
+/// How the gateway reaches Iggy: the bridge's own clients and the SASL credential check alike.
+///
+/// Separate from the gateway's own listener security. A deployment can terminate TLS on the Kafka
+/// side and still speak plain TCP to a co-located Iggy, or the reverse, and the two are configured
+/// independently because they protect different hops.
+#[derive(Debug, Clone, Default)]
+pub struct IggyTls {
+    pub enabled: bool,
+    /// Name checked against the server certificate. Empty means derive it from the address.
+    pub domain: String,
+    /// PEM roots to trust. Unset uses the SDK's bundled roots, not the system trust store.
+    pub ca_file: Option<String>,
+}
+
+impl IggyTls {
+    /// The `IGGY_KAFKA_*` vars [`Self::from_env`] reads.
+    pub const KNOWN_ENV_VARS: &'static [&'static str] = &[
+        "IGGY_KAFKA_IGGY_TLS_ENABLED",
+        "IGGY_KAFKA_IGGY_TLS_DOMAIN",
+        "IGGY_KAFKA_IGGY_TLS_CA_FILE",
+    ];
+
+    /// Reads the transport security of the Iggy hop from the environment.
+    ///
+    /// # Errors
+    ///
+    /// Returns a message naming the offending variable when `IGGY_KAFKA_IGGY_TLS_ENABLED` is set
+    /// to anything but `true` or `false`, or when material is configured with the switch off.
+    /// Defaulting a mistyped security switch to off is how a deployment ends up sending
+    /// passwords in the clear while believing it does not.
+    pub fn from_env() -> Result<Self, String> {
+        // Unset reads as off; only a value that is set and unrecognised is an error, which is
+        // what `parse_bool` decides for every switch in this gateway.
+        let enabled = match std::env::var("IGGY_KAFKA_IGGY_TLS_ENABLED") {
+            Ok(raw) => parse_bool("IGGY_KAFKA_IGGY_TLS_ENABLED", &raw)?,
+            Err(_) => false,
+        };
+        let domain = std::env::var("IGGY_KAFKA_IGGY_TLS_DOMAIN").unwrap_or_default();
+        let ca_file = std::env::var("IGGY_KAFKA_IGGY_TLS_CA_FILE").ok();
+        // Configuring TLS material and leaving the switch off is the same "believes TLS is on"
+        // mistake the value check above exists to catch, reached through the unset path instead of
+        // a typo. Silently ignoring it would send credentials in the clear.
+        if !enabled && (!domain.is_empty() || ca_file.is_some()) {
+            return Err(
+                "IGGY_KAFKA_IGGY_TLS_DOMAIN or IGGY_KAFKA_IGGY_TLS_CA_FILE is set but \
+                 IGGY_KAFKA_IGGY_TLS_ENABLED is not true; the connection to Iggy would be in the \
+                 clear despite the TLS configuration"
+                    .to_string(),
+            );
+        }
+        Ok(Self {
+            enabled,
+            domain,
+            ca_file,
+        })
+    }
+}
+
 /// Connection + topic-mapping config for [`IggyBridge`](crate::bridge::iggy_bridge::IggyBridge).
 ///
 /// `Debug` is safe to derive: `password` is `SecretString`, which redacts on `Debug` by design
@@ -50,6 +109,8 @@ pub struct IggyBridgeConfig {
     pub topic_mapping: TopicMapping,
     /// Iggy's `message_bus.max_message_size`, in bytes. Larger partitions answer 10.
     pub max_message_size: u64,
+    /// Transport security of every client the bridge opens.
+    pub tls: IggyTls,
 }
 
 impl IggyBridgeConfig {
@@ -68,6 +129,9 @@ impl IggyBridgeConfig {
         "IGGY_KAFKA_IGGY_STREAM",
         "IGGY_KAFKA_TOPIC_MAP_PATH",
         "IGGY_KAFKA_IGGY_MAX_MESSAGE_SIZE",
+        "IGGY_KAFKA_IGGY_TLS_ENABLED",
+        "IGGY_KAFKA_IGGY_TLS_DOMAIN",
+        "IGGY_KAFKA_IGGY_TLS_CA_FILE",
     ];
 
     /// Builds config from `IGGY_KAFKA_*` env vars, defaulting to the Iggy server's own
@@ -162,12 +226,15 @@ impl IggyBridgeConfig {
                 })?,
         };
 
+        let tls = IggyTls::from_env().map_err(BridgeError::InvalidConfig)?;
+
         Ok(Self {
             address,
             username,
             password: SecretString::from(password),
             topic_mapping,
             max_message_size,
+            tls,
         })
     }
 }
@@ -186,6 +253,7 @@ mod tests {
             topic_mapping: TopicMapping::new("kafka".to_string(), std::collections::HashMap::new())
                 .expect("valid mapping for this test's fixture data"),
             max_message_size: DEFAULT_MAX_MESSAGE_SIZE,
+            tls: IggyTls::default(),
         }
     }
 
@@ -220,6 +288,9 @@ mod tests {
             std::env::remove_var("IGGY_KAFKA_IGGY_STREAM");
             std::env::remove_var("IGGY_KAFKA_TOPIC_MAP_PATH");
             std::env::remove_var("IGGY_KAFKA_IGGY_MAX_MESSAGE_SIZE");
+            std::env::remove_var("IGGY_KAFKA_IGGY_TLS_ENABLED");
+            std::env::remove_var("IGGY_KAFKA_IGGY_TLS_DOMAIN");
+            std::env::remove_var("IGGY_KAFKA_IGGY_TLS_CA_FILE");
         }
         let result = IggyBridgeConfig::from_env();
         unsafe {
@@ -228,6 +299,10 @@ mod tests {
 
         let config = result.expect("valid config from documented defaults alone");
         assert_eq!(config.max_message_size, DEFAULT_MAX_MESSAGE_SIZE);
+        assert!(
+            !config.tls.enabled,
+            "the Iggy hop is in the clear unless switched on"
+        );
         assert_eq!(config.address, "127.0.0.1:8090");
         assert_eq!(config.username, "iggy");
         assert_eq!(config.topic_mapping.default_stream(), "kafka");
diff --git a/gateways/kafka/src/bridge/iggy_bridge/group_offsets.rs b/gateways/kafka/src/bridge/iggy_bridge/group_offsets.rs
index c455bce1e..4b6e60746 100644
--- a/gateways/kafka/src/bridge/iggy_bridge/group_offsets.rs
+++ b/gateways/kafka/src/bridge/iggy_bridge/group_offsets.rs
@@ -413,7 +413,7 @@ mod tests {
 
     use super::*;
     use crate::bridge::iggy_bridge::FetchPool;
-    use crate::bridge::{DEFAULT_MAX_MESSAGE_SIZE, IggyBridgeConfig, TopicMapping};
+    use crate::bridge::{DEFAULT_MAX_MESSAGE_SIZE, IggyBridgeConfig, IggyTls, TopicMapping};
 
     fn target(topic: &str) -> TopicTarget {
         TopicTarget {
@@ -457,6 +457,7 @@ mod tests {
                 password: SecretString::from("iggy"),
                 topic_mapping: TopicMapping::new("kafka".to_string(), HashMap::new()).unwrap(),
                 max_message_size: DEFAULT_MAX_MESSAGE_SIZE,
+                tls: IggyTls::default(),
             },
             send_slot: Arc::new(Semaphore::new(1)),
             fetch_pool: Arc::new(FetchPool::new()),
diff --git a/gateways/kafka/src/bridge/iggy_bridge/mod.rs b/gateways/kafka/src/bridge/iggy_bridge/mod.rs
index b0c8032ef..2fa920d87 100644
--- a/gateways/kafka/src/bridge/iggy_bridge/mod.rs
+++ b/gateways/kafka/src/bridge/iggy_bridge/mod.rs
@@ -19,6 +19,7 @@ use std::future::Future;
 use std::sync::Arc;
 use std::time::Duration;
 
+use async_trait::async_trait;
 use iggy::prelude::{
     AutoLogin, Client, Credentials, Identifier, IggyClient, IggyClientBuilder, IggyError,
 };
@@ -26,6 +27,7 @@ use tokio::sync::{OwnedSemaphorePermit, Semaphore, oneshot};
 use tokio::time::{Instant, timeout_at};
 use tracing::info;
 
+use crate::auth::{AuthError, AuthenticatedPrincipal, PrincipalResolver, resolve_principal};
 use crate::bridge::config::IggyBridgeConfig;
 use crate::bridge::error::BridgeError;
 use crate::bridge::topic_map::validate_kafka_topic_name;
@@ -243,13 +245,30 @@ async fn connect_client(config: &IggyBridgeConfig) -> Result<IggyClient, BridgeE
 
     let credentials =
         Credentials::UsernamePassword(config.username.clone(), config.password.clone());
-    let client = IggyClientBuilder::new()
+    let mut builder = IggyClientBuilder::new()
         .with_tcp()
         .with_server_address(config.address.clone())
         .with_auto_sign_in(AutoLogin::Enabled(credentials))
-        .with_reconnection_max_retries(Some(RECONNECTION_RETRIES))
-        .build()
-        .map_err(BridgeError::Iggy)?;
+        .with_reconnection_max_retries(Some(RECONNECTION_RETRIES));
+    if config.tls.enabled {
+        builder = builder.with_tls_enabled(true);
+        if !config.tls.domain.is_empty() {
+            builder = builder.with_tls_domain(config.tls.domain.clone());
+        }
+        if let Some(ref ca_file) = config.tls.ca_file {
+            builder = builder.with_tls_ca_file(ca_file.clone());
+        }
+    }
+    let client = builder.build().map_err(BridgeError::Iggy)?;
     with_request_timeout(client.connect()).await?;
     Ok(client)
 }
+
+/// The bridge's own session answers for the users client certificates name. It runs as the
+/// bridge's Iggy user, so that account needs `read_users` for any certificate to be admitted.
+#[async_trait]
+impl PrincipalResolver for IggyBridge {
+    async fn resolve(&self, username: &str) -> Result<AuthenticatedPrincipal, AuthError> {
+        resolve_principal(self.client.as_ref(), username).await
+    }
+}
diff --git a/gateways/kafka/src/bridge/mod.rs b/gateways/kafka/src/bridge/mod.rs
index 6083448f4..ac7796759 100644
--- a/gateways/kafka/src/bridge/mod.rs
+++ b/gateways/kafka/src/bridge/mod.rs
@@ -26,7 +26,7 @@ pub mod error;
 pub mod iggy_bridge;
 pub mod topic_map;
 
-pub use config::{DEFAULT_MAX_MESSAGE_SIZE, IggyBridgeConfig};
+pub use config::{DEFAULT_MAX_MESSAGE_SIZE, IggyBridgeConfig, IggyTls};
 pub use error::BridgeError;
 pub use iggy_bridge::{
     IggyBridge, KafkaTopicMetadata, OFFSET_GROUP_PREFIX, OffsetCalls, StreamTopicCache,
diff --git a/gateways/kafka/src/lib.rs b/gateways/kafka/src/lib.rs
index 722ddb6cb..49a222523 100644
--- a/gateways/kafka/src/lib.rs
+++ b/gateways/kafka/src/lib.rs
@@ -22,8 +22,10 @@ pub mod bridge;
 pub mod env;
 pub mod error;
 pub mod group;
+pub mod listener;
 pub mod protocol;
 pub mod records;
 pub mod server;
+pub mod tls;
 
 pub use server::{GatewayConfig, KafkaGateway};
diff --git a/gateways/kafka/src/listener.rs b/gateways/kafka/src/listener.rs
new file mode 100644
index 000000000..1fe2c580c
--- /dev/null
+++ b/gateways/kafka/src/listener.rs
@@ -0,0 +1,439 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Listeners, one per Kafka security protocol.
+//!
+//! The shape is Kafka's own `listeners` and `advertised.listeners`: `PROTOCOL://host:port`
+//! entries separated by commas, with the protocol doubling as the listener name. A client is
+//! told the address of the listener it arrived through and no other, so a client on the TLS port
+//! is never pointed at the plaintext one by Metadata.
+
+use std::fmt;
+use std::net::SocketAddr;
+use std::str::FromStr;
+
+use crate::error::{KafkaProtocolError, Result};
+use crate::protocol::api::BrokerAdvertise;
+
+/// Kafka's four listener security protocols.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum SecurityProtocol {
+    Plaintext,
+    Ssl,
+    SaslPlaintext,
+    SaslSsl,
+}
+
+impl SecurityProtocol {
+    pub const ALL: [Self; 4] = [
+        Self::Plaintext,
+        Self::Ssl,
+        Self::SaslPlaintext,
+        Self::SaslSsl,
+    ];
+
+    #[must_use]
+    pub const fn uses_tls(self) -> bool {
+        matches!(self, Self::Ssl | Self::SaslSsl)
+    }
+
+    #[must_use]
+    pub const fn uses_sasl(self) -> bool {
+        matches!(self, Self::SaslPlaintext | Self::SaslSsl)
+    }
+
+    /// Whether a client certificate names the principal on this listener.
+    ///
+    /// Only on a listener without SASL: with SASL the exchange names the principal and the
+    /// certificate, when one is demanded, only gates the transport, which is how Kafka treats a
+    /// `SASL_SSL` listener with `ssl.client.auth=required`.
+    #[must_use]
+    pub const fn authenticates_by_certificate(self) -> bool {
+        matches!(self, Self::Ssl)
+    }
+
+    #[must_use]
+    pub const fn as_str(self) -> &'static str {
+        match self {
+            Self::Plaintext => "PLAINTEXT",
+            Self::Ssl => "SSL",
+            Self::SaslPlaintext => "SASL_PLAINTEXT",
+            Self::SaslSsl => "SASL_SSL",
+        }
+    }
+}
+
+impl FromStr for SecurityProtocol {
+    type Err = KafkaProtocolError;
+
+    /// Exact, upper-case spellings only, like every switch this gateway reads: a lower-case or
+    /// misspelled protocol must stop the process rather than quietly pick a weaker listener.
+    fn from_str(raw: &str) -> Result<Self> {
+        Self::ALL
+            .into_iter()
+            .find(|protocol| protocol.as_str() == raw)
+            .ok_or_else(|| {
+                KafkaProtocolError::InvalidConfig(format!(
+                    "unknown security protocol '{raw}'; expected one of PLAINTEXT, SSL, \
+                     SASL_PLAINTEXT, SASL_SSL"
+                ))
+            })
+    }
+}
+
+impl fmt::Display for SecurityProtocol {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.write_str(self.as_str())
+    }
+}
+
+/// One listener: where it binds and what it tells clients to connect back to.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ListenerConfig {
+    pub protocol: SecurityProtocol,
+    /// `host:port` to bind. Must parse as a socket address.
+    pub bind_addr: String,
+    /// Hostname or IP advertised in Metadata. Required when `bind_addr` is a wildcard.
+    pub advertised_host: Option<String>,
+    /// Port advertised in Metadata. Defaults to the bound port.
+    pub advertised_port: Option<u16>,
+}
+
+impl ListenerConfig {
+    #[must_use]
+    pub fn new(protocol: SecurityProtocol, bind_addr: impl Into<String>) -> Self {
+        Self {
+            protocol,
+            bind_addr: bind_addr.into(),
+            advertised_host: None,
+            advertised_port: None,
+        }
+    }
+
+    #[must_use]
+    pub fn with_advertised(mut self, host: impl Into<String>, port: u16) -> Self {
+        self.advertised_host = Some(host.into());
+        self.advertised_port = Some(port);
+        self
+    }
+}
+
+/// Parses `IGGY_KAFKA_LISTENERS`: `PROTOCOL://host:port`, comma separated.
+///
+/// Each protocol may appear once, since it is the listener's name and the key
+/// `IGGY_KAFKA_ADVERTISED_LISTENERS` addresses it by. The host must be an IP address: the bind
+/// goes through `socket2`, which takes no hostname.
+///
+/// # Errors
+///
+/// Returns `InvalidConfig` naming the variable for an empty list, a malformed entry, an unknown
+/// protocol or a repeated one.
+pub fn parse_listeners(raw: &str) -> Result<Vec<ListenerConfig>> {
+    let mut listeners: Vec<ListenerConfig> = Vec::new();
+    for entry in raw.split(',').map(str::trim) {
+        if entry.is_empty() {
+            return Err(invalid(format!(
+                "IGGY_KAFKA_LISTENERS has an empty entry in '{raw}'"
+            )));
+        }
+        let (protocol, address) = split_entry("IGGY_KAFKA_LISTENERS", entry)?;
+        let bind_addr: SocketAddr = address.parse().map_err(|error| {
+            invalid(format!(
+                "IGGY_KAFKA_LISTENERS entry '{entry}' must bind an IP address and port: {error}"
+            ))
+        })?;
+        if listeners
+            .iter()
+            .any(|listener| listener.protocol == protocol)
+        {
+            return Err(invalid(format!(
+                "IGGY_KAFKA_LISTENERS names {protocol} twice; one listener per security protocol"
+            )));
+        }
+        listeners.push(ListenerConfig::new(protocol, bind_addr.to_string()));
+    }
+    Ok(listeners)
+}
+
+/// Applies `IGGY_KAFKA_ADVERTISED_LISTENERS` to `listeners`: `PROTOCOL://host:port` per entry.
+///
+/// The host may be a name, since it is handed to clients rather than bound.
+///
+/// # Errors
+///
+/// Returns `InvalidConfig` naming the variable for a malformed entry, a protocol that has no
+/// listener, or one advertised twice.
+pub fn apply_advertised_listeners(listeners: &mut [ListenerConfig], raw: &str) -> Result<()> {
+    let mut seen: Vec<SecurityProtocol> = Vec::new();
+    for entry in raw.split(',').map(str::trim) {
+        if entry.is_empty() {
+            return Err(invalid(format!(
+                "IGGY_KAFKA_ADVERTISED_LISTENERS has an empty entry in '{raw}'"
+            )));
+        }
+        let (protocol, address) = split_entry("IGGY_KAFKA_ADVERTISED_LISTENERS", entry)?;
+        let (host, port) = split_host_port(address).ok_or_else(|| {
+            invalid(format!(
+                "IGGY_KAFKA_ADVERTISED_LISTENERS entry '{entry}' must be PROTOCOL://host:port"
+            ))
+        })?;
+        let port: u16 = port.parse().map_err(|error| {
+            invalid(format!(
+                "IGGY_KAFKA_ADVERTISED_LISTENERS entry '{entry}' has an invalid port: {error}"
+            ))
+        })?;
+        if port == 0 {
+            return Err(invalid(format!(
+                "IGGY_KAFKA_ADVERTISED_LISTENERS entry '{entry}' advertises port 0"
+            )));
+        }
+        if seen.contains(&protocol) {
+            return Err(invalid(format!(
+                "IGGY_KAFKA_ADVERTISED_LISTENERS names {protocol} twice"
+            )));
+        }
+        let Some(listener) = listeners
+            .iter_mut()
+            .find(|listener| listener.protocol == protocol)
+        else {
+            return Err(invalid(format!(
+                "IGGY_KAFKA_ADVERTISED_LISTENERS advertises {protocol}, which IGGY_KAFKA_LISTENERS \
+                 does not bind"
+            )));
+        };
+        listener.advertised_host = Some(host.to_string());
+        listener.advertised_port = Some(port);
+        seen.push(protocol);
+    }
+    Ok(())
+}
+
+impl BrokerAdvertise {
+    /// Resolves the broker endpoint one listener advertises in Metadata and `FindCoordinator`.
+    ///
+    /// `local_addr` is the address the listener is actually bound to.
+    ///
+    /// # Errors
+    ///
+    /// Returns `InvalidConfig` when the advertised host is empty or too long for a Kafka string,
+    /// or when the listener binds a wildcard without an explicit advertised host.
+    pub fn for_listener(listener: &ListenerConfig, local_addr: SocketAddr) -> Result<Self> {
+        let port = listener
+            .advertised_port
+            .map_or_else(|| i32::from(local_addr.port()), i32::from);
+        let protocol = listener.protocol;
+
+        let host = if let Some(ref advertised) = listener.advertised_host {
+            let trimmed = advertised.trim();
+            if trimmed.is_empty() {
+                return Err(invalid(format!(
+                    "the advertised host of the {protocol} listener must not be empty \
+                     (IGGY_KAFKA_ADVERTISED_LISTENERS, or IGGY_KAFKA_ADVERTISED_HOST for the \
+                     single-listener form)"
+                )));
+            }
+            if trimmed.len() > i16::MAX as usize {
+                return Err(invalid(format!(
+                    "the advertised host of the {protocol} listener exceeds Kafka's nullable \
+                     string limit (32767 bytes) (IGGY_KAFKA_ADVERTISED_LISTENERS, or \
+                     IGGY_KAFKA_ADVERTISED_HOST for the single-listener form)"
+                )));
+            }
+            trimmed.to_string()
+        } else if local_addr.ip().is_unspecified() {
+            return Err(invalid(format!(
+                "the {protocol} listener binds a wildcard address (0.0.0.0 or ::), so clients \
+                 need a reachable hostname or IP to be pointed back at: set \
+                 IGGY_KAFKA_ADVERTISED_LISTENERS={protocol}://<host>:<port> (or \
+                 IGGY_KAFKA_ADVERTISED_HOST for the single-listener form)"
+            )));
+        } else {
+            local_addr.ip().to_string()
+        };
+
+        Ok(Self { host, port })
+    }
+}
+
+/// Splits `PROTOCOL://rest` into the protocol and the rest.
+fn split_entry<'a>(var: &str, entry: &'a str) -> Result<(SecurityProtocol, &'a str)> {
+    let Some((protocol, address)) = entry.split_once("://") else {
+        return Err(invalid(format!(
+            "{var} entry '{entry}' must be PROTOCOL://host:port"
+        )));
+    };
+    let protocol: SecurityProtocol = protocol
+        .parse()
+        .map_err(|error| invalid(format!("{var} entry '{entry}': {error}")))?;
+    if address.is_empty() {
+        return Err(invalid(format!(
+            "{var} entry '{entry}' names no address after {protocol}://"
+        )));
+    }
+    Ok((protocol, address))
+}
+
+/// Splits `host:port`, with `[v6]:port` for an IPv6 literal, into a bracket-free host and the
+/// port text.
+fn split_host_port(address: &str) -> Option<(&str, &str)> {
+    let (host, port) = address.rsplit_once(':')?;
+    let host = host
+        .strip_prefix('[')
+        .map_or(host, |inner| inner.strip_suffix(']').unwrap_or(host));
+    if host.is_empty() {
+        return None;
+    }
+    Some((host, port))
+}
+
+const fn invalid(message: String) -> KafkaProtocolError {
+    KafkaProtocolError::InvalidConfig(message)
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn given_kafka_style_listeners_should_parse_one_per_protocol() {
+        let listeners =
+            parse_listeners("PLAINTEXT://127.0.0.1:9093, SSL://0.0.0.0:9094,SASL_SSL://[::]:9095")
+                .expect("valid listeners");
+        assert_eq!(
+            listeners,
+            vec![
+                ListenerConfig::new(SecurityProtocol::Plaintext, "127.0.0.1:9093"),
+                ListenerConfig::new(SecurityProtocol::Ssl, "0.0.0.0:9094"),
+                ListenerConfig::new(SecurityProtocol::SaslSsl, "[::]:9095"),
+            ]
+        );
+    }
+
+    #[test]
+    fn given_a_malformed_listener_should_name_the_variable_and_the_entry() {
+        for raw in [
+            "",
+            "PLAINTEXT://127.0.0.1:9093,",
+            "127.0.0.1:9093",
+            "plaintext://127.0.0.1:9093",
+            "SSL://",
+            "SSL://localhost:9093",
+            "SSL://127.0.0.1",
+            "SSL://127.0.0.1:9093,SSL://127.0.0.1:9094",
+        ] {
+            let error = parse_listeners(raw)
+                .err()
+                .unwrap_or_else(|| panic!("'{raw}' must be rejected"))
+                .to_string();
+            assert!(
+                error.contains("IGGY_KAFKA_LISTENERS"),
+                "'{raw}' rejection must name the variable, got: {error}"
+            );
+        }
+    }
+
+    #[test]
+    fn given_advertised_listeners_should_apply_to_the_matching_protocol_only() {
+        let mut listeners =
+            parse_listeners("PLAINTEXT://0.0.0.0:9093,SSL://0.0.0.0:9094").expect("valid");
+        apply_advertised_listeners(
+            &mut listeners,
+            "SSL://kafka.example.com:19094, PLAINTEXT://[2001:db8::1]:19093",
+        )
+        .expect("valid advertisement");
+        assert_eq!(
+            listeners[0].advertised_host.as_deref(),
+            Some("2001:db8::1"),
+            "an IPv6 literal is advertised without its brackets"
+        );
+        assert_eq!(listeners[0].advertised_port, Some(19093));
+        assert_eq!(
+            listeners[1].advertised_host.as_deref(),
+            Some("kafka.example.com")
+        );
+        assert_eq!(listeners[1].advertised_port, Some(19094));
+    }
+
+    #[test]
+    fn given_an_advertisement_for_an_unbound_protocol_should_refuse() {
+        let mut listeners = parse_listeners("PLAINTEXT://127.0.0.1:9093").expect("valid");
+        for raw in [
+            "SSL://kafka.example.com:9094",
+            "PLAINTEXT://:9093",
+            "PLAINTEXT://kafka.example.com",
+            "PLAINTEXT://kafka.example.com:0",
+            "PLAINTEXT://kafka.example.com:9093,PLAINTEXT://other:9093",
+        ] {
+            let error = apply_advertised_listeners(&mut listeners, raw)
+                .err()
+                .unwrap_or_else(|| panic!("'{raw}' must be rejected"))
+                .to_string();
+            assert!(
+                error.contains("IGGY_KAFKA_ADVERTISED_LISTENERS"),
+                "'{raw}' rejection must name the variable, got: {error}"
+            );
+        }
+    }
+
+    #[test]
+    fn given_a_wildcard_bind_without_an_advertised_host_should_refuse_and_name_the_listener() {
+        let listener = ListenerConfig::new(SecurityProtocol::SaslSsl, "0.0.0.0:9095");
+        let error = BrokerAdvertise::for_listener(&listener, "0.0.0.0:9095".parse().unwrap())
+            .unwrap_err()
+            .to_string();
+        assert!(error.contains("SASL_SSL"), "got: {error}");
+        assert!(
+            error.contains("IGGY_KAFKA_ADVERTISED_LISTENERS"),
+            "got: {error}"
+        );
+        assert!(error.contains("IGGY_KAFKA_ADVERTISED_HOST"), "got: {error}");
+    }
+
+    #[test]
+    fn given_an_advertised_port_should_override_the_bound_one() {
+        let listener = ListenerConfig::new(SecurityProtocol::Ssl, "127.0.0.1:0")
+            .with_advertised("broker.example.com", 19094);
+        let broker = BrokerAdvertise::for_listener(&listener, "127.0.0.1:41234".parse().unwrap())
+            .expect("valid");
+        assert_eq!(broker.host, "broker.example.com");
+        assert_eq!(broker.port, 19094);
+    }
+
+    #[test]
+    fn given_a_concrete_bind_should_advertise_the_bound_address() {
+        let listener = ListenerConfig::new(SecurityProtocol::Plaintext, "192.168.1.10:0");
+        let broker =
+            BrokerAdvertise::for_listener(&listener, "192.168.1.10:19092".parse().unwrap())
+                .expect("valid");
+        assert_eq!(broker.host, "192.168.1.10");
+        assert_eq!(broker.port, 19092);
+    }
+
+    #[test]
+    fn security_protocol_round_trips_through_its_name() {
+        for protocol in SecurityProtocol::ALL {
+            assert_eq!(
+                protocol.as_str().parse::<SecurityProtocol>().unwrap(),
+                protocol
+            );
+        }
+        assert!("ssl".parse::<SecurityProtocol>().is_err());
+        assert!(SecurityProtocol::SaslSsl.uses_tls() && SecurityProtocol::SaslSsl.uses_sasl());
+        assert!(SecurityProtocol::Ssl.authenticates_by_certificate());
+        assert!(!SecurityProtocol::SaslSsl.authenticates_by_certificate());
+    }
+}
diff --git a/gateways/kafka/src/main.rs b/gateways/kafka/src/main.rs
index 11233607e..9a138da72 100644
--- a/gateways/kafka/src/main.rs
+++ b/gateways/kafka/src/main.rs
@@ -25,9 +25,13 @@ use tokio::sync::{Semaphore, broadcast};
 use tracing::{info, warn};
 
 use iggy_gateway_kafka::auth::IggyAuthenticator;
-use iggy_gateway_kafka::bridge::{IggyBridge, IggyBridgeConfig};
+use iggy_gateway_kafka::bridge::{IggyBridge, IggyBridgeConfig, IggyTls};
 use iggy_gateway_kafka::env::parse_bool;
-use iggy_gateway_kafka::server::{bind_listener, init_tracing};
+use iggy_gateway_kafka::listener::{
+    ListenerConfig, SecurityProtocol, apply_advertised_listeners, parse_listeners,
+};
+use iggy_gateway_kafka::server::{bind_listeners, init_tracing};
+use iggy_gateway_kafka::tls::{ClientAuth, TlsConfig};
 use iggy_gateway_kafka::{GatewayConfig, KafkaGateway};
 
 #[tokio::main]
@@ -38,26 +42,30 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
     let _tracing_guard = init_tracing();
 
     let config = load_config()?;
-    let sasl_enabled = config.sasl_enabled;
+    let sasl_enabled = config.sasl_enabled();
+    let plaintext_sasl = config
+        .listeners
+        .iter()
+        .any(|listener| listener.protocol == SecurityProtocol::SaslPlaintext);
     let bridge = connect_bridge(sasl_enabled).await?;
 
-    let listener = bind_listener(&config.bind_addr)
-        .map_err(|e| format!("failed to bind {}: {e}", config.bind_addr))?;
+    let listeners = bind_listeners(&config).map_err(|e| e.to_string())?;
     let mut server = KafkaGateway::new(config).with_bridge(bridge);
     if sasl_enabled {
         let authenticator = IggyAuthenticator::from_env()?;
-        // Unconditional, because the Kafka listener has no TLS at any setting. This is the hop the
-        // Kafka client's password actually crosses, and gating the warning on the Iggy hop meant
-        // encrypting that one silenced the only notice about this one.
-        warn!(
-            "SASL/PLAIN sends the password in the clear and the Kafka listener has no TLS; only \
-             run this on a trusted network until listener TLS lands"
-        );
+        if plaintext_sasl {
+            // This is the hop the Kafka client's password actually crosses. The warning is tied
+            // to the listener that exposes it, not to the Iggy hop, so encrypting the Iggy side
+            // does not silence the only notice about this one.
+            warn!(
+                "SASL/PLAIN on the SASL_PLAINTEXT listener sends the password in the clear; use \
+                 a SASL_SSL listener outside a trusted network"
+            );
+        }
         if !authenticator.is_tls_enabled() {
             warn!(
-                "the credential check's link to Iggy is also unencrypted; set \
-                 IGGY_KAFKA_IGGY_TLS_ENABLED=true to encrypt it. The bridge's own connection has \
-                 no TLS at any setting"
+                "the credential check's link to Iggy is unencrypted; set \
+                 IGGY_KAFKA_IGGY_TLS_ENABLED=true to encrypt it"
             );
         }
         info!("SASL/PLAIN enabled; credentials verified against {authenticator}");
@@ -65,7 +73,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
     }
 
     let (tx, rx) = broadcast::channel(1);
-    let mut server_task = tokio::spawn(async move { server.run(listener, rx).await });
+    let mut server_task = tokio::spawn(async move { server.run(listeners, rx).await });
 
     tokio::select! {
         result = &mut server_task => {
@@ -93,6 +101,14 @@ const KNOWN_KAFKA_ENV_VARS: &[&str] = &[
     "IGGY_KAFKA_BIND_ADDR",
     "IGGY_KAFKA_ADVERTISED_HOST",
     "IGGY_KAFKA_ADVERTISED_PORT",
+    "IGGY_KAFKA_LISTENERS",
+    "IGGY_KAFKA_ADVERTISED_LISTENERS",
+    "IGGY_KAFKA_TLS_CERT_FILE",
+    "IGGY_KAFKA_TLS_KEY_FILE",
+    "IGGY_KAFKA_TLS_CLIENT_AUTH",
+    "IGGY_KAFKA_TLS_CLIENT_CA_FILE",
+    "IGGY_KAFKA_TLS_PRINCIPAL_MAPPING_RULES",
+    "IGGY_KAFKA_TLS_RELOAD_INTERVAL_SECS",
     "IGGY_KAFKA_MAX_CONNECTIONS",
     "IGGY_KAFKA_MAX_FRAME_SIZE",
     "IGGY_KAFKA_IDLE_TIMEOUT_SECS",
@@ -106,6 +122,24 @@ const KNOWN_KAFKA_ENV_VARS: &[&str] = &[
     "IGGY_KAFKA_MAX_CONCURRENT_AUTHENTICATIONS",
 ];
 
+/// The variables of the single-listener form, which `IGGY_KAFKA_LISTENERS` replaces as a whole.
+const SINGLE_LISTENER_ENV_VARS: &[&str] = &[
+    "IGGY_KAFKA_BIND_ADDR",
+    "IGGY_KAFKA_ADVERTISED_HOST",
+    "IGGY_KAFKA_ADVERTISED_PORT",
+    "IGGY_KAFKA_SASL_ENABLED",
+];
+
+/// The variables only a TLS listener reads.
+const TLS_ENV_VARS: &[&str] = &[
+    "IGGY_KAFKA_TLS_CERT_FILE",
+    "IGGY_KAFKA_TLS_KEY_FILE",
+    "IGGY_KAFKA_TLS_CLIENT_AUTH",
+    "IGGY_KAFKA_TLS_CLIENT_CA_FILE",
+    "IGGY_KAFKA_TLS_PRINCIPAL_MAPPING_RULES",
+    "IGGY_KAFKA_TLS_RELOAD_INTERVAL_SECS",
+];
+
 /// Rejects any `IGGY_KAFKA_*` env var not in [`KNOWN_KAFKA_ENV_VARS`] or
 /// [`IggyBridgeConfig::KNOWN_ENV_VARS`] - a typo (e.g. `IGGY_KAFKA_BIN_ADDR`) would otherwise be
 /// silently ignored: the server's check in `core/configs` skips the whole `IGGY_KAFKA_` prefix, and
@@ -140,11 +174,14 @@ async fn connect_bridge(sasl_enabled: bool) -> Result<Option<Arc<IggyBridge>>, S
         let set: Vec<&str> = IggyBridgeConfig::KNOWN_ENV_VARS
             .iter()
             .copied()
-            // With SASL on, the address is the one bridge variable that is genuinely read, since
-            // it names the server credentials are verified against. Warning that nothing reads it
-            // would be false, and suppressing the whole list instead would hide a set credential
-            // that really does go nowhere.
-            .filter(|var| !(sasl_enabled && *var == "IGGY_KAFKA_IGGY_ADDR"))
+            // With SASL on, the address and the TLS switches are the bridge variables that are
+            // genuinely read, since they name and secure the server credentials are verified
+            // against. Warning that nothing reads them would be false, and suppressing the whole
+            // list instead would hide a set credential that really does go nowhere.
+            .filter(|var| {
+                !(sasl_enabled
+                    && (*var == "IGGY_KAFKA_IGGY_ADDR" || IggyTls::KNOWN_ENV_VARS.contains(var)))
+            })
             .filter(|var| std::env::var(var).is_ok())
             .collect();
         if !set.is_empty() {
@@ -157,6 +194,12 @@ async fn connect_bridge(sasl_enabled: bool) -> Result<Option<Arc<IggyBridge>>, S
         return Ok(None);
     }
     let config = IggyBridgeConfig::from_env().map_err(|e| format!("invalid bridge config: {e}"))?;
+    if !config.tls.enabled {
+        warn!(
+            "the bridge's connection to Iggy is unencrypted and carries IGGY_KAFKA_IGGY_PASSWORD \
+             in the clear; set IGGY_KAFKA_IGGY_TLS_ENABLED=true to encrypt it"
+        );
+    }
     let bridge = IggyBridge::connect(config)
         .await
         .map_err(|e| format!("failed to connect the Iggy bridge: {e}"))?;
@@ -181,15 +224,8 @@ fn load_config() -> Result<GatewayConfig, String> {
     reject_unknown_kafka_env_vars()?;
     let mut config = GatewayConfig::default();
 
-    if let Some(bind_addr) = env_var("IGGY_KAFKA_BIND_ADDR") {
-        config.bind_addr = bind_addr;
-    }
-    if let Some(advertised_host) = env_var("IGGY_KAFKA_ADVERTISED_HOST") {
-        config.advertised_host = Some(advertised_host);
-    }
-    if let Some(raw) = env_var("IGGY_KAFKA_ADVERTISED_PORT") {
-        config.advertised_port = Some(parse_positive("IGGY_KAFKA_ADVERTISED_PORT", &raw)?);
-    }
+    config.listeners = load_listeners()?;
+    config.tls = load_tls(&config.listeners)?;
     if let Some(raw) = env_var("IGGY_KAFKA_MAX_CONNECTIONS") {
         let max_connections: usize = parse_positive("IGGY_KAFKA_MAX_CONNECTIONS", &raw)?;
         if max_connections > Semaphore::MAX_PERMITS {
@@ -215,9 +251,6 @@ fn load_config() -> Result<GatewayConfig, String> {
         config.write_timeout =
             Duration::from_secs(parse_positive("IGGY_KAFKA_WRITE_TIMEOUT_SECS", &raw)?);
     }
-    if let Some(raw) = env_var("IGGY_KAFKA_SASL_ENABLED") {
-        config.sasl_enabled = parse_bool("IGGY_KAFKA_SASL_ENABLED", &raw)?;
-    }
     if let Some(raw) = env_var("IGGY_KAFKA_PRE_AUTH_TIMEOUT_SECS") {
         config.pre_auth_timeout =
             Duration::from_secs(parse_positive("IGGY_KAFKA_PRE_AUTH_TIMEOUT_SECS", &raw)?);
@@ -258,32 +291,182 @@ fn load_config() -> Result<GatewayConfig, String> {
              Iggy cluster needs its own value, or they hand out colliding producer ids"
         );
     }
-    reject_iggy_tls_without_sasl(config.sasl_enabled)?;
+    reject_unread_iggy_tls(config.sasl_enabled(), bridge_enabled()?)?;
 
     Ok(config)
 }
 
-/// Refuses `IGGY_KAFKA_IGGY_TLS_*` while SASL is off.
+/// The listeners, from `IGGY_KAFKA_LISTENERS` or from the single-listener variables.
 ///
-/// Only the credential verifier reads them, and it is built only with SASL on. Accepting them
-/// otherwise lets an operator believe the link to Iggy is encrypted when nothing reads the switch,
-/// the same mistake `IggyAuthenticator::from_env` refuses to start for.
-fn reject_iggy_tls_without_sasl(sasl_enabled: bool) -> Result<(), String> {
-    if sasl_enabled {
+/// With a listener list, the single-listener address variables are ignored with a warning rather
+/// than refused: the gateway's own image bakes `IGGY_KAFKA_BIND_ADDR=0.0.0.0:9093` in, and
+/// refusing it would make `IGGY_KAFKA_LISTENERS` unusable there. `IGGY_KAFKA_SASL_ENABLED` is
+/// refused beside a list all the same. It is a security switch, and with a list the protocol of
+/// each listener says whether it runs SASL, so a `true` left over from the single-listener form
+/// would otherwise read as SASL on while nothing ran it.
+fn load_listeners() -> Result<Vec<ListenerConfig>, String> {
+    let addressing: Vec<&str> = SINGLE_LISTENER_ENV_VARS
+        .iter()
+        .copied()
+        .filter(|var| *var != "IGGY_KAFKA_SASL_ENABLED" && env_var(var).is_some())
+        .collect();
+    let advertised = env_var("IGGY_KAFKA_ADVERTISED_LISTENERS");
+    if let Some(raw) = env_var("IGGY_KAFKA_LISTENERS") {
+        if env_var("IGGY_KAFKA_SASL_ENABLED").is_some() {
+            return Err(
+                "IGGY_KAFKA_LISTENERS and IGGY_KAFKA_SASL_ENABLED are both set; with a listener \
+                 list, a SASL_PLAINTEXT or SASL_SSL listener is what turns SASL on"
+                    .to_string(),
+            );
+        }
+        if !addressing.is_empty() {
+            warn!(
+                "{} set but IGGY_KAFKA_LISTENERS takes precedence; they are ignored (bind and \
+                 advertise through IGGY_KAFKA_LISTENERS and IGGY_KAFKA_ADVERTISED_LISTENERS)",
+                addressing.join(", ")
+            );
+        }
+        let mut listeners = parse_listeners(&raw).map_err(|e| e.to_string())?;
+        if let Some(advertised) = advertised {
+            apply_advertised_listeners(&mut listeners, &advertised).map_err(|e| e.to_string())?;
+        }
+        return Ok(listeners);
+    }
+    if advertised.is_some() {
+        return Err(
+            "IGGY_KAFKA_ADVERTISED_LISTENERS is set but IGGY_KAFKA_LISTENERS is not; the \
+             single-listener form advertises through IGGY_KAFKA_ADVERTISED_HOST and \
+             IGGY_KAFKA_ADVERTISED_PORT"
+                .to_string(),
+        );
+    }
+    let sasl_enabled = match env_var("IGGY_KAFKA_SASL_ENABLED") {
+        Some(raw) => parse_bool("IGGY_KAFKA_SASL_ENABLED", &raw)?,
+        None => false,
+    };
+    let protocol = if sasl_enabled {
+        SecurityProtocol::SaslPlaintext
+    } else {
+        SecurityProtocol::Plaintext
+    };
+    let bind_addr = env_var("IGGY_KAFKA_BIND_ADDR")
+        .unwrap_or_else(|| GatewayConfig::default().listeners[0].bind_addr.clone());
+    let mut listener = ListenerConfig::new(protocol, bind_addr);
+    listener.advertised_host = env_var("IGGY_KAFKA_ADVERTISED_HOST");
+    if let Some(raw) = env_var("IGGY_KAFKA_ADVERTISED_PORT") {
+        listener.advertised_port = Some(parse_positive("IGGY_KAFKA_ADVERTISED_PORT", &raw)?);
+    }
+    Ok(vec![listener])
+}
+
+/// The TLS material, required exactly when a listener speaks TLS.
+///
+/// Every combination in which something set would go unread is refused, the way the SASL and
+/// Iggy-hop switches are: material without a TLS listener, a client CA without client
+/// authentication, mapping rules without an `SSL` listener to apply them on. Each reads to whoever
+/// set it as a protection that is on.
+fn load_tls(listeners: &[ListenerConfig]) -> Result<Option<TlsConfig>, String> {
+    let set: Vec<&str> = TLS_ENV_VARS
+        .iter()
+        .copied()
+        .filter(|var| env_var(var).is_some())
+        .collect();
+    if !listeners
+        .iter()
+        .any(|listener| listener.protocol.uses_tls())
+    {
+        if set.is_empty() {
+            return Ok(None);
+        }
+        return Err(format!(
+            "{} set but no listener uses TLS; add an SSL or SASL_SSL listener to \
+             IGGY_KAFKA_LISTENERS, or unset them",
+            set.join(", ")
+        ));
+    }
+    let cert_file = env_var("IGGY_KAFKA_TLS_CERT_FILE").ok_or(
+        "IGGY_KAFKA_TLS_CERT_FILE must name a PEM certificate for an SSL or SASL_SSL listener",
+    )?;
+    let key_file = env_var("IGGY_KAFKA_TLS_KEY_FILE").ok_or(
+        "IGGY_KAFKA_TLS_KEY_FILE must name a PEM private key for an SSL or SASL_SSL listener",
+    )?;
+    let mut tls = TlsConfig::new(cert_file, key_file);
+
+    let client_auth = match env_var("IGGY_KAFKA_TLS_CLIENT_AUTH") {
+        Some(raw) => raw
+            .parse::<ClientAuth>()
+            .map_err(|e| format!("invalid IGGY_KAFKA_TLS_CLIENT_AUTH `{raw}`: {e}"))?,
+        None => ClientAuth::None,
+    };
+    match (
+        client_auth.is_enabled(),
+        env_var("IGGY_KAFKA_TLS_CLIENT_CA_FILE"),
+    ) {
+        (true, Some(ca_file)) => tls = tls.with_client_auth(client_auth, ca_file),
+        (true, None) => {
+            return Err(format!(
+                "IGGY_KAFKA_TLS_CLIENT_AUTH is {client_auth} but IGGY_KAFKA_TLS_CLIENT_CA_FILE is \
+                 not set; nothing could verify a client certificate"
+            ));
+        }
+        (false, Some(_)) => {
+            return Err(
+                "IGGY_KAFKA_TLS_CLIENT_CA_FILE is set but IGGY_KAFKA_TLS_CLIENT_AUTH is not \
+                 requested or required; no client would be asked for a certificate"
+                    .to_string(),
+            );
+        }
+        (false, None) => {}
+    }
+    if let Some(raw) = env_var("IGGY_KAFKA_TLS_PRINCIPAL_MAPPING_RULES") {
+        let maps_identities = client_auth.is_enabled()
+            && listeners
+                .iter()
+                .any(|listener| listener.protocol.authenticates_by_certificate());
+        if !maps_identities {
+            return Err(
+                "IGGY_KAFKA_TLS_PRINCIPAL_MAPPING_RULES is set but no SSL listener verifies \
+                 client certificates; the rules apply to an SSL listener with \
+                 IGGY_KAFKA_TLS_CLIENT_AUTH requested or required, and on SASL_SSL the \
+                 principal comes from SASL"
+                    .to_string(),
+            );
+        }
+        let rules = raw
+            .parse()
+            .map_err(|e| format!("invalid IGGY_KAFKA_TLS_PRINCIPAL_MAPPING_RULES: {e}"))?;
+        tls = tls.with_principal_mapping(rules);
+    }
+    // Zero is valid: never re-read the files.
+    if let Some(raw) = env_var("IGGY_KAFKA_TLS_RELOAD_INTERVAL_SECS") {
+        let secs: u64 = raw
+            .parse()
+            .map_err(|e| format!("invalid IGGY_KAFKA_TLS_RELOAD_INTERVAL_SECS `{raw}`: {e}"))?;
+        tls = tls.with_reload_interval(Duration::from_secs(secs));
+    }
+    Ok(Some(tls))
+}
+
+/// Refuses `IGGY_KAFKA_IGGY_TLS_*` while nothing would read them.
+///
+/// The bridge and the SASL credential check are the two things that dial Iggy. With both off,
+/// accepting the switches lets an operator believe the link to Iggy is encrypted when there is no
+/// link, the same mistake `IggyTls::from_env` refuses to start for.
+fn reject_unread_iggy_tls(sasl_enabled: bool, bridge_enabled: bool) -> Result<(), String> {
+    if sasl_enabled || bridge_enabled {
         return Ok(());
     }
-    let set: Vec<&str> = IggyAuthenticator::KNOWN_ENV_VARS
+    let set: Vec<&str> = IggyTls::KNOWN_ENV_VARS
         .iter()
         .copied()
-        .filter(|var| var.starts_with("IGGY_KAFKA_IGGY_TLS_"))
         .filter(|var| std::env::var(var).is_ok())
         .collect();
     if set.is_empty() {
         return Ok(());
     }
     Err(format!(
-        "{} set but IGGY_KAFKA_SASL_ENABLED is not true; only the SASL credential check reads them, \
-         so nothing would be encrypted",
+        "{} set but neither IGGY_KAFKA_SASL_ENABLED nor IGGY_KAFKA_BRIDGE_ENABLED is true; only \
+         the SASL credential check and the bridge dial Iggy, so nothing would be encrypted",
         set.join(", ")
     ))
 }
@@ -337,10 +520,40 @@ async fn shutdown_signal() {
 mod tests {
     use serial_test::serial;
 
+    use iggy_gateway_kafka::listener::SecurityProtocol;
+    use iggy_gateway_kafka::tls::ClientAuth;
+
     use super::{
-        load_config, parse_positive, reject_iggy_tls_without_sasl, reject_unknown_kafka_env_vars,
+        KNOWN_KAFKA_ENV_VARS, load_config, parse_positive, reject_unknown_kafka_env_vars,
+        reject_unread_iggy_tls,
     };
 
+    /// Leaves every variable `load_config` reads unset, so one test's value cannot decide
+    /// another's result.
+    ///
+    /// # Safety
+    /// Only sound under `#[serial]`, see the note on the first test below.
+    fn clear_gateway_env() {
+        for key in KNOWN_KAFKA_ENV_VARS {
+            unsafe {
+                std::env::remove_var(key);
+            }
+        }
+    }
+
+    /// Runs `load_config` with exactly `vars` set, then clears them again.
+    fn load_with(vars: &[(&str, &str)]) -> Result<super::GatewayConfig, String> {
+        clear_gateway_env();
+        for (key, value) in vars {
+            unsafe {
+                std::env::set_var(key, value);
+            }
+        }
+        let loaded = load_config();
+        clear_gateway_env();
+        loaded
+    }
+
     /// Sequential (not two separate `#[test]` fns), and `#[serial]` (unkeyed - this binary's
     /// default group), shared with the instance-id and TLS tests below since all of them touch the
     /// process environment. The `#[serial]` tests in this module are the only ones compiled into
@@ -407,21 +620,9 @@ mod tests {
     #[test]
     #[serial]
     fn given_an_instance_id_env_var_when_loading_config_should_accept_and_parse_it() {
-        unsafe {
-            std::env::set_var("IGGY_KAFKA_INSTANCE_ID", "7");
-        }
-        let seven = load_config();
-        unsafe {
-            std::env::set_var("IGGY_KAFKA_INSTANCE_ID", "0");
-        }
-        let zero = load_config();
-        unsafe {
-            std::env::set_var("IGGY_KAFKA_INSTANCE_ID", "65536");
-        }
-        let overflow = load_config();
-        unsafe {
-            std::env::remove_var("IGGY_KAFKA_INSTANCE_ID");
-        }
+        let seven = load_with(&[("IGGY_KAFKA_INSTANCE_ID", "7")]);
+        let zero = load_with(&[("IGGY_KAFKA_INSTANCE_ID", "0")]);
+        let overflow = load_with(&[("IGGY_KAFKA_INSTANCE_ID", "65536")]);
 
         assert_eq!(seven.expect("instance id 7 must load").instance_id, 7);
         assert_eq!(zero.expect("instance id 0 must load").instance_id, 0);
@@ -439,13 +640,7 @@ mod tests {
     #[serial]
     fn given_an_unparsable_instance_id_when_loading_config_should_reject_and_name_it() {
         for raw in ["abc", "-1", "", " 7", "7.0"] {
-            unsafe {
-                std::env::set_var("IGGY_KAFKA_INSTANCE_ID", raw);
-            }
-            let loaded = load_config();
-            unsafe {
-                std::env::remove_var("IGGY_KAFKA_INSTANCE_ID");
-            }
+            let loaded = load_with(&[("IGGY_KAFKA_INSTANCE_ID", raw)]);
             let error = loaded.err().unwrap_or_else(|| {
                 panic!("instance id `{raw}` must be rejected, not silently defaulted to 0")
             });
@@ -463,20 +658,205 @@ mod tests {
     /// `#[serial]` for the same reason as the test above: it mutates process-wide env state.
     #[test]
     #[serial]
-    fn given_iggy_tls_without_sasl_should_refuse_to_start() {
+    fn given_iggy_tls_with_nothing_dialing_iggy_should_refuse_to_start() {
         unsafe {
             std::env::set_var("IGGY_KAFKA_IGGY_TLS_ENABLED", "true");
         }
-        let without_sasl = reject_iggy_tls_without_sasl(false);
-        let with_sasl = reject_iggy_tls_without_sasl(true);
+        let nothing_reads_it = reject_unread_iggy_tls(false, false);
+        let sasl_reads_it = reject_unread_iggy_tls(true, false);
+        let bridge_reads_it = reject_unread_iggy_tls(false, true);
         unsafe {
             std::env::remove_var("IGGY_KAFKA_IGGY_TLS_ENABLED");
         }
         assert!(
-            without_sasl.is_err(),
-            "nothing reads the TLS switch with SASL off, so accepting it hides that"
+            nothing_reads_it.is_err(),
+            "nothing reads the TLS switch with SASL and the bridge off, so accepting it hides that"
+        );
+        assert!(sasl_reads_it.is_ok());
+        assert!(bridge_reads_it.is_ok());
+    }
+
+    #[test]
+    #[serial]
+    fn given_the_single_listener_form_should_build_one_listener_from_its_variables() {
+        let plain = load_with(&[("IGGY_KAFKA_BIND_ADDR", "0.0.0.0:19093")])
+            .expect("a bind address alone is valid");
+        assert_eq!(plain.listeners.len(), 1);
+        assert_eq!(plain.listeners[0].protocol, SecurityProtocol::Plaintext);
+        assert_eq!(plain.listeners[0].bind_addr, "0.0.0.0:19093");
+        assert!(plain.tls.is_none());
+
+        let sasl = load_with(&[
+            ("IGGY_KAFKA_SASL_ENABLED", "true"),
+            ("IGGY_KAFKA_ADVERTISED_HOST", "kafka.example.com"),
+            ("IGGY_KAFKA_ADVERTISED_PORT", "9093"),
+        ])
+        .expect("the SASL switch selects the listener's protocol");
+        assert_eq!(sasl.listeners[0].protocol, SecurityProtocol::SaslPlaintext);
+        assert_eq!(
+            sasl.listeners[0].advertised_host.as_deref(),
+            Some("kafka.example.com")
+        );
+        assert_eq!(sasl.listeners[0].advertised_port, Some(9093));
+        assert!(sasl.sasl_enabled());
+
+        let unset = load_with(&[]).expect("an empty environment is valid");
+        assert_eq!(unset.listeners[0].bind_addr, "127.0.0.1:9093");
+    }
+
+    #[test]
+    #[serial]
+    fn given_both_listener_forms_should_refuse_the_sasl_switch_and_ignore_the_addresses() {
+        let error = load_with(&[
+            ("IGGY_KAFKA_LISTENERS", "PLAINTEXT://127.0.0.1:9093"),
+            ("IGGY_KAFKA_SASL_ENABLED", "true"),
+        ])
+        .unwrap_err();
+        assert!(error.contains("IGGY_KAFKA_LISTENERS"), "got: {error}");
+        assert!(error.contains("IGGY_KAFKA_SASL_ENABLED"), "got: {error}");
+
+        // The image bakes a bind address in, so a listener list has to win over it.
+        let config = load_with(&[
+            ("IGGY_KAFKA_LISTENERS", "SSL://127.0.0.1:9094"),
+            ("IGGY_KAFKA_BIND_ADDR", "0.0.0.0:9093"),
+            ("IGGY_KAFKA_TLS_CERT_FILE", "/etc/iggy/kafka.pem"),
+            ("IGGY_KAFKA_TLS_KEY_FILE", "/etc/iggy/kafka.key"),
+        ])
+        .expect("the list takes precedence over the baked bind address");
+        assert_eq!(config.listeners.len(), 1);
+        assert_eq!(config.listeners[0].bind_addr, "127.0.0.1:9094");
+
+        let error = load_with(&[(
+            "IGGY_KAFKA_ADVERTISED_LISTENERS",
+            "PLAINTEXT://kafka.example.com:9093",
+        )])
+        .unwrap_err();
+        assert!(
+            error.contains("IGGY_KAFKA_ADVERTISED_LISTENERS"),
+            "got: {error}"
+        );
+    }
+
+    #[test]
+    #[serial]
+    fn given_kafka_style_listeners_with_tls_should_require_and_carry_the_material() {
+        let missing = load_with(&[("IGGY_KAFKA_LISTENERS", "SSL://0.0.0.0:9094")]).unwrap_err();
+        assert!(
+            missing.contains("IGGY_KAFKA_TLS_CERT_FILE"),
+            "got: {missing}"
+        );
+
+        let config = load_with(&[
+            (
+                "IGGY_KAFKA_LISTENERS",
+                "PLAINTEXT://127.0.0.1:9093,SASL_SSL://0.0.0.0:9095",
+            ),
+            (
+                "IGGY_KAFKA_ADVERTISED_LISTENERS",
+                "SASL_SSL://kafka.example.com:9095",
+            ),
+            ("IGGY_KAFKA_TLS_CERT_FILE", "/etc/iggy/kafka.pem"),
+            ("IGGY_KAFKA_TLS_KEY_FILE", "/etc/iggy/kafka.key"),
+            ("IGGY_KAFKA_TLS_RELOAD_INTERVAL_SECS", "0"),
+        ])
+        .expect("a TLS listener with its material is valid");
+        assert_eq!(config.listeners.len(), 2);
+        assert_eq!(config.listeners[1].protocol, SecurityProtocol::SaslSsl);
+        assert_eq!(
+            config.listeners[1].advertised_host.as_deref(),
+            Some("kafka.example.com")
+        );
+        let tls = config.tls.as_ref().expect("material carried through");
+        assert_eq!(tls.cert_file.to_str(), Some("/etc/iggy/kafka.pem"));
+        assert_eq!(tls.client_auth, ClientAuth::None);
+        assert!(tls.reload_interval.is_zero());
+        assert!(config.sasl_enabled());
+        assert!(config.tls_enabled());
+        assert!(!config.maps_certificate_identities());
+    }
+
+    #[test]
+    #[serial]
+    fn given_tls_variables_without_a_tls_listener_should_refuse() {
+        let error = load_with(&[
+            ("IGGY_KAFKA_LISTENERS", "PLAINTEXT://127.0.0.1:9093"),
+            ("IGGY_KAFKA_TLS_CERT_FILE", "/etc/iggy/kafka.pem"),
+        ])
+        .unwrap_err();
+        assert!(error.contains("IGGY_KAFKA_TLS_CERT_FILE"), "got: {error}");
+        assert!(error.contains("no listener uses TLS"), "got: {error}");
+    }
+
+    #[test]
+    #[serial]
+    fn given_client_auth_settings_should_refuse_the_half_configured_combinations() {
+        let base = [
+            ("IGGY_KAFKA_LISTENERS", "SSL://0.0.0.0:9094"),
+            ("IGGY_KAFKA_TLS_CERT_FILE", "/etc/iggy/kafka.pem"),
+            ("IGGY_KAFKA_TLS_KEY_FILE", "/etc/iggy/kafka.key"),
+        ];
+        let with = |extra: &[(&str, &str)]| {
+            let mut vars = base.to_vec();
+            vars.extend_from_slice(extra);
+            load_with(&vars)
+        };
+
+        let no_ca = with(&[("IGGY_KAFKA_TLS_CLIENT_AUTH", "required")]).unwrap_err();
+        assert!(
+            no_ca.contains("IGGY_KAFKA_TLS_CLIENT_CA_FILE"),
+            "got: {no_ca}"
+        );
+
+        let no_auth = with(&[("IGGY_KAFKA_TLS_CLIENT_CA_FILE", "/etc/iggy/ca.pem")]).unwrap_err();
+        assert!(
+            no_auth.contains("IGGY_KAFKA_TLS_CLIENT_AUTH"),
+            "got: {no_auth}"
+        );
+
+        let rules_without_auth =
+            with(&[("IGGY_KAFKA_TLS_PRINCIPAL_MAPPING_RULES", "DEFAULT")]).unwrap_err();
+        assert!(
+            rules_without_auth.contains("IGGY_KAFKA_TLS_PRINCIPAL_MAPPING_RULES"),
+            "got: {rules_without_auth}"
+        );
+
+        let bad_mode = with(&[
+            ("IGGY_KAFKA_TLS_CLIENT_AUTH", "Required"),
+            ("IGGY_KAFKA_TLS_CLIENT_CA_FILE", "/etc/iggy/ca.pem"),
+        ])
+        .unwrap_err();
+        assert!(
+            bad_mode.contains("IGGY_KAFKA_TLS_CLIENT_AUTH"),
+            "got: {bad_mode}"
+        );
+
+        let bad_rules = with(&[
+            ("IGGY_KAFKA_TLS_CLIENT_AUTH", "required"),
+            ("IGGY_KAFKA_TLS_CLIENT_CA_FILE", "/etc/iggy/ca.pem"),
+            ("IGGY_KAFKA_TLS_PRINCIPAL_MAPPING_RULES", "RULE:broken"),
+        ])
+        .unwrap_err();
+        assert!(
+            bad_rules.contains("IGGY_KAFKA_TLS_PRINCIPAL_MAPPING_RULES"),
+            "got: {bad_rules}"
+        );
+
+        let complete = with(&[
+            ("IGGY_KAFKA_TLS_CLIENT_AUTH", "required"),
+            ("IGGY_KAFKA_TLS_CLIENT_CA_FILE", "/etc/iggy/ca.pem"),
+            (
+                "IGGY_KAFKA_TLS_PRINCIPAL_MAPPING_RULES",
+                "RULE:^CN=([^,]+).*$/$1/L",
+            ),
+        ])
+        .expect("a complete mTLS configuration is valid");
+        let tls = complete.tls.as_ref().expect("material carried through");
+        assert_eq!(tls.client_auth, ClientAuth::Required);
+        assert_eq!(
+            tls.principal_mapping.map("CN=Alice,O=Example").as_deref(),
+            Some("alice")
         );
-        assert!(with_sasl.is_ok());
+        assert!(complete.maps_certificate_identities());
     }
 
     #[test]
diff --git a/gateways/kafka/src/protocol/api.rs b/gateways/kafka/src/protocol/api.rs
index 9539773b8..ef4f169cd 100644
--- a/gateways/kafka/src/protocol/api.rs
+++ b/gateways/kafka/src/protocol/api.rs
@@ -37,6 +37,7 @@ use crate::protocol::acl::{
 use crate::protocol::bounds_guard::{
     validate_describe_acls_shape, validate_sasl_authenticate_shape, validate_sasl_handshake_shape,
 };
+use crate::protocol::handlers::api_versions::Advertisement;
 use crate::protocol::handlers::init_producer_id::ProducerIdAllocator;
 use crate::protocol::handlers::{
     alter_configs, api_versions, create_topics, decode_guarded, delete_topics, describe_configs,
@@ -322,12 +323,8 @@ pub fn supported_api_ranges() -> &'static [ApiVersionRange] {
 /// `IggyClient`, so Kafka connections serialize behind whichever of those calls is in flight. The
 /// `Arc` does not change that. See the README's "Concurrency ceiling".
 pub struct GatewayState {
-    pub broker: BrokerAdvertise,
     pub bridge: Option<Arc<IggyBridge>>,
     pub max_frame_size: usize,
-    /// Whether `SaslHandshake` and `SaslAuthenticate` are advertised and routed. Kept on the
-    /// shared state so `ApiVersions` can answer without a widened handler signature.
-    pub sasl_enabled: bool,
     /// Shared across every connection this gateway serves: a producer id has to be unique for
     /// the process, not for the connection that asked for it.
     pub producer_ids: ProducerIdAllocator,
@@ -350,18 +347,14 @@ const PRODUCE_SLOTS: usize = 4;
 impl GatewayState {
     #[must_use]
     pub fn new(
-        broker: BrokerAdvertise,
         bridge: Option<Arc<IggyBridge>>,
         max_frame_size: usize,
-        sasl_enabled: bool,
         instance_id: u16,
         groups: GroupCoordinator,
     ) -> Self {
         Self {
-            broker,
             bridge,
             max_frame_size,
-            sasl_enabled,
             producer_ids: ProducerIdAllocator::new(instance_id),
             produce_slots: Semaphore::const_new(PRODUCE_SLOTS),
             groups,
@@ -374,12 +367,10 @@ impl GatewayState {
     ///
     /// The coordinator is real but fresh, so two calls never share group state.
     #[must_use]
-    pub fn stub(broker: BrokerAdvertise, max_frame_size: usize) -> Self {
+    pub fn stub(max_frame_size: usize) -> Self {
         Self::new(
-            broker,
             None,
             max_frame_size,
-            false,
             0,
             GroupCoordinator::new(GroupCoordinatorConfig::default(), CancellationToken::new()),
         )
@@ -391,8 +382,20 @@ impl GatewayState {
 /// Fetch keeps its -1 holds and the offsets it cannot place here. One consumer's stuck offset then
 /// neither skips another consumer's read of it nor replaces the hold of a consumer stuck elsewhere
 /// in the partition, and one consumer's wait for an offset never spends another's grace.
+///
+/// The listener the connection arrived through lives here too, because a gateway with several
+/// listeners answers Metadata and `ApiVersions` differently on each: a client is pointed back at
+/// the port it used, and the SASL keys are advertised only where the exchange is run.
 #[derive(Default)]
 pub struct ConnectionState {
+    /// The broker address this connection's listener advertises.
+    pub broker: BrokerAdvertise,
+    /// Whether `SaslHandshake` and `SaslAuthenticate` are advertised and routed on this
+    /// connection's listener.
+    pub sasl_enabled: bool,
+    /// Whether `DescribeAcls` is advertised and answered: the listener names a principal, by
+    /// SASL or by a verified client certificate.
+    pub acls_enabled: bool,
     /// Partitions that answered -1 to this connection's Fetches, per Kafka topic.
     pub(crate) stuck_offsets: Mutex<fetch::StuckOffsets>,
     /// Offsets this connection's Fetches cannot place, per Kafka topic.
@@ -403,6 +406,28 @@ pub struct ConnectionState {
 }
 
 impl ConnectionState {
+    /// State for a connection accepted on the listener that advertises `broker`.
+    ///
+    /// `acls_enabled` is at least `sasl_enabled`: a SASL listener always names a principal.
+    #[must_use]
+    pub fn for_listener(broker: BrokerAdvertise, sasl_enabled: bool, acls_enabled: bool) -> Self {
+        Self {
+            broker,
+            sasl_enabled,
+            acls_enabled: acls_enabled || sasl_enabled,
+            ..Self::default()
+        }
+    }
+
+    /// What `ApiVersions` tells this connection about the listener-dependent keys.
+    #[must_use]
+    pub const fn advertisement(&self) -> Advertisement {
+        Advertisement {
+            sasl: self.sasl_enabled,
+            acls: self.acls_enabled,
+        }
+    }
+
     pub(crate) fn note_heartbeat(&self, member: GroupMember) {
         *self
             .heartbeat_member
@@ -431,8 +456,9 @@ pub async fn handle_request(
     body: Bytes,
     broker: &BrokerAdvertise,
 ) -> HandleOutcome {
-    let state = GatewayState::stub(broker.clone(), DEFAULT_MAX_FRAME_SIZE);
-    handle_request_bounded(&state, api_key, api_version, body).await
+    let state = GatewayState::stub(DEFAULT_MAX_FRAME_SIZE);
+    let connection = ConnectionState::for_listener(broker.clone(), false, false);
+    handle_connection_request(&state, &connection, None, api_key, api_version, body).await
 }
 
 /// Same as [`handle_request`], but rejects a request whose declared array/string lengths project
@@ -530,16 +556,20 @@ static SASL_ADVERTISED_RANGES: &[ApiVersionRange] = &[
         min_version: 0,
         max_version: 2,
     },
-    // Grouped with the SASL keys rather than with `SUPPORTED_RANGES` because it answers about the
-    // authenticated principal. With SASL off there is no principal, so there is nothing it could
-    // truthfully describe, and advertising it would invite a question with no answer.
-    ApiVersionRange {
-        api_key: API_KEY_DESCRIBE_ACLS,
-        min_version: 1,
-        max_version: 3,
-    },
 ];
 
+/// Advertised only on a listener that names a principal, and absent from [`SUPPORTED_RANGES`]
+/// for the same reason the SASL keys are: it answers about the authenticated principal, which
+/// only the connection knows. On a plaintext listener with SASL off there is none, so there is
+/// nothing it could truthfully describe, and advertising it would invite a question with no
+/// answer. An `SSL` listener that verifies client certificates names one too, so it is advertised
+/// there without the SASL keys.
+static ACL_ADVERTISED_RANGES: &[ApiVersionRange] = &[ApiVersionRange {
+    api_key: API_KEY_DESCRIBE_ACLS,
+    min_version: 1,
+    max_version: 3,
+}];
+
 /// Sent with every `SASL_AUTHENTICATION_FAILED`, whatever the real cause.
 ///
 /// Iggy's own login runs a dummy hash for an unknown user precisely so that "no such user" and
@@ -679,12 +709,18 @@ fn finish_sasl(encoded: Result<Bytes>, close: bool, api_name: &str) -> HandleOut
     }
 }
 
-/// The SASL keys, advertised only while the feature is on.
+/// The SASL keys, advertised only on a listener that runs the exchange.
 #[must_use]
 pub fn sasl_advertised_ranges() -> &'static [ApiVersionRange] {
     SASL_ADVERTISED_RANGES
 }
 
+/// The ACL keys, advertised only on a listener that names a principal.
+#[must_use]
+pub fn acl_advertised_ranges() -> &'static [ApiVersionRange] {
+    ACL_ADVERTISED_RANGES
+}
+
 /// Builds a well-formed error response for `api_key`, shaped for `api_version`.
 ///
 /// Used when a request is refused for a reason that belongs to the connection rather than the
@@ -701,7 +737,7 @@ pub fn encode_error_for_key(
     api_key: i16,
     api_version: i16,
     error_code: i16,
-    sasl_enabled: bool,
+    advertisement: Advertisement,
 ) -> HandleOutcome {
     // The firewall applies here too, and it has to be checked explicitly. `kafka_protocol`'s
     // encoders accept a wider version range than `SUPPORTED_RANGES` does (Fetch to 18 against a
@@ -719,11 +755,11 @@ pub fn encode_error_for_key(
             describe_configs::encode_error_response(api_version, error_code)
         }
         API_KEY_ALTER_CONFIGS => alter_configs::encode_error_response(api_version, error_code),
-        // Carries the live SASL setting, not a hardcoded `false`: answering an illegal-state
-        // ApiVersions with a SASL-less key set contradicts the advertisement sent one frame
-        // earlier on the same connection.
+        // Carries the listener's live advertisement, not a hardcoded `NONE`: answering an
+        // illegal-state ApiVersions with a SASL-less key set contradicts the advertisement sent
+        // one frame earlier on the same connection.
         API_KEY_API_VERSIONS => {
-            api_versions::encode_response(api_version, error_code, sasl_enabled)
+            api_versions::encode_response(api_version, error_code, advertisement)
         }
         _ => return HandleOutcome::Close,
     };
diff --git a/gateways/kafka/src/protocol/handlers/api_versions.rs b/gateways/kafka/src/protocol/handlers/api_versions.rs
index 4c3974665..2ba404394 100644
--- a/gateways/kafka/src/protocol/handlers/api_versions.rs
+++ b/gateways/kafka/src/protocol/handlers/api_versions.rs
@@ -23,8 +23,8 @@ use kafka_protocol::messages::{ApiVersionsRequest, ApiVersionsResponse};
 
 use crate::error::Result;
 use crate::protocol::api::{
-    API_KEY_API_VERSIONS, ApiVersionRange, ERROR_INVALID_REQUEST, ERROR_NONE,
-    ERROR_UNSUPPORTED_VERSION, GatewayState, HandleOutcome, advertised_min_version,
+    API_KEY_API_VERSIONS, ApiVersionRange, ConnectionState, ERROR_INVALID_REQUEST, ERROR_NONE,
+    ERROR_UNSUPPORTED_VERSION, HandleOutcome, acl_advertised_ranges, advertised_min_version,
     is_supported_version, sasl_advertised_ranges, supported_api_ranges,
 };
 use crate::protocol::bounds_guard::validate_api_versions_shape;
@@ -36,21 +36,44 @@ pub const RANGE: ApiVersionRange = ApiVersionRange {
     max_version: 3,
 };
 
+/// Which of the listener-dependent keys one connection is told about.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub struct Advertisement {
+    /// `SaslHandshake` and `SaslAuthenticate`.
+    pub sasl: bool,
+    /// `DescribeAcls`.
+    pub acls: bool,
+}
+
+impl Advertisement {
+    /// Nothing listener-dependent: a plaintext listener with SASL off.
+    pub const NONE: Self = Self {
+        sasl: false,
+        acls: false,
+    };
+
+    /// Both: a listener that runs SASL always names a principal.
+    pub const SASL: Self = Self {
+        sasl: true,
+        acls: true,
+    };
+}
+
 #[expect(
     clippy::unused_async,
     reason = "the shared handler signature, kept until a handler awaits the bridge"
 )]
-pub async fn handle(state: &GatewayState, api_version: i16, body: Bytes) -> HandleOutcome {
+pub async fn handle(connection: &ConnectionState, api_version: i16, body: Bytes) -> HandleOutcome {
     if !is_supported_version(API_KEY_API_VERSIONS, api_version) {
         // KIP-511: reply with v0 when the requested version is not understood.
         return respond_or_close(
-            encode_response(0, ERROR_UNSUPPORTED_VERSION, state.sasl_enabled),
+            encode_response(0, ERROR_UNSUPPORTED_VERSION, connection.advertisement()),
             "ApiVersions",
         );
     }
     match decode_guarded::<ApiVersionsRequest>(api_version, body, validate_api_versions_shape) {
         Ok(_) => respond_or_close(
-            encode_response(api_version, ERROR_NONE, state.sasl_enabled),
+            encode_response(api_version, ERROR_NONE, connection.advertisement()),
             "ApiVersions",
         ),
         Err(error) => {
@@ -58,7 +81,11 @@ pub async fn handle(state: &GatewayState, api_version: i16, body: Bytes) -> Hand
             // note on the Produce decode-failure arm).
             tracing::debug!(%error, "failed to decode ApiVersions request");
             respond_or_close(
-                encode_response(api_version, ERROR_INVALID_REQUEST, state.sasl_enabled),
+                encode_response(
+                    api_version,
+                    ERROR_INVALID_REQUEST,
+                    connection.advertisement(),
+                ),
                 "ApiVersions",
             )
         }
@@ -71,18 +98,32 @@ pub async fn handle(state: &GatewayState, api_version: i16, body: Bytes) -> Hand
 /// # Errors
 ///
 /// Returns an error when `kafka_protocol` cannot encode the response at `api_version`.
-pub fn encode_response(api_version: i16, error_code: i16, sasl_enabled: bool) -> Result<Bytes> {
-    // The SASL keys are advertised only while the feature is on, and are deliberately kept out of
-    // `SUPPORTED_RANGES` so dispatch never serves them. With SASL off the state machine still
-    // answers them with `ILLEGAL_SASL_STATE` and keeps the connection open.
-    let sasl = if sasl_enabled {
+pub fn encode_response(
+    api_version: i16,
+    error_code: i16,
+    advertisement: Advertisement,
+) -> Result<Bytes> {
+    // The SASL and ACL keys are advertised only on a listener that runs the exchange or names a
+    // principal, and are deliberately kept out of `SUPPORTED_RANGES` so dispatch never serves
+    // them. Elsewhere the state machine still answers them with `ILLEGAL_SASL_STATE` and keeps
+    // the connection open.
+    let sasl = if advertisement.sasl {
         sasl_advertised_ranges()
     } else {
         &[][..]
     };
+    let acls = if advertisement.acls {
+        acl_advertised_ranges()
+    } else {
+        &[][..]
+    };
     // Ascending by api_key, as every real broker emits it. Chaining the SASL rows onto the end
     // would put key 17 after key 19, which no broker does and some clients do not expect.
-    let mut rows: Vec<&ApiVersionRange> = supported_api_ranges().iter().chain(sasl).collect();
+    let mut rows: Vec<&ApiVersionRange> = supported_api_ranges()
+        .iter()
+        .chain(sasl)
+        .chain(acls)
+        .collect();
     rows.sort_unstable_by_key(|r| r.api_key);
     let api_keys = rows
         .into_iter()
diff --git a/gateways/kafka/src/protocol/handlers/find_coordinator.rs b/gateways/kafka/src/protocol/handlers/find_coordinator.rs
index fe5f39f2d..21ee772d5 100644
--- a/gateways/kafka/src/protocol/handlers/find_coordinator.rs
+++ b/gateways/kafka/src/protocol/handlers/find_coordinator.rs
@@ -28,9 +28,9 @@ use kafka_protocol::protocol::StrBytes;
 
 use crate::error::Result;
 use crate::protocol::api::{
-    API_KEY_FIND_COORDINATOR, ApiVersionRange, BrokerAdvertise, ERROR_INVALID_REQUEST, ERROR_NONE,
-    ERROR_TRANSACTIONAL_ID_AUTHORIZATION_FAILED, ERROR_UNSUPPORTED_VERSION, GatewayState,
-    HandleOutcome, is_supported_version,
+    API_KEY_FIND_COORDINATOR, ApiVersionRange, BrokerAdvertise, ConnectionState,
+    ERROR_INVALID_REQUEST, ERROR_NONE, ERROR_TRANSACTIONAL_ID_AUTHORIZATION_FAILED,
+    ERROR_UNSUPPORTED_VERSION, GatewayState, HandleOutcome, is_supported_version,
 };
 use crate::protocol::bounds_guard::validate_find_coordinator_shape;
 use crate::protocol::handlers::{
@@ -57,7 +57,12 @@ const UNSUPPORTED_KEY_TYPE_MESSAGE: &str = "only group coordination is supported
     clippy::unused_async,
     reason = "the shared handler signature, kept until a handler awaits the bridge"
 )]
-pub async fn handle(state: &GatewayState, api_version: i16, body: Bytes) -> HandleOutcome {
+pub async fn handle(
+    state: &GatewayState,
+    connection: &ConnectionState,
+    api_version: i16,
+    body: Bytes,
+) -> HandleOutcome {
     if !is_supported_version(API_KEY_FIND_COORDINATOR, api_version) {
         return unsupported_version_response(API_KEY_FIND_COORDINATOR, api_version, |version| {
             encode_error_response(version, ERROR_UNSUPPORTED_VERSION)
@@ -67,7 +72,7 @@ pub async fn handle(state: &GatewayState, api_version: i16, body: Bytes) -> Hand
         validate_find_coordinator_shape(version, body, state.max_frame_size)
     }) {
         Ok(request) => respond_or_close(
-            encode_response(api_version, &request, &state.broker),
+            encode_response(api_version, &request, &connection.broker),
             "FindCoordinator",
         ),
         Err(error) => {
diff --git a/gateways/kafka/src/protocol/handlers/metadata.rs b/gateways/kafka/src/protocol/handlers/metadata.rs
index 0b1742cd8..fcb6fad33 100644
--- a/gateways/kafka/src/protocol/handlers/metadata.rs
+++ b/gateways/kafka/src/protocol/handlers/metadata.rs
@@ -27,9 +27,9 @@ use kafka_protocol::protocol::{Encodable, StrBytes};
 use crate::bridge::IggyBridge;
 use crate::error::{KafkaProtocolError, Result};
 use crate::protocol::api::{
-    API_KEY_METADATA, ApiVersionRange, BrokerAdvertise, ERROR_NONE, ERROR_REQUEST_TIMED_OUT,
-    ERROR_UNKNOWN_TOPIC_OR_PARTITION, GatewayState, HandleOutcome, REQUEST_DEADLINE,
-    is_supported_version, supported_max_version,
+    API_KEY_METADATA, ApiVersionRange, BrokerAdvertise, ConnectionState, ERROR_NONE,
+    ERROR_REQUEST_TIMED_OUT, ERROR_UNKNOWN_TOPIC_OR_PARTITION, GatewayState, HandleOutcome,
+    REQUEST_DEADLINE, is_supported_version, supported_max_version,
 };
 use crate::protocol::bounds_guard::validate_metadata_shape;
 use crate::protocol::dedup::dedup_first_seen;
@@ -47,7 +47,12 @@ pub const RANGE: ApiVersionRange = ApiVersionRange {
 /// threshold - tune with a real benchmark if it proves too high or too low in practice.
 const BLOCKING_ENCODE_PARTITION_THRESHOLD: u32 = 20_000;
 
-pub async fn handle(state: &GatewayState, api_version: i16, body: Bytes) -> HandleOutcome {
+pub async fn handle(
+    state: &GatewayState,
+    connection: &ConnectionState,
+    api_version: i16,
+    body: Bytes,
+) -> HandleOutcome {
     if !is_supported_version(API_KEY_METADATA, api_version) {
         // Clamping the response to the supported max leaves a body the client parses at its own
         // (unsupported) version, so UNSUPPORTED_VERSION never survives. Clients that skip
@@ -63,7 +68,7 @@ pub async fn handle(state: &GatewayState, api_version: i16, body: Bytes) -> Hand
     let Some(bridge) = &state.bridge else {
         return match decode_topics(api_version, body, state.max_frame_size) {
             Ok(topics) => respond_or_close(
-                encode_response(api_version, &topics, &state.broker, ERROR_NONE),
+                encode_response(api_version, &topics, &connection.broker, ERROR_NONE),
                 "Metadata",
             ),
             Err(error) => {
@@ -161,7 +166,7 @@ pub async fn handle(state: &GatewayState, api_version: i16, body: Bytes) -> Hand
         // this shard for the duration. `spawn_blocking` moves that cost off the shard's own task
         // so ordinary requests keep their latency regardless of how large one all-topics response
         // gets.
-        let broker = state.broker.clone();
+        let broker = connection.broker.clone();
         tokio::task::spawn_blocking(move || encode_real_response(api_version, &results, &broker))
             .await
             .unwrap_or_else(|join_error| {
@@ -169,7 +174,7 @@ pub async fn handle(state: &GatewayState, api_version: i16, body: Bytes) -> Hand
                 Err(KafkaProtocolError::Malformed(join_error.to_string()))
             })
     } else {
-        encode_real_response(api_version, &results, &state.broker)
+        encode_real_response(api_version, &results, &connection.broker)
     };
     respond_or_close(encoded, "Metadata")
 }
diff --git a/gateways/kafka/src/protocol/handlers/mod.rs b/gateways/kafka/src/protocol/handlers/mod.rs
index 2e2282229..3d73d7a56 100644
--- a/gateways/kafka/src/protocol/handlers/mod.rs
+++ b/gateways/kafka/src/protocol/handlers/mod.rs
@@ -114,15 +114,17 @@ pub async fn dispatch(
         API_KEY_PRODUCE => produce::handle(state, api_version, body).await,
         API_KEY_FETCH => fetch::handle(state, connection, api_version, body).await,
         API_KEY_LIST_OFFSETS => list_offsets::handle(state, api_version, body).await,
-        API_KEY_METADATA => metadata::handle(state, api_version, body).await,
+        API_KEY_METADATA => metadata::handle(state, connection, api_version, body).await,
         API_KEY_OFFSET_COMMIT => offset_commit::handle(state, connection, api_version, body).await,
         API_KEY_OFFSET_FETCH => offset_fetch::handle(state, connection, api_version, body).await,
-        API_KEY_API_VERSIONS => api_versions::handle(state, api_version, body).await,
+        API_KEY_API_VERSIONS => api_versions::handle(connection, api_version, body).await,
         API_KEY_CREATE_TOPICS => create_topics::handle(state, api_version, body).await,
         API_KEY_DELETE_TOPICS => delete_topics::handle(state, principal, api_version, body).await,
         API_KEY_DESCRIBE_CONFIGS => describe_configs::handle(state, api_version, body).await,
         API_KEY_ALTER_CONFIGS => alter_configs::handle(state, principal, api_version, body).await,
-        API_KEY_FIND_COORDINATOR => find_coordinator::handle(state, api_version, body).await,
+        API_KEY_FIND_COORDINATOR => {
+            find_coordinator::handle(state, connection, api_version, body).await
+        }
         API_KEY_JOIN_GROUP => join_group::handle(state, api_version, body).await,
         API_KEY_HEARTBEAT => heartbeat::handle(state, connection, api_version, body).await,
         API_KEY_LEAVE_GROUP => leave_group::handle(state, api_version, body).await,
diff --git a/gateways/kafka/src/protocol/handlers/offset_commit.rs b/gateways/kafka/src/protocol/handlers/offset_commit.rs
index 3a257313b..c21d36952 100644
--- a/gateways/kafka/src/protocol/handlers/offset_commit.rs
+++ b/gateways/kafka/src/protocol/handlers/offset_commit.rs
@@ -201,7 +201,7 @@ mod tests {
 
     use super::*;
     use crate::bridge::BridgeError;
-    use crate::protocol::api::{BrokerAdvertise, ERROR_UNKNOWN_MEMBER_ID};
+    use crate::protocol::api::ERROR_UNKNOWN_MEMBER_ID;
 
     fn request(generation_id: i32, member_id: &'static str) -> OffsetCommitRequest {
         OffsetCommitRequest::default()
@@ -229,7 +229,7 @@ mod tests {
     }
 
     async fn codes(version: i16, request: &OffsetCommitRequest) -> Vec<(String, i32, i16)> {
-        let state = GatewayState::stub(BrokerAdvertise::default(), 8 * 1024 * 1024);
+        let state = GatewayState::stub(8 * 1024 * 1024);
         let connection = ConnectionState::default();
         let mut response = handle(&state, &connection, version, body(version, request))
             .await
@@ -307,7 +307,7 @@ mod tests {
     /// may go back.
     #[tokio::test]
     async fn given_an_unreadable_request_should_close_rather_than_answer() {
-        let state = GatewayState::stub(BrokerAdvertise::default(), 8 * 1024 * 1024);
+        let state = GatewayState::stub(8 * 1024 * 1024);
         let connection = ConnectionState::default();
 
         let truncated = body(9, &request(-1, "")).slice(..5);
diff --git a/gateways/kafka/src/protocol/handlers/offset_fetch.rs b/gateways/kafka/src/protocol/handlers/offset_fetch.rs
index 4b91ece8c..2d6493298 100644
--- a/gateways/kafka/src/protocol/handlers/offset_fetch.rs
+++ b/gateways/kafka/src/protocol/handlers/offset_fetch.rs
@@ -449,7 +449,6 @@ mod tests {
     use kafka_protocol::protocol::{Decodable, Encodable};
 
     use super::*;
-    use crate::protocol::api::BrokerAdvertise;
 
     fn topic(name: &'static str) -> TopicName {
         TopicName(StrBytes::from_static_str(name))
@@ -466,7 +465,7 @@ mod tests {
     }
 
     async fn fetch(version: i16, request: &OffsetFetchRequest) -> OffsetFetchResponse {
-        let state = GatewayState::stub(BrokerAdvertise::default(), 8 * 1024 * 1024);
+        let state = GatewayState::stub(8 * 1024 * 1024);
         let connection = ConnectionState::default();
         let mut body = BytesMut::new();
         request.encode(&mut body, version).unwrap();
@@ -548,7 +547,7 @@ mod tests {
 
     #[tokio::test]
     async fn given_an_unreadable_request_should_close_rather_than_answer() {
-        let state = GatewayState::stub(BrokerAdvertise::default(), 8 * 1024 * 1024);
+        let state = GatewayState::stub(8 * 1024 * 1024);
         let connection = ConnectionState::default();
         let mut body = BytesMut::new();
         single_group("g").encode(&mut body, 6).unwrap();
diff --git a/gateways/kafka/src/server.rs b/gateways/kafka/src/server.rs
index 70ee83e2e..6000a8d54 100644
--- a/gateways/kafka/src/server.rs
+++ b/gateways/kafka/src/server.rs
@@ -15,6 +15,7 @@
 // specific language governing permissions and limitations
 // under the License.
 
+use std::io;
 use std::net::SocketAddr;
 use std::sync::Arc;
 use std::time::Duration;
@@ -22,9 +23,10 @@ use std::time::Duration;
 use bytes::{Buf, BufMut, Bytes, BytesMut};
 use kafka_protocol::messages::RequestHeader;
 use kafka_protocol::protocol::Decodable;
-use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
 use tokio::net::{TcpListener, TcpStream};
 use tokio::sync::{Semaphore, broadcast};
+use tokio::task::JoinSet;
 use tokio::time::{timeout, timeout_at};
 use tokio_util::sync::CancellationToken;
 use tokio_util::task::TaskTracker;
@@ -33,10 +35,14 @@ use tracing_appender::non_blocking::WorkerGuard;
 use tracing_subscriber::EnvFilter;
 use tracing_subscriber::filter::LevelFilter;
 
-use crate::auth::{AuthError, AuthenticatedPrincipal, FailedLoginThrottle, SaslAuthenticator};
+use crate::auth::{
+    AuthError, AuthenticatedPrincipal, FailedLoginThrottle, PrincipalResolver, SaslAuthenticator,
+};
 use crate::bridge::IggyBridge;
 use crate::error::{KafkaProtocolError, Result};
 use crate::group::{GroupCoordinator, GroupCoordinatorConfig};
+use crate::listener::{ListenerConfig, SecurityProtocol};
+use crate::protocol::acl::PrincipalPermissions;
 use crate::protocol::api::{
     API_KEY_DESCRIBE_ACLS, API_KEY_SASL_AUTHENTICATE, API_KEY_SASL_HANDSHAKE, BrokerAdvertise,
     ConnectionState, DEFAULT_KAFKA_PORT, ERROR_ILLEGAL_SASL_STATE, ERROR_INVALID_REQUEST,
@@ -46,16 +52,20 @@ use crate::protocol::api::{
     decode_sasl_mechanism, describe_acls_outcome, encode_error_for_key, handle_connection_request,
     respond_describe_acls_error, sasl_authenticate_outcome, sasl_handshake_outcome,
 };
+use crate::protocol::handlers::api_versions::Advertisement;
 use crate::protocol::header::{request_header_version, response_header_version};
 use crate::protocol::sasl::{
     PlainCredentials, SASL_AUTHENTICATE_MAX_VERSION, SASL_HANDSHAKE_VERSION, SaslAction, SaslState,
     parse_plain,
 };
-use std::io;
+use crate::tls::{TlsConfig, TlsState};
 
 const READ_CHUNK: usize = 65536;
 const GATEWAY_LOG_TARGET: &str = env!("CARGO_CRATE_NAME");
 
+/// Kafka's name for a client that proved no identity, as `DescribeAcls` renders it.
+const ANONYMOUS_PRINCIPAL: &str = "ANONYMOUS";
+
 /// Builds the log filter, forcing the Iggy SDK quiet unless the operator asked otherwise.
 ///
 /// This is a credential-disclosure control, not noise reduction. The SDK logs the username it
@@ -99,12 +109,13 @@ fn sdk_quieted_filter(rust_log: Option<&str>) -> String {
 
 #[derive(Debug, Clone)]
 pub struct GatewayConfig {
-    pub bind_addr: String,
-    /// Hostname or IP advertised in Metadata (`IGGY_KAFKA_ADVERTISED_HOST`). Required when
-    /// `bind_addr` uses a wildcard address (`0.0.0.0` / `::`).
-    pub advertised_host: Option<String>,
-    /// Port advertised in Metadata (`IGGY_KAFKA_ADVERTISED_PORT`). Defaults to the bind port.
-    pub advertised_port: Option<u16>,
+    /// The listeners, one per security protocol (`IGGY_KAFKA_LISTENERS`, or the single-listener
+    /// `IGGY_KAFKA_BIND_ADDR` form). Which of them run SASL and which run TLS is what the
+    /// protocol says; `tls` holds the material the TLS ones share.
+    pub listeners: Vec<ListenerConfig>,
+    /// Certificate, key and client-authentication policy for every `SSL` and `SASL_SSL` listener.
+    /// Required exactly when one of those exists.
+    pub tls: Option<TlsConfig>,
     pub max_frame_size: usize,
     /// Maximum concurrent connections accepted before new ones are rejected.
     pub max_connections: usize,
@@ -127,18 +138,8 @@ pub struct GatewayConfig {
     /// `InitProducerId`, which Kafka requires to be cluster-unique; two gateways left on the
     /// same number hand out the same ids.
     pub instance_id: u16,
-    /// Require SASL authentication before serving any other API.
-    ///
-    /// Off by default, and switching it on is a breaking change for every client already talking
-    /// to this gateway: the two SASL keys only appear in the `ApiVersions` advertisement while it
-    /// is on, and unauthenticated clients stop being served.
-    ///
-    /// While it is off the keys are still answered, with `ILLEGAL_SASL_STATE` and an empty
-    /// mechanism list, because a well-formed response exists for them unlike a genuinely unknown
-    /// key. They are kept out of the advertisement so nothing is invited into an exchange that
-    /// cannot finish.
-    pub sasl_enabled: bool,
-    /// How long an unauthenticated connection may sit between frames.
+    /// How long an unauthenticated connection may sit between frames, and how long a TLS
+    /// handshake or a certificate identity lookup may take.
     ///
     /// Separate from `idle_timeout` because that one is sized for a well-behaved idle client (10
     /// minutes, matching a real broker) and applies to connections that have proven who they are.
@@ -166,9 +167,11 @@ pub struct GatewayConfig {
 impl Default for GatewayConfig {
     fn default() -> Self {
         Self {
-            bind_addr: format!("127.0.0.1:{DEFAULT_KAFKA_PORT}"),
-            advertised_host: None,
-            advertised_port: None,
+            listeners: vec![ListenerConfig::new(
+                SecurityProtocol::Plaintext,
+                format!("127.0.0.1:{DEFAULT_KAFKA_PORT}"),
+            )],
+            tls: None,
             max_frame_size: 8 * 1024 * 1024,
             max_connections: 1024,
             idle_timeout: Duration::from_mins(10),
@@ -177,53 +180,49 @@ impl Default for GatewayConfig {
             shutdown_drain_timeout: Duration::from_secs(25),
             group: GroupCoordinatorConfig::default(),
             instance_id: 0,
-            sasl_enabled: false,
             pre_auth_timeout: Duration::from_secs(15),
             max_concurrent_authentications: 4,
         }
     }
 }
 
-impl BrokerAdvertise {
-    /// Resolve the broker endpoint advertised in Metadata.
+impl GatewayConfig {
+    /// Whether any listener runs the SASL exchange.
     ///
-    /// `local_addr` is the address the listener is actually bound to (from `listener.local_addr()`).
+    /// Switching a listener to SASL is a breaking change for every client already talking to it:
+    /// the two SASL keys only appear in that listener's `ApiVersions` advertisement while it is
+    /// on, and unauthenticated clients stop being served there.
     ///
-    /// # Errors
-    ///
-    /// Returns `InvalidConfig` when `advertised_host` is empty or the listener binds to a wildcard
-    /// without an explicit advertised host.
-    pub fn from_server_config(config: &GatewayConfig, local_addr: SocketAddr) -> Result<Self> {
-        let port = config
-            .advertised_port
-            .map_or_else(|| i32::from(local_addr.port()), i32::from);
-
-        let host = if let Some(ref advertised) = config.advertised_host {
-            let trimmed = advertised.trim();
-            if trimmed.is_empty() {
-                return Err(KafkaProtocolError::InvalidConfig(
-                    "IGGY_KAFKA_ADVERTISED_HOST must not be empty".into(),
-                ));
-            }
-            if trimmed.len() > i16::MAX as usize {
-                return Err(KafkaProtocolError::InvalidConfig(
-                    "IGGY_KAFKA_ADVERTISED_HOST exceeds Kafka nullable string limit (32767 bytes)"
-                        .into(),
-                ));
-            }
-            trimmed.to_string()
-        } else if local_addr.ip().is_unspecified() {
-            return Err(KafkaProtocolError::InvalidConfig(
-                "binding to a wildcard address (0.0.0.0 or ::) requires \
-                 IGGY_KAFKA_ADVERTISED_HOST to be set to a reachable hostname or IP for \
-                 Metadata broker advertisement"
-                    .into(),
-            ));
-        } else {
-            local_addr.ip().to_string()
-        };
+    /// On a listener without SASL the keys are still answered, with `ILLEGAL_SASL_STATE` and an
+    /// empty mechanism list, because a well-formed response exists for them unlike a genuinely
+    /// unknown key. They are kept out of the advertisement so nothing is invited into an exchange
+    /// that cannot finish.
+    #[must_use]
+    pub fn sasl_enabled(&self) -> bool {
+        self.listeners
+            .iter()
+            .any(|listener| listener.protocol.uses_sasl())
+    }
+
+    /// Whether any listener speaks TLS.
+    #[must_use]
+    pub fn tls_enabled(&self) -> bool {
+        self.listeners
+            .iter()
+            .any(|listener| listener.protocol.uses_tls())
+    }
 
-        Ok(Self { host, port })
+    /// Whether some listener turns client certificates into Iggy identities: an `SSL` listener
+    /// with client authentication on.
+    #[must_use]
+    pub fn maps_certificate_identities(&self) -> bool {
+        self.tls
+            .as_ref()
+            .is_some_and(|tls| tls.client_auth.is_enabled())
+            && self
+                .listeners
+                .iter()
+                .any(|listener| listener.protocol.authenticates_by_certificate())
     }
 }
 
@@ -264,29 +263,106 @@ pub fn bind_listener(addr: &str) -> Result<TcpListener> {
     Ok(TcpListener::from_std(std_listener)?)
 }
 
+/// A listener bound by the caller, paired with the configuration it was bound from.
+pub struct BoundListener {
+    pub config: ListenerConfig,
+    pub socket: TcpListener,
+}
+
+impl BoundListener {
+    #[must_use]
+    pub const fn new(config: ListenerConfig, socket: TcpListener) -> Self {
+        Self { config, socket }
+    }
+
+    /// The address the socket is actually bound to.
+    ///
+    /// # Errors
+    ///
+    /// Returns the socket's error when the address cannot be read.
+    pub fn local_addr(&self) -> io::Result<SocketAddr> {
+        self.socket.local_addr()
+    }
+}
+
+/// Binds every listener in `config`, through [`bind_listener`].
+///
+/// # Errors
+///
+/// Returns the first bind failure, naming the listener's protocol and address.
+pub fn bind_listeners(config: &GatewayConfig) -> Result<Vec<BoundListener>> {
+    config
+        .listeners
+        .iter()
+        .map(|listener| {
+            let socket = bind_listener(&listener.bind_addr).map_err(|error| {
+                KafkaProtocolError::InvalidConfig(format!(
+                    "failed to bind the {} listener on {}: {error}",
+                    listener.protocol, listener.bind_addr
+                ))
+            })?;
+            Ok(BoundListener::new(listener.clone(), socket))
+        })
+        .collect()
+}
+
 pub struct KafkaGateway {
     config: Arc<GatewayConfig>,
     authenticator: Option<Arc<dyn SaslAuthenticator>>,
     bridge: Option<Arc<IggyBridge>>,
+    principal_resolver: Option<Arc<dyn PrincipalResolver>>,
 }
 
 /// Owned by [`KafkaGateway::run`] and shared by every connection it serves.
 struct SharedAuth {
     authenticator: Option<Arc<dyn SaslAuthenticator>>,
+    /// Looks up the Iggy user a client certificate names. The bridge, unless a test swaps one in.
+    resolver: Option<Arc<dyn PrincipalResolver>>,
     slots: Semaphore,
     failed_logins: FailedLoginThrottle,
 }
 
 impl SharedAuth {
-    fn new(authenticator: Option<Arc<dyn SaslAuthenticator>>, max_concurrent: usize) -> Self {
+    fn new(
+        authenticator: Option<Arc<dyn SaslAuthenticator>>,
+        resolver: Option<Arc<dyn PrincipalResolver>>,
+        max_concurrent: usize,
+    ) -> Self {
         Self {
             authenticator,
+            resolver,
             slots: Semaphore::new(max_concurrent),
             failed_logins: FailedLoginThrottle::default(),
         }
     }
 }
 
+/// One listener as its accept loop and its connections see it.
+struct Listener {
+    protocol: SecurityProtocol,
+    broker: BrokerAdvertise,
+    /// Whether this listener names a principal, by SASL or by a verified client certificate.
+    /// Decides whether `DescribeAcls` is advertised and answered.
+    acls_enabled: bool,
+}
+
+impl Listener {
+    fn connection_state(&self) -> ConnectionState {
+        ConnectionState::for_listener(
+            self.broker.clone(),
+            self.protocol.uses_sasl(),
+            self.acls_enabled,
+        )
+    }
+
+    const fn advertisement(&self) -> Advertisement {
+        Advertisement {
+            sasl: self.protocol.uses_sasl(),
+            acls: self.acls_enabled,
+        }
+    }
+}
+
 impl KafkaGateway {
     #[must_use]
     pub fn new(config: GatewayConfig) -> Self {
@@ -294,12 +370,15 @@ impl KafkaGateway {
             config: Arc::new(config),
             authenticator: None,
             bridge: None,
+            principal_resolver: None,
         }
     }
 
     /// Serve requests against `bridge` instead of the stub answers.
     ///
-    /// `None` is the default and keeps every handler on its stub.
+    /// `None` is the default and keeps every handler on its stub. The bridge also resolves the
+    /// Iggy user a client certificate names, unless [`Self::with_principal_resolver`] supplies
+    /// something else.
     #[must_use]
     pub fn with_bridge(mut self, bridge: Option<Arc<IggyBridge>>) -> Self {
         self.bridge = bridge;
@@ -308,7 +387,7 @@ impl KafkaGateway {
 
     /// Supplies the verifier that SASL credentials are checked against.
     ///
-    /// Required when `sasl_enabled` is set: a gateway that demands authentication with nothing to
+    /// Required when a listener runs SASL: a gateway that demands authentication with nothing to
     /// authenticate against would refuse every client, so [`Self::run`] rejects that combination
     /// at startup rather than at the first login attempt.
     #[must_use]
@@ -317,149 +396,325 @@ impl KafkaGateway {
         self
     }
 
-    /// Accept Kafka wire connections until `shutdown` fires, then drain in-flight tasks.
+    /// Supplies the lookup that turns a client certificate's mapped name into an Iggy user.
     ///
-    /// `listener` must already be bound by the caller. This lets tests and `main` bind
-    /// the port before spawning the task, eliminating the TOCTOU race of bind-drop-rebind.
+    /// The bridge does this by default. A test drives the certificate path without an Iggy
+    /// server by supplying its own.
+    #[must_use]
+    pub fn with_principal_resolver(mut self, resolver: Arc<dyn PrincipalResolver>) -> Self {
+        self.principal_resolver = Some(resolver);
+        self
+    }
+
+    /// Accept Kafka wire connections on every listener until `shutdown` fires, then drain
+    /// in-flight tasks.
+    ///
+    /// The listeners must already be bound by the caller. This lets tests and `main` bind the
+    /// ports before spawning the task, eliminating the TOCTOU race of bind-drop-rebind.
     ///
     /// # Errors
     ///
-    /// Returns an error on invalid config or a non-transient `accept()` error.
+    /// Returns an error on invalid config, unusable TLS material, or a non-transient `accept()`
+    /// error on any listener.
     pub async fn run(
         self,
-        listener: TcpListener,
+        listeners: Vec<BoundListener>,
         mut shutdown: broadcast::Receiver<()>,
     ) -> Result<()> {
         self.check_sasl_wiring()?;
-        let local_addr = listener.local_addr()?;
-        let broker = BrokerAdvertise::from_server_config(&self.config, local_addr)?;
-        // instance_id is logged because it is the only way to tell from a running process which
-        // half of the producer-id space this gateway owns. Two gateways left on the default
-        // collide silently, and a config file cannot be diffed against a live deployment.
-        info!(
-            "kafka listener bound on {} (advertised as {}:{}, instance id {})",
-            local_addr, broker.host, broker.port, self.config.instance_id
-        );
+        let tls = self.check_tls_wiring(&listeners)?;
+        if listeners.is_empty() {
+            return Err(KafkaProtocolError::InvalidConfig(
+                "no listener is configured".into(),
+            ));
+        }
+        let resolver = self.principal_resolver.clone().or_else(|| {
+            self.bridge
+                .clone()
+                .map(|bridge| bridge as Arc<dyn PrincipalResolver>)
+        });
+        let acls_by_certificate = tls
+            .as_ref()
+            .is_some_and(|tls| tls.config().client_auth.is_enabled());
+
+        let mut bound = Vec::with_capacity(listeners.len());
+        for BoundListener { config, socket } in listeners {
+            let local_addr = socket.local_addr()?;
+            let broker = BrokerAdvertise::for_listener(&config, local_addr)?;
+            // instance_id is logged because it is the only way to tell from a running process
+            // which half of the producer-id space this gateway owns. Two gateways left on the
+            // default collide silently, and a config file cannot be diffed against a live
+            // deployment.
+            info!(
+                "kafka {} listener bound on {} (advertised as {}:{}, instance id {})",
+                config.protocol, local_addr, broker.host, broker.port, self.config.instance_id
+            );
+            let protocol = config.protocol;
+            bound.push((
+                Arc::new(Listener {
+                    protocol,
+                    broker,
+                    acls_enabled: protocol.uses_sasl()
+                        || (protocol.authenticates_by_certificate() && acls_by_certificate),
+                }),
+                socket,
+            ));
+        }
+
         // Cancelled on shutdown so connection tasks exit instead of sitting in idle waits until
         // `idle_timeout` (or forever if that is raised). Created before the state so the group
         // coordinator can take a child token: a parked JoinGroup or SyncGroup waiter would
         // otherwise hold the drain open for a full rebalance timeout.
         let cancel = CancellationToken::new();
         let state = Arc::new(GatewayState::new(
-            broker,
             self.bridge.clone(),
             self.config.max_frame_size,
-            self.config.sasl_enabled,
             self.config.instance_id,
             GroupCoordinator::new(self.config.group.clone(), cancel.child_token()),
         ));
-
         let shared_auth = Arc::new(SharedAuth::new(
             self.authenticator.clone(),
+            resolver,
             self.config.max_concurrent_authentications,
         ));
         let tracker = TaskTracker::new();
         let conn_limiter = Arc::new(Semaphore::new(self.config.max_connections));
-
         let drain_timeout = self.config.shutdown_drain_timeout;
 
-        loop {
-            tokio::select! {
-                result = shutdown.recv() => {
-                    match result {
-                        Ok(()) => {
-                            info!("kafka listener shutdown requested");
-                            drain(&tracker, &cancel, drain_timeout).await;
-                            break;
-                        }
-                        // Capacity-1 channel: lagged means a signal was sent before we polled - treat as shutdown.
-                        Err(broadcast::error::RecvError::Lagged(_)) => {
-                            info!("kafka listener shutdown requested (lagged)");
-                            drain(&tracker, &cancel, drain_timeout).await;
-                            break;
-                        }
-                        Err(broadcast::error::RecvError::Closed) => {
-                            drain(&tracker, &cancel, drain_timeout).await;
-                            break;
-                        }
-                    }
-                }
-                accept_result = listener.accept() => {
-                    match accept_result {
-                        Ok((stream, peer)) => {
-                            let Ok(permit) = Arc::clone(&conn_limiter).try_acquire_owned() else {
-                                warn!(%peer, max_connections = self.config.max_connections, "connection limit reached, rejecting");
-                                continue;
-                            };
-                            if let Err(e) = stream.set_nodelay(true) {
-                                warn!(%peer, "TCP_NODELAY failed: {e}");
-                            }
-                            if let Err(e) = enable_tcp_keepalive(&stream) {
-                                warn!(%peer, "TCP_KEEPALIVE failed: {e}");
-                            }
-                            let cfg = Arc::clone(&self.config);
-                            let state = Arc::clone(&state);
-                            let auth = Arc::clone(&shared_auth);
-                            let conn_cancel = cancel.child_token();
-                            tracker.spawn(async move {
-                                let _permit = permit;
-                                if let Err(err) =
-                                    handle_connection(stream, cfg, peer, state, auth, conn_cancel)
-                                        .await
-                                {
-                                    // debug!, not warn!: every `KafkaProtocolError` that can
-                                    // reach here is either a malformed/oversized frame from the
-                                    // client (attacker-controlled, not operator-actionable) or a
-                                    // plain TCP reset/EOF - never an internal gateway fault. A
-                                    // flood of either at warn! would drown real signal in logs
-                                    // under adversarial load (same reasoning as the decode-
-                                    // failure downgrades in `protocol/api.rs`).
-                                    debug!(%peer, "connection closed with error: {err}");
-                                }
-                            });
-                        }
-                        Err(e) if is_transient_accept_error(&e) => {
-                            // Brief backoff on fd exhaustion to avoid busy-spinning.
-                            if matches!(e.raw_os_error(), Some(23 | 24)) {
-                                tokio::time::sleep(Duration::from_millis(10)).await;
-                            }
-                            warn!(%e, "transient accept error, continuing");
-                        }
-                        Err(e) => {
-                            drain(&tracker, &cancel, drain_timeout).await;
-                            return Err(e.into());
-                        }
+        if let Some(tls) = &tls {
+            // Not tracked: it ends on the cancel token, which the drain fires first.
+            tokio::spawn(Arc::clone(tls).reload_until_cancelled(cancel.child_token()));
+        }
+
+        let mut accept_loops = JoinSet::new();
+        for (listener, socket) in bound {
+            accept_loops.spawn(accept_loop(AcceptLoop {
+                socket,
+                listener,
+                config: Arc::clone(&self.config),
+                state: Arc::clone(&state),
+                auth: Arc::clone(&shared_auth),
+                tracker: tracker.clone(),
+                conn_limiter: Arc::clone(&conn_limiter),
+                cancel: cancel.clone(),
+                tls: tls.clone(),
+            }));
+        }
+
+        let outcome = tokio::select! {
+            result = shutdown.recv() => {
+                match result {
+                    Ok(()) => info!("kafka listener shutdown requested"),
+                    // Capacity-1 channel: lagged means a signal was sent before we polled -
+                    // treat as shutdown.
+                    Err(broadcast::error::RecvError::Lagged(_)) => {
+                        info!("kafka listener shutdown requested (lagged)");
                     }
+                    Err(broadcast::error::RecvError::Closed) => {}
                 }
-
+                Ok(())
             }
-        }
-        Ok(())
+            // An accept loop ends early only on a non-transient accept error, since shutdown is
+            // what the other branch is for.
+            Some(finished) = accept_loops.join_next() => match finished {
+                Ok(result) => result,
+                Err(join_error) => Err(io::Error::other(join_error).into()),
+            },
+        };
+        drain(&tracker, &cancel, drain_timeout).await;
+        accept_loops.shutdown().await;
+        outcome
     }
 
-    /// Refuses to start when the SASL flag and the configured authenticator disagree.
+    /// Refuses to start when the SASL listeners and the configured authenticator disagree.
     fn check_sasl_wiring(&self) -> Result<()> {
-        if !self.config.sasl_enabled && self.authenticator.is_some() {
-            // The mirror of the guard below, and the quieter mistake: a verifier attached while the
-            // flag is off means every connection is served unauthenticated, with nothing in the log
-            // to say so. Refusing to start is the only way that failure is visible.
+        let sasl_enabled = self.config.sasl_enabled();
+        if !sasl_enabled && self.authenticator.is_some() {
+            // The mirror of the guard below, and the quieter mistake: a verifier attached while no
+            // listener runs SASL means every connection is served unauthenticated, with nothing
+            // in the log to say so. Refusing to start is the only way that failure is visible.
             return Err(KafkaProtocolError::InvalidConfig(
-                "an authenticator is configured but SASL is disabled; every connection would be \
-                 served unauthenticated. Set IGGY_KAFKA_SASL_ENABLED=true, or remove the \
-                 authenticator"
+                "an authenticator is configured but no listener runs SASL; every connection \
+                 would be served unauthenticated. Add a SASL_PLAINTEXT or SASL_SSL listener (or \
+                 set IGGY_KAFKA_SASL_ENABLED=true), or remove the authenticator"
                     .into(),
             ));
         }
-        if self.config.sasl_enabled && self.authenticator.is_none() {
+        if sasl_enabled && self.authenticator.is_none() {
             return Err(KafkaProtocolError::InvalidConfig(
-                "SASL is enabled but no authenticator is configured; every client would be \
-                 rejected. Set IGGY_KAFKA_IGGY_ADDR to the Iggy server that credentials are \
-                 verified against, or unset IGGY_KAFKA_SASL_ENABLED"
+                "a listener runs SASL but no authenticator is configured; every client on it \
+                 would be rejected. Set IGGY_KAFKA_IGGY_ADDR to the Iggy server that credentials \
+                 are verified against, or drop the SASL listener"
                     .into(),
             ));
         }
         Ok(())
     }
+
+    /// Loads the TLS material when a listener needs it, and refuses the combinations in which
+    /// something configured would silently go unused.
+    fn check_tls_wiring(&self, listeners: &[BoundListener]) -> Result<Option<Arc<TlsState>>> {
+        let tls_listener = listeners
+            .iter()
+            .find(|listener| listener.config.protocol.uses_tls());
+        let Some(tls_config) = self.config.tls.clone() else {
+            if let Some(listener) = tls_listener {
+                return Err(KafkaProtocolError::InvalidConfig(format!(
+                    "the {} listener needs a certificate; set IGGY_KAFKA_TLS_CERT_FILE and \
+                     IGGY_KAFKA_TLS_KEY_FILE",
+                    listener.config.protocol
+                )));
+            }
+            return Ok(None);
+        };
+        if tls_listener.is_none() {
+            // The same mistake the SASL guard catches: material configured and nothing serving
+            // it reads as an encrypted listener to whoever set it.
+            return Err(KafkaProtocolError::InvalidConfig(
+                "TLS is configured but no listener uses it; add an SSL or SASL_SSL listener to \
+                 IGGY_KAFKA_LISTENERS, or remove the IGGY_KAFKA_TLS_* settings"
+                    .into(),
+            ));
+        }
+        let maps_identities = tls_config.client_auth.is_enabled()
+            && listeners
+                .iter()
+                .any(|listener| listener.config.protocol.authenticates_by_certificate());
+        if maps_identities && self.principal_resolver.is_none() && self.bridge.is_none() {
+            // A certificate names an Iggy user, and only an Iggy session can say whether that
+            // user exists. Admitting the name unchecked would let any certificate from the CA
+            // claim any account.
+            return Err(KafkaProtocolError::InvalidConfig(
+                "the SSL listener maps client certificates to Iggy users, which needs the bridge \
+                 to look them up; set IGGY_KAFKA_BRIDGE_ENABLED=true, or set \
+                 IGGY_KAFKA_TLS_CLIENT_AUTH=none"
+                    .into(),
+            ));
+        }
+        TlsState::load(tls_config).map(|state| Some(Arc::new(state)))
+    }
+}
+
+/// Everything one listener's accept loop needs, bundled so the loop is one spawnable future.
+struct AcceptLoop {
+    socket: TcpListener,
+    listener: Arc<Listener>,
+    config: Arc<GatewayConfig>,
+    state: Arc<GatewayState>,
+    auth: Arc<SharedAuth>,
+    tracker: TaskTracker,
+    conn_limiter: Arc<Semaphore>,
+    cancel: CancellationToken,
+    tls: Option<Arc<TlsState>>,
+}
+
+/// Accepts on one listener until the cancel token fires or `accept()` fails for good.
+async fn accept_loop(this: AcceptLoop) -> Result<()> {
+    loop {
+        let accepted = tokio::select! {
+            () = this.cancel.cancelled() => return Ok(()),
+            accepted = this.socket.accept() => accepted,
+        };
+        match accepted {
+            Ok((stream, peer)) => {
+                let Ok(permit) = Arc::clone(&this.conn_limiter).try_acquire_owned() else {
+                    warn!(%peer, max_connections = this.config.max_connections, "connection limit reached, rejecting");
+                    continue;
+                };
+                if let Err(e) = stream.set_nodelay(true) {
+                    warn!(%peer, "TCP_NODELAY failed: {e}");
+                }
+                if let Err(e) = enable_tcp_keepalive(&stream) {
+                    warn!(%peer, "TCP_KEEPALIVE failed: {e}");
+                }
+                let connection = Connection {
+                    peer,
+                    listener: Arc::clone(&this.listener),
+                    config: Arc::clone(&this.config),
+                    state: Arc::clone(&this.state),
+                    auth: Arc::clone(&this.auth),
+                    cancel: this.cancel.child_token(),
+                    tls: this.tls.clone(),
+                };
+                this.tracker.spawn(async move {
+                    let _permit = permit;
+                    serve_connection(stream, connection).await;
+                });
+            }
+            Err(e) if is_transient_accept_error(&e) => {
+                // Brief backoff on fd exhaustion to avoid busy-spinning.
+                if matches!(e.raw_os_error(), Some(23 | 24)) {
+                    tokio::time::sleep(Duration::from_millis(10)).await;
+                }
+                warn!(%e, "transient accept error, continuing");
+            }
+            Err(e) => return Err(e.into()),
+        }
+    }
+}
+
+/// What an accepted socket carries into its own task.
+struct Connection {
+    peer: SocketAddr,
+    listener: Arc<Listener>,
+    config: Arc<GatewayConfig>,
+    state: Arc<GatewayState>,
+    auth: Arc<SharedAuth>,
+    cancel: CancellationToken,
+    tls: Option<Arc<TlsState>>,
+}
+
+/// Runs the TLS handshake when the listener calls for one, then the frame loop.
+async fn serve_connection(stream: TcpStream, connection: Connection) {
+    let peer = connection.peer;
+    let result = if connection.listener.protocol.uses_tls() {
+        let Some(tls) = connection.tls.clone() else {
+            // `check_tls_wiring` refuses to start a TLS listener without material.
+            error!(%peer, "TLS listener accepted a connection with no TLS material loaded");
+            return;
+        };
+        // Bounded like everything else a connection does before proving who it is: an
+        // unfinished handshake holds a `max_connections` permit.
+        let handshake = timeout(
+            connection.config.pre_auth_timeout,
+            tls.acceptor().accept(stream),
+        );
+        let tls_stream = match handshake.await {
+            Ok(Ok(tls_stream)) => tls_stream,
+            Ok(Err(error)) => {
+                // debug!, not warn!: a plaintext client on the TLS port, an untrusted client
+                // certificate or a scanner all end here, none of them operator-actionable.
+                debug!(%peer, %error, "TLS handshake failed");
+                return;
+            }
+            Err(_elapsed) => {
+                debug!(%peer, "TLS handshake did not finish within the pre-authentication budget");
+                return;
+            }
+        };
+        let certificate_name = if connection.listener.protocol.authenticates_by_certificate() {
+            match tls.principal_name(tls_stream.get_ref().1) {
+                Ok(name) => name,
+                Err(error) => {
+                    debug!(%peer, %error, "client certificate names no principal; closing");
+                    return;
+                }
+            }
+        } else {
+            None
+        };
+        handle_connection(tls_stream, connection, certificate_name).await
+    } else {
+        handle_connection(stream, connection, None).await
+    };
+    if let Err(err) = result {
+        // debug!, not warn!: every `KafkaProtocolError` that can reach here is either a
+        // malformed/oversized frame from the client (attacker-controlled, not
+        // operator-actionable) or a plain TCP reset/EOF - never an internal gateway fault. A
+        // flood of either at warn! would drown real signal in logs under adversarial load (same
+        // reasoning as the decode-failure downgrades in `protocol/api.rs`).
+        debug!(%peer, "connection closed with error: {err}");
+    }
 }
 
 /// Cancel in-flight connections, close the tracker to new spawns, and wait for tasks to finish
@@ -500,9 +755,11 @@ fn enable_tcp_keepalive(stream: &TcpStream) -> std::io::Result<()> {
 /// for no gain in clarity.
 struct ConnectionContext<'a> {
     config: &'a GatewayConfig,
+    listener: &'a Listener,
     state: &'a GatewayState,
     connection: &'a ConnectionState,
     authenticator: Option<&'a dyn SaslAuthenticator>,
+    resolver: Option<&'a dyn PrincipalResolver>,
     auth_slots: &'a Semaphore,
     failed_logins: &'a FailedLoginThrottle,
     peer: &'a SocketAddr,
@@ -538,13 +795,14 @@ async fn route_frame(
     );
     match action {
         // Answered here rather than in the stateless dispatch, because it describes the principal
-        // this connection authenticated as, which only the connection knows. Gated on the feature
-        // as well as the key: with SASL off there is no principal, and the key is not advertised,
-        // so it falls through to ordinary dispatch and is refused as the unlisted key it is.
+        // this connection authenticated as, which only the connection knows. Gated on the
+        // listener naming principals as well as on the key: elsewhere there is no principal, and
+        // the key is not advertised, so it falls through to ordinary dispatch and is refused as
+        // the unlisted key it is.
         SaslAction::Dispatch
-            if ctx.config.sasl_enabled && req.request_api_key == API_KEY_DESCRIBE_ACLS =>
+            if ctx.listener.acls_enabled && req.request_api_key == API_KEY_DESCRIBE_ACLS =>
         {
-            describe_acls(principal.as_ref(), req.request_api_version, body, peer)
+            describe_acls(ctx, principal.as_ref(), req.request_api_version, body)
         }
         SaslAction::Dispatch => {
             handle_connection_request(
@@ -623,41 +881,65 @@ async fn route_frame(
                 req.request_api_key,
                 req.request_api_version,
                 matches!(action, SaslAction::IllegalStateKeepOpen),
-                ctx.config.sasl_enabled,
+                ctx.listener.advertisement(),
             )
         }
     }
 }
 
-async fn handle_connection(
-    mut stream: TcpStream,
-    config: Arc<GatewayConfig>,
-    peer: SocketAddr,
-    state: Arc<GatewayState>,
-    shared_auth: Arc<SharedAuth>,
-    cancel: CancellationToken,
-) -> Result<()> {
-    debug!(%peer, "connection accepted");
-
-    // A gateway with SASL off starts every connection already authenticated, so the dispatch path
-    // below has one question to ask rather than two.
-    let mut sasl_state = if config.sasl_enabled {
+/// The frame loop of one accepted connection, plain or TLS.
+///
+/// `certificate_name` is the Iggy username the client certificate mapped to, on an `SSL`
+/// listener that verifies certificates. It is resolved against Iggy before the first frame, and
+/// a name that resolves to no user closes the connection, so a certificate from the trusted CA
+/// never admits a client as an account that does not exist.
+async fn handle_connection<S>(
+    mut stream: S,
+    connection: Connection,
+    certificate_name: Option<String>,
+) -> Result<()>
+where
+    S: AsyncRead + AsyncWrite + Unpin + Send,
+{
+    let Connection {
+        peer,
+        listener,
+        config,
+        state,
+        auth: shared_auth,
+        cancel,
+        tls: _,
+    } = connection;
+    debug!(%peer, protocol = %listener.protocol, "connection accepted");
+
+    // A listener without SASL starts every connection already authenticated, so the dispatch
+    // path below has one question to ask rather than two.
+    let mut sasl_state = if listener.protocol.uses_sasl() {
         SaslState::new()
     } else {
         SaslState::Authenticated
     };
-    let mut principal: Option<AuthenticatedPrincipal> = None;
-    let connection = ConnectionState::default();
+    let connection_state = listener.connection_state();
     let ctx = ConnectionContext {
         config: &config,
+        listener: &listener,
         state: &state,
-        connection: &connection,
+        connection: &connection_state,
         authenticator: shared_auth.authenticator.as_deref(),
+        resolver: shared_auth.resolver.as_deref(),
         auth_slots: &shared_auth.slots,
         failed_logins: &shared_auth.failed_logins,
         peer: &peer,
         cancel: &cancel,
     };
+    let mut principal = if let Some(username) = certificate_name {
+        let Some(resolved) = resolve_certificate_principal(&ctx, &username).await else {
+            return Ok(());
+        };
+        Some(resolved)
+    } else {
+        None
+    };
 
     loop {
         let idle_budget = if sasl_state.is_authenticated() {
@@ -722,6 +1004,51 @@ async fn handle_connection(
     }
 }
 
+/// Looks up the Iggy user a client certificate named, within the pre-authentication budget.
+///
+/// `None` closes the connection. Unlike a SASL refusal there is no response to shape: the client
+/// has sent nothing yet, and a certificate the CA signed for an account that does not exist is a
+/// provisioning mistake the gateway's log reports, not something the client can correct.
+async fn resolve_certificate_principal(
+    ctx: &ConnectionContext<'_>,
+    username: &str,
+) -> Option<AuthenticatedPrincipal> {
+    let peer = ctx.peer;
+    let Some(resolver) = ctx.resolver else {
+        // Unreachable: `check_tls_wiring` refuses to start in this combination. Fail closed
+        // anyway, since the alternative is admitting an unverified identity.
+        error!(%peer, "a client certificate named a principal but nothing can look it up");
+        return None;
+    };
+    let outcome = tokio::select! {
+        () = ctx.cancel.cancelled() => {
+            debug!(%peer, "certificate identity lookup abandoned by shutdown");
+            return None;
+        }
+        outcome = timeout(ctx.config.pre_auth_timeout, resolver.resolve(username)) => outcome,
+    };
+    match outcome {
+        Ok(Ok(principal)) => {
+            debug!(%peer, username, "client certificate authenticated");
+            Some(principal)
+        }
+        Ok(Err(AuthError::Rejected)) => {
+            // warn!, not debug!: the certificate chained to the trusted CA, so this is an account
+            // the operator meant to exist, or a mapping rule that produced the wrong name.
+            warn!(%peer, username, "client certificate names no active Iggy user; closing");
+            None
+        }
+        Ok(Err(AuthError::Unavailable)) => {
+            warn!(%peer, username, "could not look up the certificate's Iggy user; closing");
+            None
+        }
+        Err(_elapsed) => {
+            warn!(%peer, username, "certificate identity lookup did not finish within the pre-authentication budget");
+            None
+        }
+    }
+}
+
 /// Verifies a `SaslAuthenticate` token and answers it.
 ///
 /// Every failure answers with the same code and the same message. A malformed token, an unknown
@@ -809,23 +1136,38 @@ async fn authenticate_token(
 
 /// Answers `DescribeAcls` from the permissions captured when this connection authenticated.
 ///
-/// Only reachable on an authenticated connection: the SASL gate refuses every key but one before a
-/// principal exists, and the caller additionally gates this on the feature being on, so a gateway
-/// with SASL off never routes here. The `None` arm is a fail-closed guard, not a reachable path.
+/// Only reachable on a listener that names principals: elsewhere the key is not advertised and
+/// falls through to ordinary dispatch, which refuses it. On a SASL listener the SASL gate refuses
+/// every key but one before a principal exists, so a missing principal there is a gateway fault.
+/// On an `SSL` listener that only requests a certificate, a client that presented none is
+/// Kafka's anonymous principal, and is described as holding nothing.
 fn describe_acls(
+    ctx: &ConnectionContext<'_>,
     principal: Option<&AuthenticatedPrincipal>,
     api_version: i16,
     body: Bytes,
-    peer: &SocketAddr,
 ) -> HandleOutcome {
-    let Some(principal) = principal else {
-        // `error!` rather than `debug!` on purpose, unlike every other refusal here: reaching this
-        // means the routing guards above disagree with each other, which is a gateway fault and not
-        // something a client can provoke.
-        error!(%peer, "DescribeAcls reached a connection with no authenticated principal");
-        // Not `encode_error_for_key`: key 29 is absent from `SUPPORTED_RANGES`, so that helper
-        // always returns `Close` here and the code would read as if it answers when it cannot.
-        return respond_describe_acls_error(api_version, ERROR_ILLEGAL_SASL_STATE, true);
+    let peer = ctx.peer;
+    let anonymous;
+    let principal = match principal {
+        Some(principal) => principal,
+        None if ctx.listener.protocol.uses_sasl() => {
+            // `error!` rather than `debug!` on purpose, unlike every other refusal here: reaching
+            // this means the routing guards above disagree with each other, which is a gateway
+            // fault and not something a client can provoke.
+            error!(%peer, "DescribeAcls reached a connection with no authenticated principal");
+            // Not `encode_error_for_key`: key 29 is absent from `SUPPORTED_RANGES`, so that helper
+            // always returns `Close` here and the code would read as if it answers when it cannot.
+            return respond_describe_acls_error(api_version, ERROR_ILLEGAL_SASL_STATE, true);
+        }
+        None => {
+            anonymous = AuthenticatedPrincipal {
+                username: ANONYMOUS_PRINCIPAL.to_string(),
+                permissions: PrincipalPermissions::default(),
+                permissions_known: true,
+            };
+            &anonymous
+        }
     };
     // The firewall table cannot cover this key: it is kept out of `SUPPORTED_RANGES` on purpose,
     // so the advertised range would otherwise be enforced only by whatever `kafka_protocol`'s
@@ -901,7 +1243,7 @@ fn illegal_state_outcome(
     api_key: i16,
     api_version: i16,
     keep_open: bool,
-    sasl_enabled: bool,
+    advertisement: Advertisement,
 ) -> HandleOutcome {
     match api_key {
         API_KEY_SASL_HANDSHAKE if (0..=SASL_HANDSHAKE_VERSION).contains(&api_version) => {
@@ -914,19 +1256,25 @@ fn illegal_state_outcome(
         // from it, so routing through there would answer an unauthenticated client with a bodyless
         // close while the unreachable guard above is the one that speaks. Answer it directly.
         API_KEY_DESCRIBE_ACLS
-            if sasl_enabled && SASL_ADVERTISED_DESCRIBE_ACLS_VERSIONS.contains(&api_version) =>
+            if advertisement.acls
+                && SASL_ADVERTISED_DESCRIBE_ACLS_VERSIONS.contains(&api_version) =>
         {
             respond_describe_acls_error(api_version, ERROR_ILLEGAL_SASL_STATE, !keep_open)
         }
         API_KEY_SASL_HANDSHAKE | API_KEY_SASL_AUTHENTICATE => HandleOutcome::Close,
-        API_KEY_DESCRIBE_ACLS if sasl_enabled => HandleOutcome::Close,
-        _ => encode_error_for_key(api_key, api_version, ERROR_ILLEGAL_SASL_STATE, sasl_enabled),
+        API_KEY_DESCRIBE_ACLS if advertisement.acls => HandleOutcome::Close,
+        _ => encode_error_for_key(
+            api_key,
+            api_version,
+            ERROR_ILLEGAL_SASL_STATE,
+            advertisement,
+        ),
     }
 }
 
 /// Returns `Ok(None)` when shutdown cancellation wins; `Ok(Some(frame))` on a full frame.
-async fn read_next_frame(
-    stream: &mut TcpStream,
+async fn read_next_frame<S: AsyncRead + Unpin>(
+    stream: &mut S,
     config: &GatewayConfig,
     idle_timeout: Duration,
     peer: &SocketAddr,
@@ -957,8 +1305,8 @@ async fn read_next_frame(
 }
 
 /// Applies a [`HandleOutcome`]. Returns `true` when the connection should close.
-async fn dispatch_outcome(
-    stream: &mut TcpStream,
+async fn dispatch_outcome<S: AsyncRead + AsyncWrite + Unpin>(
+    stream: &mut S,
     peer: &SocketAddr,
     config: &GatewayConfig,
     req: &RequestHeader,
@@ -1024,8 +1372,13 @@ async fn dispatch_outcome(
 ///
 /// Dropping a socket with unread bytes in its receive queue makes Linux send RST instead of FIN,
 /// and an RST lets the peer discard the response this close follows before its client reads it.
-/// A real broker closes an authentication failure gracefully for the same reason.
-async fn close_gracefully(stream: &mut TcpStream, budget: Duration, cancel: &CancellationToken) {
+/// A real broker closes an authentication failure gracefully for the same reason. On a TLS
+/// stream the shutdown also sends `close_notify` first.
+async fn close_gracefully<S: AsyncRead + AsyncWrite + Unpin>(
+    stream: &mut S,
+    budget: Duration,
+    cancel: &CancellationToken,
+) {
     if stream.shutdown().await.is_err() {
         return;
     }
@@ -1053,8 +1406,8 @@ const fn response_header_size(header_version: i16) -> usize {
 
 /// Write a single length-prefixed Kafka frame using one allocation.
 /// Avoids the separate header-encode + payload-concat + length-prefix allocations.
-async fn send_response(
-    stream: &mut TcpStream,
+async fn send_response<S: AsyncWrite + Unpin>(
+    stream: &mut S,
     correlation_id: i32,
     header_version: i16,
     body: Bytes,
@@ -1085,8 +1438,8 @@ async fn send_response(
 /// # Errors
 ///
 /// Returns an error on timeout, invalid length, or I/O failure.
-pub async fn read_frame(
-    stream: &mut TcpStream,
+pub async fn read_frame<S: AsyncRead + Unpin>(
+    stream: &mut S,
     max_frame_size: usize,
     idle_timeout: Duration,
     read_timeout: Duration,
@@ -1273,6 +1626,17 @@ mod tests {
         (client, server)
     }
 
+    /// One plaintext listener on an ephemeral port, the shape every test here runs.
+    async fn ephemeral_plaintext() -> (BoundListener, SocketAddr) {
+        let socket = TcpListener::bind("127.0.0.1:0").await.unwrap();
+        let addr = socket.local_addr().unwrap();
+        let listener = BoundListener::new(
+            ListenerConfig::new(SecurityProtocol::Plaintext, addr.to_string()),
+            socket,
+        );
+        (listener, addr)
+    }
+
     /// `listener_robustness_tests.rs::e2e_frame_exceeding_max_frame_size_closes_connection`
     /// exercises the oversized-frame-rejection *mechanism* with a small custom `max_frame_size`
     /// (sending an 8 MiB+ frame just to hit the real default would be slow for no extra
@@ -1283,6 +1647,22 @@ mod tests {
         assert_eq!(GatewayConfig::default().max_frame_size, 8 * 1024 * 1024);
     }
 
+    #[test]
+    fn default_config_is_one_plaintext_listener_without_tls() {
+        let config = GatewayConfig::default();
+        assert_eq!(
+            config.listeners,
+            vec![ListenerConfig::new(
+                SecurityProtocol::Plaintext,
+                "127.0.0.1:9093"
+            )]
+        );
+        assert!(config.tls.is_none());
+        assert!(!config.sasl_enabled());
+        assert!(!config.tls_enabled());
+        assert!(!config.maps_certificate_identities());
+    }
+
     #[test]
     fn transient_accept_error_classification_covers_all_branches() {
         for kind in [
@@ -1393,8 +1773,7 @@ mod tests {
 
     #[tokio::test]
     async fn server_shutdown_does_not_stall_past_drain_timeout() {
-        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
-        let addr = listener.local_addr().unwrap();
+        let (listener, addr) = ephemeral_plaintext().await;
         let (tx, rx) = broadcast::channel(1);
         let server = KafkaGateway::new(GatewayConfig {
             // Idle timeout is intentionally long - cancellation + drain deadline, not the
@@ -1403,7 +1782,7 @@ mod tests {
             shutdown_drain_timeout: Duration::from_millis(200),
             ..GatewayConfig::default()
         });
-        let handle = tokio::spawn(async move { server.run(listener, rx).await });
+        let handle = tokio::spawn(async move { server.run(vec![listener], rx).await });
 
         // Held open, never sends a frame: without cancellation the task would park in
         // read_frame's idle wait for the full 600s idle_timeout.
@@ -1428,14 +1807,13 @@ mod tests {
 
     #[tokio::test]
     async fn server_rejects_connections_beyond_max_connections() {
-        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
-        let addr = listener.local_addr().unwrap();
+        let (listener, addr) = ephemeral_plaintext().await;
         let (tx, rx) = broadcast::channel(1);
         let server = KafkaGateway::new(GatewayConfig {
             max_connections: 1,
             ..GatewayConfig::default()
         });
-        let handle = tokio::spawn(async move { server.run(listener, rx).await });
+        let handle = tokio::spawn(async move { server.run(vec![listener], rx).await });
 
         // First connection holds the only permit by never sending a frame.
         let held = TcpStream::connect(addr).await.unwrap();
@@ -1458,30 +1836,29 @@ mod tests {
 
     #[tokio::test]
     async fn server_run_exits_when_shutdown_channel_closed() {
-        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+        let (listener, _addr) = ephemeral_plaintext().await;
         let (tx, rx) = broadcast::channel(1);
         drop(tx);
         let server = KafkaGateway::new(GatewayConfig::default());
-        assert!(server.run(listener, rx).await.is_ok());
+        assert!(server.run(vec![listener], rx).await.is_ok());
     }
 
     #[tokio::test]
     async fn server_run_exits_when_shutdown_receiver_is_lagged() {
-        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+        let (listener, _addr) = ephemeral_plaintext().await;
         let (tx, rx) = broadcast::channel(1);
         tx.send(()).unwrap();
         tx.send(()).unwrap();
         let server = KafkaGateway::new(GatewayConfig::default());
-        assert!(server.run(listener, rx).await.is_ok());
+        assert!(server.run(vec![listener], rx).await.is_ok());
     }
 
     #[tokio::test]
     async fn server_run_exits_on_shutdown_signal_ok() {
-        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
-        let addr = listener.local_addr().unwrap();
+        let (listener, addr) = ephemeral_plaintext().await;
         let (tx, rx) = broadcast::channel(1);
         let server = KafkaGateway::new(GatewayConfig::default());
-        let handle = tokio::spawn(async move { server.run(listener, rx).await });
+        let handle = tokio::spawn(async move { server.run(vec![listener], rx).await });
 
         let stream = TcpStream::connect(addr).await.unwrap();
         tx.send(()).unwrap();
@@ -1489,6 +1866,45 @@ mod tests {
         assert!(handle.await.unwrap().is_ok());
     }
 
+    #[tokio::test]
+    async fn server_run_refuses_an_empty_listener_list() {
+        let (_tx, rx) = broadcast::channel(1);
+        let server = KafkaGateway::new(GatewayConfig::default());
+        assert!(server.run(Vec::new(), rx).await.is_err());
+    }
+
+    #[tokio::test]
+    async fn server_run_refuses_a_tls_listener_without_material() {
+        let socket = TcpListener::bind("127.0.0.1:0").await.unwrap();
+        let listener = BoundListener::new(
+            ListenerConfig::new(SecurityProtocol::Ssl, "127.0.0.1:0"),
+            socket,
+        );
+        let (_tx, rx) = broadcast::channel(1);
+        let error = KafkaGateway::new(GatewayConfig::default())
+            .run(vec![listener], rx)
+            .await
+            .unwrap_err()
+            .to_string();
+        assert!(error.contains("IGGY_KAFKA_TLS_CERT_FILE"), "got: {error}");
+    }
+
+    #[tokio::test]
+    async fn server_run_refuses_tls_material_without_a_tls_listener() {
+        let (listener, _addr) = ephemeral_plaintext().await;
+        let (_tx, rx) = broadcast::channel(1);
+        let config = GatewayConfig {
+            tls: Some(TlsConfig::new("unused.pem", "unused.pem")),
+            ..GatewayConfig::default()
+        };
+        let error = KafkaGateway::new(config)
+            .run(vec![listener], rx)
+            .await
+            .unwrap_err()
+            .to_string();
+        assert!(error.contains("no listener uses it"), "got: {error}");
+    }
+
     #[tokio::test]
     async fn read_frame_accepts_exact_max_frame_size() {
         let (mut client, mut server) = tcp_pair().await;
diff --git a/gateways/kafka/src/tls/identity.rs b/gateways/kafka/src/tls/identity.rs
new file mode 100644
index 000000000..e7917fe90
--- /dev/null
+++ b/gateways/kafka/src/tls/identity.rs
@@ -0,0 +1,528 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! The principal a client certificate names.
+//!
+//! Kafka hands `ssl.principal.mapping.rules` the subject as Java's `X500Principal.getName()`
+//! renders it: RFC 2253, most specific RDN first, no spaces after the commas. Operators write
+//! their rules against that rendering, so this one matches it rather than x509-parser's own
+//! `Display`, which keeps the certificate's order and pads with spaces.
+
+use std::fmt::Write as _;
+use std::str::FromStr;
+
+use regex::{Captures, Regex};
+use thiserror::Error;
+use x509_parser::asn1_rs::{Any, Tag, ToDer};
+use x509_parser::parse_x509_certificate;
+use x509_parser::x509::{AttributeTypeAndValue, RelativeDistinguishedName, X509Name};
+
+/// Why a client certificate yielded no principal.
+#[derive(Debug, Error)]
+pub enum IdentityError {
+    #[error("the client certificate could not be parsed: {0}")]
+    Certificate(String),
+    #[error("no principal mapping rule matches the certificate subject '{subject}'")]
+    NoMatchingRule { subject: String },
+}
+
+/// The subject of a DER certificate, as Kafka's principal builder sees it.
+///
+/// # Errors
+///
+/// Returns [`IdentityError::Certificate`] when `certificate` is not a DER X.509 certificate.
+pub fn subject_distinguished_name(certificate: &[u8]) -> Result<String, IdentityError> {
+    let (_, parsed) = parse_x509_certificate(certificate)
+        .map_err(|error| IdentityError::Certificate(error.to_string()))?;
+    Ok(render_rfc2253(parsed.subject()))
+}
+
+/// RFC 2253 string form: RDNs in reverse certificate order, `,` between RDNs, `+` inside a
+/// multi-valued one, and the attribute keywords Java emits.
+fn render_rfc2253(name: &X509Name<'_>) -> String {
+    let rendered: Vec<String> = name.iter_rdn().map(render_rdn).collect();
+    let mut out = String::new();
+    for (index, rdn) in rendered.iter().rev().enumerate() {
+        if index > 0 {
+            out.push(',');
+        }
+        out.push_str(rdn);
+    }
+    out
+}
+
+fn render_rdn(rdn: &RelativeDistinguishedName<'_>) -> String {
+    let mut out = String::new();
+    for (index, attribute) in rdn.iter().enumerate() {
+        if index > 0 {
+            out.push('+');
+        }
+        render_attribute(&mut out, attribute);
+    }
+    out
+}
+
+/// `KEYWORD=value` for the attribute types RFC 2253 and Java give a keyword, `OID=#hex` for the
+/// rest, and `#hex` of the DER for any value that is not a printable string. Java hex-encodes
+/// in exactly those cases, and a rule written against its output has to keep matching here.
+fn render_attribute(out: &mut String, attribute: &AttributeTypeAndValue<'_>) {
+    let value = attribute.attr_value();
+    if let Some(keyword) = rfc2253_keyword(&attribute.attr_type().to_string()) {
+        out.push_str(keyword);
+        out.push('=');
+        match string_value(value) {
+            Some(text) if !text.chars().any(char::is_control) => escape_into(out, &text),
+            _ => push_hex(out, value),
+        }
+    } else {
+        let _ = write!(out, "{}=", attribute.attr_type());
+        push_hex(out, value);
+    }
+}
+
+/// The keyword Java's RFC 2253 rendering uses for an attribute type, or `None` for an OID it
+/// spells out. Java's set is RFC 2253's seven plus `DC` and `UID` from RFC 4514; everything
+/// else, `emailAddress` included, is rendered as a dotted OID with a hex value.
+fn rfc2253_keyword(oid: &str) -> Option<&'static str> {
+    Some(match oid {
+        "2.5.4.3" => "CN",
+        "2.5.4.6" => "C",
+        "2.5.4.7" => "L",
+        "2.5.4.8" => "ST",
+        "2.5.4.9" => "STREET",
+        "2.5.4.10" => "O",
+        "2.5.4.11" => "OU",
+        "0.9.2342.19200300.100.1.25" => "DC",
+        "0.9.2342.19200300.100.1.1" => "UID",
+        _ => return None,
+    })
+}
+
+/// The text of a directory string, for the string types Java decodes rather than hex-encodes.
+fn string_value(value: &Any<'_>) -> Option<String> {
+    match value.tag() {
+        Tag::Utf8String | Tag::PrintableString | Tag::Ia5String | Tag::NumericString => {
+            std::str::from_utf8(value.data).ok().map(str::to_owned)
+        }
+        Tag::BmpString => {
+            let units: Option<Vec<u16>> = value
+                .data
+                .chunks(2)
+                .map(|pair| <[u8; 2]>::try_from(pair).ok().map(u16::from_be_bytes))
+                .collect();
+            String::from_utf16(&units?).ok()
+        }
+        // T.61 is close enough to Latin-1 for the subjects that still carry it.
+        Tag::T61String => Some(value.data.iter().map(|&byte| char::from(byte)).collect()),
+        _ => None,
+    }
+}
+
+fn push_hex(out: &mut String, value: &Any<'_>) {
+    out.push('#');
+    let der = value
+        .to_der_vec()
+        .unwrap_or_else(|_| value.as_bytes().to_vec());
+    for byte in der {
+        let _ = write!(out, "{byte:02x}");
+    }
+}
+
+/// Backslash-escapes what Java's RFC 2253 rendering escapes: `,=+<>#;"\` anywhere, and a space
+/// at either end.
+fn escape_into(out: &mut String, text: &str) {
+    let last = text.chars().count().saturating_sub(1);
+    for (index, character) in text.chars().enumerate() {
+        let edge_space = character == ' ' && (index == 0 || index == last);
+        if edge_space
+            || matches!(
+                character,
+                ',' | '=' | '+' | '<' | '>' | '#' | ';' | '"' | '\\'
+            )
+        {
+            out.push('\\');
+        }
+        out.push(character);
+    }
+}
+
+/// Kafka's `ssl.principal.mapping.rules`: `RULE:pattern/replacement/[LU]` and `DEFAULT`, comma
+/// separated, tried in order. The first rule whose pattern matches the whole subject decides.
+#[derive(Debug, Clone)]
+pub struct PrincipalMappingRules {
+    rules: Vec<Rule>,
+}
+
+#[derive(Debug, Clone)]
+enum Rule {
+    /// The subject string itself.
+    Default,
+    Rewrite {
+        /// The operator's pattern anchored at both ends, since Java's `matches()` demands the
+        /// whole subject.
+        whole: Regex,
+        /// The pattern as written, for the replacement pass. Java runs `replaceAll` over the
+        /// subject with it unanchored, and `a|ab` on `ab` replaces `a` alone that way.
+        finder: Regex,
+        replacement: String,
+        case: Case,
+    },
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Case {
+    Keep,
+    Lower,
+    Upper,
+}
+
+impl Default for PrincipalMappingRules {
+    fn default() -> Self {
+        Self {
+            rules: vec![Rule::Default],
+        }
+    }
+}
+
+impl PrincipalMappingRules {
+    /// Maps a rendered subject to a principal name, or `None` when no rule matches.
+    #[must_use]
+    pub fn map(&self, subject: &str) -> Option<String> {
+        self.rules.iter().find_map(|rule| match rule {
+            Rule::Default => Some(subject.to_string()),
+            Rule::Rewrite {
+                whole,
+                finder,
+                replacement,
+                case,
+            } => {
+                if !whole.is_match(subject) {
+                    return None;
+                }
+                let rewritten = finder.replace_all(subject, |captures: &Captures<'_>| {
+                    expand_replacement(replacement, captures)
+                });
+                Some(match case {
+                    Case::Keep => rewritten.into_owned(),
+                    Case::Lower => rewritten.to_lowercase(),
+                    Case::Upper => rewritten.to_uppercase(),
+                })
+            }
+        })
+    }
+}
+
+impl FromStr for PrincipalMappingRules {
+    type Err = String;
+
+    fn from_str(raw: &str) -> Result<Self, Self::Err> {
+        let mut rules = Vec::new();
+        let mut rest = raw.trim_start();
+        if rest.is_empty() {
+            return Err("the rule list is empty; the default is DEFAULT".to_string());
+        }
+        while !rest.is_empty() {
+            if let Some(after) = rest.strip_prefix("DEFAULT") {
+                rules.push(Rule::Default);
+                rest = after;
+            } else if let Some(after) = rest.strip_prefix("RULE:") {
+                let (pattern, after) = take_until_slash(after)
+                    .ok_or_else(|| format!("rule '{rest}' has no '/' after its pattern"))?;
+                let (replacement, after) = take_until_slash(after)
+                    .ok_or_else(|| format!("rule '{rest}' has no '/' after its replacement"))?;
+                let (case, after) = match after.chars().next() {
+                    Some('L') => (Case::Lower, &after[1..]),
+                    Some('U') => (Case::Upper, &after[1..]),
+                    _ => (Case::Keep, after),
+                };
+                let finder = Regex::new(&pattern).map_err(|error| {
+                    format!("rule pattern '{pattern}' is not a valid regex: {error}")
+                })?;
+                let whole = Regex::new(&format!("^(?:{pattern})$")).map_err(|error| {
+                    format!("rule pattern '{pattern}' is not a valid regex: {error}")
+                })?;
+                rules.push(Rule::Rewrite {
+                    whole,
+                    finder,
+                    replacement,
+                    case,
+                });
+                rest = after;
+            } else {
+                return Err(format!(
+                    "'{rest}' is neither DEFAULT nor RULE:pattern/replacement/[LU]"
+                ));
+            }
+            rest = rest.trim_start();
+            match rest.strip_prefix(',') {
+                Some(after) => {
+                    rest = after.trim_start();
+                    if rest.is_empty() {
+                        return Err("the rule list ends with a comma".to_string());
+                    }
+                }
+                None if rest.is_empty() => {}
+                None => {
+                    return Err(format!(
+                        "expected ',' or the end of the list before '{rest}'"
+                    ));
+                }
+            }
+        }
+        Ok(Self { rules })
+    }
+}
+
+/// Reads up to the first unescaped `/`, unescaping `\/` on the way and keeping every other
+/// escape for the regex engine. Returns the text and what follows the slash.
+fn take_until_slash(input: &str) -> Option<(String, &str)> {
+    let mut text = String::new();
+    let mut chars = input.char_indices();
+    while let Some((index, character)) = chars.next() {
+        match character {
+            '/' => return Some((text, &input[index + 1..])),
+            '\\' => match chars.next() {
+                Some((_, '/')) => text.push('/'),
+                Some((_, escaped)) => {
+                    text.push('\\');
+                    text.push(escaped);
+                }
+                None => text.push('\\'),
+            },
+            other => text.push(other),
+        }
+    }
+    None
+}
+
+/// Expands a replacement the way `java.util.regex.Matcher` does: `$N` is a group, taking as
+/// many digits as still name an existing group, `${name}` a named group, and `\x` a literal
+/// `x`. A group that did not participate expands to nothing.
+fn expand_replacement(replacement: &str, captures: &Captures<'_>) -> String {
+    let mut out = String::new();
+    let mut chars = replacement.chars().peekable();
+    while let Some(character) = chars.next() {
+        match character {
+            '\\' => {
+                if let Some(escaped) = chars.next() {
+                    out.push(escaped);
+                }
+            }
+            '$' => match chars.peek() {
+                Some('{') => {
+                    chars.next();
+                    let name: String = chars.by_ref().take_while(|&c| c != '}').collect();
+                    if let Some(found) = captures.name(&name) {
+                        out.push_str(found.as_str());
+                    }
+                }
+                Some(digit) if digit.is_ascii_digit() => {
+                    let mut group = 0usize;
+                    let mut taken_any = false;
+                    while let Some(&next) = chars.peek() {
+                        let Some(value) = next.to_digit(10) else {
+                            break;
+                        };
+                        let candidate = group * 10 + value as usize;
+                        if taken_any && candidate >= captures.len() {
+                            break;
+                        }
+                        group = candidate;
+                        taken_any = true;
+                        chars.next();
+                    }
+                    if let Some(found) = captures.get(group) {
+                        out.push_str(found.as_str());
+                    }
+                }
+                _ => out.push('$'),
+            },
+            other => out.push(other),
+        }
+    }
+    out
+}
+
+#[cfg(test)]
+mod tests {
+    use rcgen::{CertificateParams, DistinguishedName, DnType, DnValue, KeyPair};
+
+    use super::*;
+
+    /// `build` fills the subject in certificate order, least specific first, the way a CA writes
+    /// it. rcgen seeds every subject with a common name, which would otherwise land first.
+    fn subject_of(build: impl FnOnce(&mut CertificateParams)) -> String {
+        let key = KeyPair::generate().expect("generate a key");
+        let mut params = CertificateParams::new(Vec::<String>::new()).expect("params");
+        params.distinguished_name = DistinguishedName::new();
+        build(&mut params);
+        let certificate = params.self_signed(&key).expect("self-sign");
+        subject_distinguished_name(certificate.der()).expect("parse")
+    }
+
+    #[test]
+    fn given_a_subject_should_render_most_specific_rdn_first_without_spaces() {
+        let subject = subject_of(|params| {
+            params.distinguished_name.push(DnType::CountryName, "US");
+            params
+                .distinguished_name
+                .push(DnType::OrganizationName, "Example");
+            params
+                .distinguished_name
+                .push(DnType::OrganizationalUnitName, "Eng");
+            params.distinguished_name.push(DnType::CommonName, "alice");
+        });
+        assert_eq!(subject, "CN=alice,OU=Eng,O=Example,C=US");
+    }
+
+    #[test]
+    fn given_special_characters_should_escape_them_the_way_java_does() {
+        let subject = subject_of(|params| {
+            params
+                .distinguished_name
+                .push(DnType::CommonName, "Doe, John+Jr <#1>=\"x\"; \\");
+        });
+        assert_eq!(subject, r#"CN=Doe\, John\+Jr \<\#1\>\=\"x\"\; \\"#);
+    }
+
+    #[test]
+    fn given_edge_spaces_should_escape_only_those() {
+        let subject = subject_of(|params| {
+            params
+                .distinguished_name
+                .push(DnType::CommonName, DnValue::Utf8String(" a b ".to_string()));
+        });
+        assert_eq!(subject, r"CN=\ a b\ ");
+    }
+
+    #[test]
+    fn given_an_attribute_without_a_keyword_should_render_its_oid_and_hex_value() {
+        let subject = subject_of(|params| {
+            params.distinguished_name.push(
+                DnType::CustomDnType(vec![1, 2, 840, 113_549, 1, 9, 1]),
+                DnValue::Ia5String("alice@example.com".try_into().expect("ia5")),
+            );
+            params.distinguished_name.push(DnType::CommonName, "alice");
+        });
+        // 0x16 is IA5String, 0x11 its length.
+        assert_eq!(
+            subject,
+            "CN=alice,1.2.840.113549.1.9.1=#1611616c696365406578616d706c652e636f6d"
+        );
+    }
+
+    #[test]
+    fn given_the_default_rule_should_keep_the_subject() {
+        let rules: PrincipalMappingRules = "DEFAULT".parse().expect("valid");
+        assert_eq!(
+            rules.map("CN=alice,O=Example").as_deref(),
+            Some("CN=alice,O=Example")
+        );
+        assert_eq!(
+            PrincipalMappingRules::default().map("CN=alice").as_deref(),
+            Some("CN=alice")
+        );
+    }
+
+    #[test]
+    fn given_kafkas_documented_rules_should_extract_the_common_name() {
+        let rules: PrincipalMappingRules =
+            "RULE:^CN=(.*?),OU=ServiceUsers.*$/$1/,RULE:^CN=(.*?),OU=(.*?),O=(.*?),L=(.*?),\
+             ST=(.*?),C=(.*?)$/$1@$2/L,RULE:^.*[Cc][Nn]=([a-zA-Z0-9.]*).*$/$1/L,DEFAULT"
+                .parse()
+                .expect("Kafka's own example parses");
+        assert_eq!(
+            rules
+                .map("CN=serviceuser,OU=ServiceUsers,O=Unknown,L=Unknown,ST=Unknown,C=Unknown")
+                .as_deref(),
+            Some("serviceuser")
+        );
+        assert_eq!(
+            rules
+                .map("CN=adminUser,OU=Admin,O=Unknown,L=Unknown,ST=Unknown,C=Unknown")
+                .as_deref(),
+            Some("adminuser@admin")
+        );
+        assert_eq!(
+            rules.map("CN=kafka,O=Example").as_deref(),
+            Some("kafka"),
+            "the third rule lowercases the match"
+        );
+        assert_eq!(
+            rules.map("O=Example").as_deref(),
+            Some("O=Example"),
+            "DEFAULT catches what no rule matched"
+        );
+    }
+
+    #[test]
+    fn given_no_matching_rule_should_map_to_nothing() {
+        let rules: PrincipalMappingRules = "RULE:^CN=([^,]+).*$/$1/".parse().expect("valid");
+        assert_eq!(rules.map("O=Example"), None);
+        assert_eq!(rules.map("CN=alice,O=Example").as_deref(), Some("alice"));
+    }
+
+    #[test]
+    fn given_a_pattern_that_matches_the_whole_subject_only_should_require_the_whole_match() {
+        // `CN=([^,]+)` alone matches part of a longer subject; Java's `matches()` refuses that.
+        let rules: PrincipalMappingRules = "RULE:CN=([^,]+)/$1/".parse().expect("valid");
+        assert_eq!(rules.map("CN=alice").as_deref(), Some("alice"));
+        assert_eq!(rules.map("CN=alice,O=Example"), None);
+    }
+
+    #[test]
+    fn given_an_escaped_slash_should_keep_it_in_the_pattern_and_the_replacement() {
+        let rules: PrincipalMappingRules =
+            r"RULE:^CN=svc\/(.*)$/svc-$1\/x/U".parse().expect("valid");
+        assert_eq!(rules.map("CN=svc/alice").as_deref(), Some("SVC-ALICE/X"));
+    }
+
+    #[test]
+    fn given_java_replacement_syntax_should_expand_groups_and_escapes() {
+        let rules: PrincipalMappingRules = r"RULE:^CN=(\w+),OU=(\w+)$/$1-$2x\$lit\\/"
+            .parse()
+            .expect("valid");
+        assert_eq!(
+            rules.map("CN=alice,OU=eng").as_deref(),
+            Some(r"alice-engx$lit\")
+        );
+        let named: PrincipalMappingRules = r"RULE:^CN=(?P<user>\w+).*$/${user}/"
+            .parse()
+            .expect("valid");
+        assert_eq!(named.map("CN=bob,O=x").as_deref(), Some("bob"));
+    }
+
+    #[test]
+    fn given_a_malformed_rule_list_should_refuse() {
+        for raw in [
+            "",
+            "RULE:",
+            "RULE:^CN=(.*)$",
+            "RULE:^CN=(.*)$/$1",
+            "RULE:^CN=(.*)$/$1/X",
+            "DEFAULT,",
+            "DEFAULT DEFAULT",
+            "rule:a/b/",
+            "RULE:^CN=([/$1/",
+        ] {
+            assert!(
+                raw.parse::<PrincipalMappingRules>().is_err(),
+                "'{raw}' must be rejected"
+            );
+        }
+    }
+}
diff --git a/gateways/kafka/src/tls/mod.rs b/gateways/kafka/src/tls/mod.rs
new file mode 100644
index 000000000..85c3ef4f0
--- /dev/null
+++ b/gateways/kafka/src/tls/mod.rs
@@ -0,0 +1,505 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! TLS on the Kafka-facing listeners: the certificate, client authentication, reload without a
+//! restart, and the principal a client certificate carries.
+
+use std::fmt;
+use std::fs;
+use std::path::{Path, PathBuf};
+use std::str::FromStr;
+use std::sync::{Arc, Mutex, PoisonError};
+use std::time::Duration;
+
+use arc_swap::ArcSwap;
+use rustls::pki_types::pem::PemObject;
+use rustls::pki_types::{CertificateDer, PrivateKeyDer};
+use rustls::server::WebPkiClientVerifier;
+use rustls::{RootCertStore, ServerConfig, ServerConnection};
+use tokio_rustls::TlsAcceptor;
+use tokio_util::sync::CancellationToken;
+use tracing::{error, info};
+
+use crate::error::{KafkaProtocolError, Result};
+
+pub mod identity;
+
+pub use identity::{IdentityError, PrincipalMappingRules, subject_distinguished_name};
+
+/// How often the certificate files are re-read when nothing else is configured.
+///
+/// A minute is short against any rotation schedule and costs two small file reads.
+pub const DEFAULT_RELOAD_INTERVAL: Duration = Duration::from_secs(60);
+
+/// Kafka's `ssl.client.auth`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub enum ClientAuth {
+    /// No certificate is requested.
+    #[default]
+    None,
+    /// A certificate is requested and verified when presented; a client without one is admitted
+    /// anonymously.
+    Requested,
+    /// A client without a valid certificate fails the handshake.
+    Required,
+}
+
+impl ClientAuth {
+    #[must_use]
+    pub const fn is_enabled(self) -> bool {
+        !matches!(self, Self::None)
+    }
+
+    #[must_use]
+    pub const fn as_str(self) -> &'static str {
+        match self {
+            Self::None => "none",
+            Self::Requested => "requested",
+            Self::Required => "required",
+        }
+    }
+}
+
+impl FromStr for ClientAuth {
+    type Err = KafkaProtocolError;
+
+    fn from_str(raw: &str) -> Result<Self> {
+        match raw {
+            "none" => Ok(Self::None),
+            "requested" => Ok(Self::Requested),
+            "required" => Ok(Self::Required),
+            other => Err(KafkaProtocolError::InvalidConfig(format!(
+                "unknown client authentication mode '{other}'; expected none, requested or \
+                 required"
+            ))),
+        }
+    }
+}
+
+impl fmt::Display for ClientAuth {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.write_str(self.as_str())
+    }
+}
+
+/// TLS material and policy shared by every `SSL` and `SASL_SSL` listener.
+#[derive(Debug, Clone)]
+pub struct TlsConfig {
+    /// PEM certificate chain, leaf first.
+    pub cert_file: PathBuf,
+    /// PEM private key, PKCS#8, PKCS#1 or SEC1.
+    pub key_file: PathBuf,
+    pub client_auth: ClientAuth,
+    /// PEM roots client certificates must chain to. Required unless `client_auth` is `none`.
+    pub client_ca_file: Option<PathBuf>,
+    /// How a client certificate's subject becomes an Iggy username on an `SSL` listener.
+    pub principal_mapping: PrincipalMappingRules,
+    /// How often the files are re-read. Zero never re-reads them.
+    pub reload_interval: Duration,
+}
+
+impl TlsConfig {
+    #[must_use]
+    pub fn new(cert_file: impl Into<PathBuf>, key_file: impl Into<PathBuf>) -> Self {
+        Self {
+            cert_file: cert_file.into(),
+            key_file: key_file.into(),
+            client_auth: ClientAuth::None,
+            client_ca_file: None,
+            principal_mapping: PrincipalMappingRules::default(),
+            reload_interval: DEFAULT_RELOAD_INTERVAL,
+        }
+    }
+
+    #[must_use]
+    pub fn with_client_auth(mut self, mode: ClientAuth, ca_file: impl Into<PathBuf>) -> Self {
+        self.client_auth = mode;
+        self.client_ca_file = Some(ca_file.into());
+        self
+    }
+
+    #[must_use]
+    pub fn with_principal_mapping(mut self, rules: PrincipalMappingRules) -> Self {
+        self.principal_mapping = rules;
+        self
+    }
+
+    #[must_use]
+    pub const fn with_reload_interval(mut self, interval: Duration) -> Self {
+        self.reload_interval = interval;
+        self
+    }
+}
+
+/// The bytes last read from disk, kept so a reload can tell whether anything changed.
+#[derive(PartialEq, Eq)]
+struct Material {
+    certificate: Vec<u8>,
+    key: Vec<u8>,
+    client_ca: Option<Vec<u8>>,
+}
+
+impl Material {
+    fn read(config: &TlsConfig) -> Result<Self> {
+        Ok(Self {
+            certificate: read_file(&config.cert_file)?,
+            key: read_file(&config.key_file)?,
+            client_ca: config
+                .client_ca_file
+                .as_deref()
+                .map(read_file)
+                .transpose()?,
+        })
+    }
+}
+
+fn read_file(path: &Path) -> Result<Vec<u8>> {
+    fs::read(path).map_err(|error| {
+        KafkaProtocolError::InvalidConfig(format!("cannot read {}: {error}", path.display()))
+    })
+}
+
+/// The live TLS configuration, swapped under running listeners when the files change.
+///
+/// Every accept takes the configuration current at that moment, so a connection in flight keeps
+/// the material it handshook with and the next one gets the new material. Nothing waits on a
+/// lock in the accept path: the swap is an atomic pointer exchange.
+pub struct TlsState {
+    config: TlsConfig,
+    current: ArcSwap<ServerConfig>,
+    loaded: Mutex<Material>,
+}
+
+impl fmt::Debug for TlsState {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.debug_struct("TlsState")
+            .field("config", &self.config)
+            .finish_non_exhaustive()
+    }
+}
+
+impl TlsState {
+    /// Reads the files and builds the first configuration.
+    ///
+    /// # Errors
+    ///
+    /// Returns `InvalidConfig` when client authentication is on without a CA file, a file
+    /// cannot be read, or the material does not build a usable server configuration: no
+    /// certificate, an unparsable key, a key that does not match the certificate, or an
+    /// empty root store.
+    pub fn load(config: TlsConfig) -> Result<Self> {
+        if config.client_auth.is_enabled() && config.client_ca_file.is_none() {
+            return Err(KafkaProtocolError::InvalidConfig(format!(
+                "client authentication is '{}' but no client CA file is configured to verify \
+                 certificates against",
+                config.client_auth
+            )));
+        }
+        let material = Material::read(&config)?;
+        let server_config = build_server_config(&config, &material)?;
+        Ok(Self {
+            config,
+            current: ArcSwap::from_pointee(server_config),
+            loaded: Mutex::new(material),
+        })
+    }
+
+    #[must_use]
+    pub const fn config(&self) -> &TlsConfig {
+        &self.config
+    }
+
+    /// An acceptor over the configuration current right now.
+    #[must_use]
+    pub fn acceptor(&self) -> TlsAcceptor {
+        TlsAcceptor::from(self.current.load_full())
+    }
+
+    /// Re-reads the files and swaps the configuration if they changed.
+    ///
+    /// Returns `Ok(true)` when new material went live. A read or build failure leaves the current
+    /// material serving: a rotation that is half written, or a certificate that does not match
+    /// its key, must not take the listener down.
+    ///
+    /// # Errors
+    ///
+    /// The same conditions as [`Self::load`].
+    pub fn reload(&self) -> Result<bool> {
+        let material = Material::read(&self.config)?;
+        let unchanged = *self.loaded.lock().unwrap_or_else(PoisonError::into_inner) == material;
+        if unchanged {
+            return Ok(false);
+        }
+        let server_config = build_server_config(&self.config, &material)?;
+        self.current.store(Arc::new(server_config));
+        *self.loaded.lock().unwrap_or_else(PoisonError::into_inner) = material;
+        Ok(true)
+    }
+
+    /// Reloads on the configured interval until `cancel` fires.
+    pub async fn reload_until_cancelled(self: Arc<Self>, cancel: CancellationToken) {
+        let interval = self.config.reload_interval;
+        if interval.is_zero() {
+            return;
+        }
+        loop {
+            tokio::select! {
+                () = cancel.cancelled() => return,
+                () = tokio::time::sleep(interval) => {}
+            }
+            match self.reload() {
+                Ok(true) => info!(
+                    cert_file = %self.config.cert_file.display(),
+                    "TLS certificate reloaded; new connections use the new material"
+                ),
+                Ok(false) => {}
+                // error!, not warn!: an operator who rotated a certificate and sees this is
+                // about to serve an expired one, and nothing else will say so.
+                Err(error) => error!(
+                    %error,
+                    cert_file = %self.config.cert_file.display(),
+                    "TLS certificate reload failed; the previous material stays in use"
+                ),
+            }
+        }
+    }
+
+    /// The Iggy username the client certificate on `connection` names, or `None` when the client
+    /// presented no certificate.
+    ///
+    /// Only meaningful on an `SSL` listener. The chain was already verified by the handshake, so
+    /// what is read here is trusted; what can still fail is the subject naming no principal.
+    ///
+    /// # Errors
+    ///
+    /// Returns [`IdentityError`] when the leaf does not parse or no mapping rule matches it.
+    pub fn principal_name(
+        &self,
+        connection: &ServerConnection,
+    ) -> std::result::Result<Option<String>, IdentityError> {
+        let Some(leaf) = connection
+            .peer_certificates()
+            .and_then(|chain| chain.first())
+        else {
+            return Ok(None);
+        };
+        let subject = subject_distinguished_name(leaf)?;
+        self.config
+            .principal_mapping
+            .map(&subject)
+            .map(Some)
+            .ok_or(IdentityError::NoMatchingRule { subject })
+    }
+}
+
+fn build_server_config(config: &TlsConfig, material: &Material) -> Result<ServerConfig> {
+    // Named explicitly rather than taken from the process default: the Iggy SDK installs its own
+    // provider lazily on its first TLS dial, and a listener that came up first would otherwise
+    // decide for it, or panic because neither had chosen yet.
+    let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider());
+    let certificates = pem_certificates(&material.certificate, &config.cert_file)?;
+    if certificates.is_empty() {
+        return Err(KafkaProtocolError::InvalidConfig(format!(
+            "{} holds no certificate",
+            config.cert_file.display()
+        )));
+    }
+    let key = PrivateKeyDer::from_pem_slice(&material.key).map_err(|error| {
+        KafkaProtocolError::InvalidConfig(format!(
+            "{} holds no usable private key: {error}",
+            config.key_file.display()
+        ))
+    })?;
+    let builder = ServerConfig::builder_with_provider(Arc::clone(&provider))
+        .with_safe_default_protocol_versions()
+        .map_err(|error| KafkaProtocolError::InvalidConfig(error.to_string()))?;
+    let builder = match (
+        config.client_auth,
+        &material.client_ca,
+        &config.client_ca_file,
+    ) {
+        (ClientAuth::None, _, _) => builder.with_no_client_auth(),
+        (mode, Some(ca_pem), Some(ca_file)) => {
+            let mut roots = RootCertStore::empty();
+            for certificate in pem_certificates(ca_pem, ca_file)? {
+                roots.add(certificate).map_err(|error| {
+                    KafkaProtocolError::InvalidConfig(format!(
+                        "{} holds a certificate that cannot be a root: {error}",
+                        ca_file.display()
+                    ))
+                })?;
+            }
+            if roots.is_empty() {
+                return Err(KafkaProtocolError::InvalidConfig(format!(
+                    "{} holds no certificate",
+                    ca_file.display()
+                )));
+            }
+            let mut verifier =
+                WebPkiClientVerifier::builder_with_provider(Arc::new(roots), provider);
+            if mode == ClientAuth::Requested {
+                verifier = verifier.allow_unauthenticated();
+            }
+            let verifier = verifier
+                .build()
+                .map_err(|error| KafkaProtocolError::InvalidConfig(error.to_string()))?;
+            builder.with_client_cert_verifier(verifier)
+        }
+        // `load` refuses this combination before any material is read.
+        (mode, _, _) => {
+            return Err(KafkaProtocolError::InvalidConfig(format!(
+                "client authentication is '{mode}' but no client CA file is configured"
+            )));
+        }
+    };
+    builder
+        .with_single_cert(certificates, key)
+        .map_err(|error| {
+            KafkaProtocolError::InvalidConfig(format!(
+                "{} and {} do not form a usable certificate and key pair: {error}",
+                config.cert_file.display(),
+                config.key_file.display()
+            ))
+        })
+}
+
+fn pem_certificates(pem: &[u8], path: &Path) -> Result<Vec<CertificateDer<'static>>> {
+    CertificateDer::pem_slice_iter(pem)
+        .collect::<std::result::Result<Vec<_>, _>>()
+        .map_err(|error| {
+            KafkaProtocolError::InvalidConfig(format!(
+                "{} is not a PEM certificate file: {error}",
+                path.display()
+            ))
+        })
+}
+
+#[cfg(test)]
+mod tests {
+    use rcgen::{CertificateParams, DnType, KeyPair};
+
+    use super::*;
+
+    fn self_signed(common_name: &str) -> (String, String) {
+        let key = KeyPair::generate().expect("generate a key");
+        let mut params =
+            CertificateParams::new(vec!["localhost".to_string()]).expect("valid params");
+        params
+            .distinguished_name
+            .push(DnType::CommonName, common_name);
+        let certificate = params.self_signed(&key).expect("self-sign");
+        (certificate.pem(), key.serialize_pem())
+    }
+
+    fn write(dir: &Path, name: &str, contents: &str) -> PathBuf {
+        let path = dir.join(name);
+        fs::write(&path, contents).expect("write test file");
+        path
+    }
+
+    #[test]
+    fn client_auth_parses_kafkas_spellings_only() {
+        assert_eq!("none".parse::<ClientAuth>().unwrap(), ClientAuth::None);
+        assert_eq!(
+            "requested".parse::<ClientAuth>().unwrap(),
+            ClientAuth::Requested
+        );
+        assert_eq!(
+            "required".parse::<ClientAuth>().unwrap(),
+            ClientAuth::Required
+        );
+        for raw in ["Required", "true", "", "optional"] {
+            assert!(
+                raw.parse::<ClientAuth>().is_err(),
+                "'{raw}' must be rejected"
+            );
+        }
+    }
+
+    #[test]
+    fn given_a_certificate_and_key_should_load_and_report_no_change_on_reload() {
+        let dir = tempfile::tempdir().expect("tempdir");
+        let (cert, key) = self_signed("first");
+        let cert_file = write(dir.path(), "cert.pem", &cert);
+        let key_file = write(dir.path(), "key.pem", &key);
+        let state = TlsState::load(TlsConfig::new(cert_file, key_file)).expect("loads");
+        assert!(!state.reload().expect("reload reads the same files"));
+    }
+
+    #[test]
+    fn given_rotated_files_should_swap_and_keep_the_old_material_on_a_broken_rotation() {
+        let dir = tempfile::tempdir().expect("tempdir");
+        let (cert, key) = self_signed("first");
+        let cert_file = write(dir.path(), "cert.pem", &cert);
+        let key_file = write(dir.path(), "key.pem", &key);
+        let state = TlsState::load(TlsConfig::new(&cert_file, &key_file)).expect("loads");
+        let before = state.current.load_full();
+
+        // The certificate is rewritten first and the key later, as a non-atomic rotation does.
+        let (next_cert, next_key) = self_signed("second");
+        fs::write(&cert_file, &next_cert).expect("rotate certificate");
+        let error = state
+            .reload()
+            .expect_err("a certificate that does not match the key must not go live");
+        assert!(error.to_string().contains("pair"), "got: {error}");
+        assert!(
+            Arc::ptr_eq(&before, &state.current.load_full()),
+            "the previous material keeps serving"
+        );
+
+        fs::write(&key_file, &next_key).expect("rotate key");
+        assert!(state.reload().expect("the completed rotation loads"));
+        assert!(!Arc::ptr_eq(&before, &state.current.load_full()));
+        assert!(!state.reload().expect("nothing changed since"));
+    }
+
+    #[test]
+    fn given_client_auth_without_a_ca_should_refuse_to_load() {
+        let dir = tempfile::tempdir().expect("tempdir");
+        let (cert, key) = self_signed("first");
+        let cert_file = write(dir.path(), "cert.pem", &cert);
+        let key_file = write(dir.path(), "key.pem", &key);
+        let mut config = TlsConfig::new(cert_file, key_file);
+        config.client_auth = ClientAuth::Required;
+        let error = TlsState::load(config).unwrap_err().to_string();
+        assert!(error.contains("required"), "got: {error}");
+    }
+
+    #[test]
+    fn given_unreadable_or_empty_files_should_name_the_file() {
+        let dir = tempfile::tempdir().expect("tempdir");
+        let (cert, key) = self_signed("first");
+        let key_file = write(dir.path(), "key.pem", &key);
+        let missing = dir.path().join("missing.pem");
+        let error = TlsState::load(TlsConfig::new(&missing, &key_file))
+            .unwrap_err()
+            .to_string();
+        assert!(error.contains("missing.pem"), "got: {error}");
+
+        let empty = write(dir.path(), "empty.pem", "");
+        let error = TlsState::load(TlsConfig::new(&empty, &key_file))
+            .unwrap_err()
+            .to_string();
+        assert!(error.contains("empty.pem"), "got: {error}");
+
+        let cert_file = write(dir.path(), "cert.pem", &cert);
+        let error = TlsState::load(TlsConfig::new(&cert_file, &empty))
+            .unwrap_err()
+            .to_string();
+        assert!(error.contains("empty.pem"), "got: {error}");
+    }
+}
diff --git a/gateways/kafka/tests/bridge_iggy_integration_tests.rs b/gateways/kafka/tests/bridge_iggy_integration_tests.rs
index 51af8ba70..371d4cbac 100644
--- a/gateways/kafka/tests/bridge_iggy_integration_tests.rs
+++ b/gateways/kafka/tests/bridge_iggy_integration_tests.rs
@@ -30,15 +30,47 @@ use secrecy::SecretString;
 use serial_test::serial;
 
 use iggy_gateway_kafka::bridge::{
-    BridgeError, DEFAULT_MAX_MESSAGE_SIZE, IggyBridge, IggyBridgeConfig, TopicMapping,
+    BridgeError, DEFAULT_MAX_MESSAGE_SIZE, IggyBridge, IggyBridgeConfig, IggyTls, TopicMapping,
     TopicOverride,
 };
 
+#[path = "common/certs.rs"]
+mod certs;
 #[path = "common/iggy_server.rs"]
 mod iggy_server;
 
+use certs::TestPki;
 use iggy_server::{PortGuard, TestServer, raw_client};
 
+/// The bridge's own hop to Iggy encrypted: a server that speaks only TLS on its TCP port, and
+/// a bridge told to trust the CA that signed it. Produce and Fetch go through this client, so
+/// a bridge that silently stayed in the clear would fail to connect at all.
+#[tokio::test]
+#[serial]
+async fn given_a_tls_only_server_when_the_bridge_dials_over_tls_should_provision_topics() {
+    let data_dir = tempfile::tempdir().expect("tempdir");
+    let certs_dir = tempfile::tempdir().expect("certs dir");
+    let pki = TestPki::new();
+    let (cert_file, key_file) = pki.server_cert("iggy").write(certs_dir.path(), "server");
+    let ca_file = pki.write_ca(certs_dir.path());
+    let server = TestServer::spawn_with_tls(data_dir.path(), &cert_file, &key_file).await;
+
+    let mut config = server.test_config();
+    config.tls = IggyTls {
+        enabled: true,
+        domain: String::new(),
+        ca_file: Some(ca_file.display().to_string()),
+    };
+    let bridge = IggyBridge::connect(config)
+        .await
+        .expect("the bridge connects to a TLS-only server over TLS");
+    bridge
+        .ensure_stream_and_topic("orders", 2)
+        .await
+        .expect("a call on the TLS session succeeds");
+    bridge.close().await.expect("clean close");
+}
+
 #[tokio::test]
 #[serial]
 async fn ensure_stream_and_topic_is_idempotent_on_repeated_calls() {
@@ -394,6 +426,7 @@ async fn connect_to_unreachable_iggy_returns_err_not_panic() {
         topic_mapping: TopicMapping::new("kafka".to_string(), HashMap::new())
             .expect("valid mapping for this test's fixture data"),
         max_message_size: DEFAULT_MAX_MESSAGE_SIZE,
+        tls: IggyTls::default(),
     };
 
     let result = IggyBridge::connect(config).await;
@@ -418,6 +451,7 @@ async fn connect_to_a_black_hole_address_times_out_instead_of_hanging() {
         topic_mapping: TopicMapping::new("kafka".to_string(), HashMap::new())
             .expect("valid mapping for this test's fixture data"),
         max_message_size: DEFAULT_MAX_MESSAGE_SIZE,
+        tls: IggyTls::default(),
     };
 
     let start = tokio::time::Instant::now();
diff --git a/gateways/kafka/tests/broker_advertise_tests.rs b/gateways/kafka/tests/broker_advertise_tests.rs
index fc8b6c6e4..90f705e3b 100644
--- a/gateways/kafka/tests/broker_advertise_tests.rs
+++ b/gateways/kafka/tests/broker_advertise_tests.rs
@@ -22,7 +22,7 @@ mod codec;
 
 use std::net::SocketAddr;
 
-use iggy_gateway_kafka::GatewayConfig;
+use iggy_gateway_kafka::listener::{ListenerConfig, SecurityProtocol};
 use iggy_gateway_kafka::protocol::api::{API_KEY_METADATA, BrokerAdvertise, handle_request};
 
 use codec::{Decoder, Encoder};
@@ -56,63 +56,48 @@ async fn metadata_reflects_broker_addr() {
 }
 
 #[test]
-fn from_server_config_uses_explicit_advertised_host_on_wildcard_bind() {
-    let config = GatewayConfig {
-        bind_addr: "0.0.0.0:9093".to_string(),
-        advertised_host: Some("kafka.internal".to_string()),
-        ..GatewayConfig::default()
-    };
+fn for_listener_uses_explicit_advertised_host_on_wildcard_bind() {
+    let mut listener = ListenerConfig::new(SecurityProtocol::Plaintext, "0.0.0.0:9093");
+    listener.advertised_host = Some("kafka.internal".to_string());
     let local_addr: SocketAddr = "0.0.0.0:9093".parse().unwrap();
-    let broker = BrokerAdvertise::from_server_config(&config, local_addr).expect("valid config");
+    let broker = BrokerAdvertise::for_listener(&listener, local_addr).expect("valid config");
     assert_eq!(broker.host, "kafka.internal");
     assert_eq!(broker.port, 9093);
 }
 
 #[test]
-fn from_server_config_rejects_wildcard_bind_without_advertised_host() {
-    let config = GatewayConfig {
-        bind_addr: "0.0.0.0:9093".to_string(),
-        ..GatewayConfig::default()
-    };
+fn for_listener_rejects_wildcard_bind_without_advertised_host() {
+    let listener = ListenerConfig::new(SecurityProtocol::Plaintext, "0.0.0.0:9093");
     let local_addr: SocketAddr = "0.0.0.0:9093".parse().unwrap();
-    let err = BrokerAdvertise::from_server_config(&config, local_addr).unwrap_err();
+    let err = BrokerAdvertise::for_listener(&listener, local_addr).unwrap_err();
     assert!(err.to_string().contains("IGGY_KAFKA_ADVERTISED_HOST"));
+    assert!(err.to_string().contains("IGGY_KAFKA_ADVERTISED_LISTENERS"));
 }
 
 #[test]
-fn from_server_config_uses_bind_ip_for_non_wildcard_listener() {
-    let config = GatewayConfig {
-        bind_addr: "192.168.1.10:19092".to_string(),
-        ..GatewayConfig::default()
-    };
+fn for_listener_uses_bind_ip_for_non_wildcard_listener() {
+    let listener = ListenerConfig::new(SecurityProtocol::Plaintext, "192.168.1.10:19092");
     let local_addr: SocketAddr = "192.168.1.10:19092".parse().unwrap();
-    let broker = BrokerAdvertise::from_server_config(&config, local_addr).expect("valid config");
+    let broker = BrokerAdvertise::for_listener(&listener, local_addr).expect("valid config");
     assert_eq!(broker.host, "192.168.1.10");
     assert_eq!(broker.port, 19092);
 }
 
 #[test]
-fn from_server_config_rejects_advertised_host_exceeding_kafka_string_limit() {
-    let config = GatewayConfig {
-        bind_addr: "127.0.0.1:9093".to_string(),
-        advertised_host: Some("x".repeat(i16::MAX as usize + 1)),
-        ..GatewayConfig::default()
-    };
+fn for_listener_rejects_advertised_host_exceeding_kafka_string_limit() {
+    let mut listener = ListenerConfig::new(SecurityProtocol::Plaintext, "127.0.0.1:9093");
+    listener.advertised_host = Some("x".repeat(i16::MAX as usize + 1));
     let local_addr: SocketAddr = "127.0.0.1:9093".parse().unwrap();
-    let err = BrokerAdvertise::from_server_config(&config, local_addr).unwrap_err();
+    let err = BrokerAdvertise::for_listener(&listener, local_addr).unwrap_err();
     assert!(err.to_string().contains("IGGY_KAFKA_ADVERTISED_HOST"));
 }
 
 #[test]
-fn from_server_config_honors_advertised_port_override() {
-    let config = GatewayConfig {
-        bind_addr: "127.0.0.1:9093".to_string(),
-        advertised_host: Some("broker.example.com".to_string()),
-        advertised_port: Some(19093),
-        ..GatewayConfig::default()
-    };
+fn for_listener_honors_advertised_port_override() {
+    let listener = ListenerConfig::new(SecurityProtocol::Plaintext, "127.0.0.1:9093")
+        .with_advertised("broker.example.com", 19093);
     let local_addr: SocketAddr = "127.0.0.1:9093".parse().unwrap();
-    let broker = BrokerAdvertise::from_server_config(&config, local_addr).expect("valid config");
+    let broker = BrokerAdvertise::for_listener(&listener, local_addr).expect("valid config");
     assert_eq!(broker.host, "broker.example.com");
     assert_eq!(broker.port, 19093);
 }
diff --git a/gateways/kafka/tests/common/certs.rs b/gateways/kafka/tests/common/certs.rs
new file mode 100644
index 000000000..c7297fde9
--- /dev/null
+++ b/gateways/kafka/tests/common/certs.rs
@@ -0,0 +1,178 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! A throwaway PKI for the TLS suites, minted per test so nothing checked in can expire.
+//!
+//! Compiled into each integration test binary via `#[path]`.
+#![allow(dead_code)]
+
+use std::net::SocketAddr;
+use std::path::{Path, PathBuf};
+use std::sync::Arc;
+
+use rcgen::{
+    BasicConstraints, CertificateParams, DistinguishedName, DnType, ExtendedKeyUsagePurpose, IsCa,
+    Issuer, KeyPair,
+};
+use rustls::pki_types::pem::PemObject;
+use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName};
+use rustls::{ClientConfig, RootCertStore};
+use tokio::net::TcpStream;
+use tokio_rustls::TlsConnector;
+use tokio_rustls::client::TlsStream;
+
+/// A certificate and the key that goes with it, as PEM and as DER.
+pub struct Issued {
+    pub cert_pem: String,
+    pub key_pem: String,
+    pub der: Vec<u8>,
+}
+
+impl Issued {
+    /// Writes `<name>.pem` and `<name>.key` into `dir` and returns their paths.
+    pub fn write(&self, dir: &Path, name: &str) -> (PathBuf, PathBuf) {
+        let cert = dir.join(format!("{name}.pem"));
+        let key = dir.join(format!("{name}.key"));
+        std::fs::write(&cert, &self.cert_pem).expect("write certificate");
+        std::fs::write(&key, &self.key_pem).expect("write key");
+        (cert, key)
+    }
+
+    /// Both halves in one PEM file, the shape the Java client's PEM keystore reads.
+    pub fn write_bundle(&self, dir: &Path, name: &str) -> PathBuf {
+        let path = dir.join(format!("{name}.pem"));
+        std::fs::write(&path, format!("{}{}", self.key_pem, self.cert_pem)).expect("write bundle");
+        path
+    }
+}
+
+/// One CA that signs every certificate a test needs.
+pub struct TestPki {
+    pub ca_pem: String,
+    issuer: Issuer<'static, KeyPair>,
+}
+
+impl Default for TestPki {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl TestPki {
+    pub fn new() -> Self {
+        let key = KeyPair::generate().expect("generate a CA key");
+        let mut params = CertificateParams::new(Vec::<String>::new()).expect("CA params");
+        params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
+        params
+            .distinguished_name
+            .push(DnType::CommonName, "iggy kafka gateway test CA");
+        let certificate = params.self_signed(&key).expect("self-sign the CA");
+        Self {
+            ca_pem: certificate.pem(),
+            issuer: Issuer::new(params, key),
+        }
+    }
+
+    /// A server certificate for `localhost` and `127.0.0.1`, which is what every client here
+    /// dials and what a hostname-verifying Java client checks.
+    pub fn server_cert(&self, common_name: &str) -> Issued {
+        let mut params =
+            CertificateParams::new(vec!["localhost".to_string(), "127.0.0.1".to_string()])
+                .expect("server params");
+        params
+            .distinguished_name
+            .push(DnType::CommonName, common_name);
+        params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth];
+        self.issue(&params)
+    }
+
+    /// A client certificate whose subject is `CN=<common_name>,O=<organization>`.
+    pub fn client_cert(&self, common_name: &str, organization: &str) -> Issued {
+        self.client_cert_with_subject(|subject| {
+            subject.push(DnType::OrganizationName, organization);
+            subject.push(DnType::CommonName, common_name);
+        })
+    }
+
+    /// A client certificate with whatever subject `build` assembles, in certificate order: least
+    /// specific first, the way a CA writes it. rcgen seeds every subject with a common name,
+    /// which would otherwise land first.
+    pub fn client_cert_with_subject(&self, build: impl FnOnce(&mut DistinguishedName)) -> Issued {
+        let mut params = CertificateParams::new(Vec::<String>::new()).expect("client params");
+        params.distinguished_name = DistinguishedName::new();
+        build(&mut params.distinguished_name);
+        params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth];
+        self.issue(&params)
+    }
+
+    fn issue(&self, params: &CertificateParams) -> Issued {
+        let key = KeyPair::generate().expect("generate a key");
+        let certificate = params.signed_by(&key, &self.issuer).expect("sign");
+        Issued {
+            cert_pem: certificate.pem(),
+            key_pem: key.serialize_pem(),
+            der: certificate.der().to_vec(),
+        }
+    }
+
+    /// Writes the CA certificate into `dir` and returns its path.
+    pub fn write_ca(&self, dir: &Path) -> PathBuf {
+        let path = dir.join("ca.pem");
+        std::fs::write(&path, &self.ca_pem).expect("write CA");
+        path
+    }
+
+    /// A rustls client that trusts this CA, presenting `client` when given one.
+    pub fn client_config(&self, client: Option<&Issued>) -> Arc<ClientConfig> {
+        let mut roots = RootCertStore::empty();
+        for certificate in CertificateDer::pem_slice_iter(self.ca_pem.as_bytes()) {
+            roots
+                .add(certificate.expect("CA PEM parses"))
+                .expect("CA is a root");
+        }
+        let builder = ClientConfig::builder_with_provider(Arc::new(
+            rustls::crypto::aws_lc_rs::default_provider(),
+        ))
+        .with_safe_default_protocol_versions()
+        .expect("default protocol versions")
+        .with_root_certificates(roots);
+        let config = match client {
+            Some(issued) => {
+                let chain = CertificateDer::pem_slice_iter(issued.cert_pem.as_bytes())
+                    .collect::<Result<Vec<_>, _>>()
+                    .expect("client certificate parses");
+                let key = PrivateKeyDer::from_pem_slice(issued.key_pem.as_bytes())
+                    .expect("client key parses");
+                builder
+                    .with_client_auth_cert(chain, key)
+                    .expect("client certificate and key match")
+            }
+            None => builder.with_no_client_auth(),
+        };
+        Arc::new(config)
+    }
+}
+
+/// Opens a TLS connection to `addr` as `localhost`, with `config`.
+pub async fn connect_tls(
+    addr: SocketAddr,
+    config: Arc<ClientConfig>,
+) -> Result<TlsStream<TcpStream>, std::io::Error> {
+    let tcp = TcpStream::connect(addr).await?;
+    let server_name = ServerName::try_from("localhost").expect("valid server name");
+    TlsConnector::from(config).connect(server_name, tcp).await
+}
diff --git a/gateways/kafka/tests/common/iggy_server.rs b/gateways/kafka/tests/common/iggy_server.rs
index 51cc9a746..6ed6433c3 100644
--- a/gateways/kafka/tests/common/iggy_server.rs
+++ b/gateways/kafka/tests/common/iggy_server.rs
@@ -33,7 +33,9 @@ use std::time::Duration;
 use iggy::prelude::{AutoLogin, Client, Credentials, IggyClient, IggyClientBuilder};
 use secrecy::SecretString;
 
-use iggy_gateway_kafka::bridge::{DEFAULT_MAX_MESSAGE_SIZE, IggyBridgeConfig, TopicMapping};
+use iggy_gateway_kafka::bridge::{
+    DEFAULT_MAX_MESSAGE_SIZE, IggyBridgeConfig, IggyTls, TopicMapping,
+};
 
 /// Desired slot count - the actual count `port_band()` computes may be smaller if the machine's
 /// real ephemeral range leaves little room, but this crate never needs more than a handful live
@@ -259,6 +261,26 @@ impl TestServer {
     /// its assertions, orphaning a process that still holds its `PortGuard` slot, which then
     /// fails the next test that draws that slot to bind.
     pub async fn spawn_with_password(data_dir: &std::path::Path, password: &str) -> Self {
+        Self::spawn_configured(data_dir, password, None).await
+    }
+
+    /// Spawns `iggy-server` whose TCP listener speaks only TLS, with the given PEM pair.
+    ///
+    /// The bridge under test then has to dial it over TLS, which is the one way to prove the
+    /// bridge's own `IggyTls` reaches the socket rather than only the credential check's.
+    pub async fn spawn_with_tls(
+        data_dir: &std::path::Path,
+        cert_file: &std::path::Path,
+        key_file: &std::path::Path,
+    ) -> Self {
+        Self::spawn_configured(data_dir, "iggy", Some((cert_file, key_file))).await
+    }
+
+    async fn spawn_configured(
+        data_dir: &std::path::Path,
+        password: &str,
+        tls: Option<(&std::path::Path, &std::path::Path)>,
+    ) -> Self {
         let port_guard = PortGuard::acquire();
         let address = format!("127.0.0.1:{}", port_guard.port);
 
@@ -300,6 +322,15 @@ impl TestServer {
             // attempt fails with "invalid credentials" no matter what this test passes.
             .env("IGGY_ROOT_USERNAME", "iggy")
             .env("IGGY_ROOT_PASSWORD", password);
+        if let Some((cert_file, key_file)) = tls {
+            // `self_signed` is off explicitly: left on, the server would still load an existing
+            // pair, but the test should fail loudly on a missing file rather than mint one.
+            command
+                .env("IGGY_TCP_TLS_ENABLED", "true")
+                .env("IGGY_TCP_TLS_SELF_SIGNED", "false")
+                .env("IGGY_TCP_TLS_CERT_FILE", cert_file)
+                .env("IGGY_TCP_TLS_KEY_FILE", key_file);
+        }
         let child = command.spawn().expect("spawn iggy-server");
 
         let mut server = Self {
@@ -332,6 +363,7 @@ impl TestServer {
             topic_mapping: TopicMapping::new("kafka".to_string(), HashMap::new())
                 .expect("valid mapping for this test's fixture data"),
             max_message_size: DEFAULT_MAX_MESSAGE_SIZE,
+            tls: IggyTls::default(),
         }
     }
 }
diff --git a/gateways/kafka/tests/common/server.rs b/gateways/kafka/tests/common/server.rs
index 64abee24b..7552ed23d 100644
--- a/gateways/kafka/tests/common/server.rs
+++ b/gateways/kafka/tests/common/server.rs
@@ -19,14 +19,14 @@
 #![allow(dead_code)]
 
 use std::net::SocketAddr;
+use std::sync::Arc;
 use std::time::Duration;
 
 use tokio::sync::broadcast;
 
-use std::sync::Arc;
-
 use iggy_gateway_kafka::auth::SaslAuthenticator;
-use iggy_gateway_kafka::server::bind_listener;
+use iggy_gateway_kafka::listener::{ListenerConfig, SecurityProtocol};
+use iggy_gateway_kafka::server::{BoundListener, bind_listener};
 use iggy_gateway_kafka::{GatewayConfig, KafkaGateway};
 
 /// Bind an ephemeral port, start `KafkaGateway`, return address + shutdown sender.
@@ -41,7 +41,10 @@ pub async fn spawn_test_server() -> (SocketAddr, broadcast::Sender<()>) {
     .await
 }
 
-/// Start `KafkaGateway` with explicit config (`bind_addr` overwritten with ephemeral port).
+/// Start `KafkaGateway` with explicit config, every listener rebound to an ephemeral port.
+///
+/// Returns the first listener's address: every suite but the TLS one runs a single listener.
+/// [`spawn_gateway`] hands back all of them.
 ///
 /// `bind_listener` is synchronous, so this function's own body has no `.await` left - kept
 /// `async` anyway (with the lint silenced) rather than churning every one of this suite's ~20
@@ -49,38 +52,51 @@ pub async fn spawn_test_server() -> (SocketAddr, broadcast::Sender<()>) {
 /// whose whole purpose is spawning an async task.
 #[allow(clippy::unused_async)]
 pub async fn spawn_test_server_with_config(
-    mut config: GatewayConfig,
+    config: GatewayConfig,
 ) -> (SocketAddr, broadcast::Sender<()>) {
-    // Routed through the same tuned bind path as `main` (deep accept backlog via socket2), not a
-    // bare `TcpListener::bind`, so integration tests actually exercise it.
-    let listener = bind_listener("127.0.0.1:0").expect("bind ephemeral port");
-    let addr = listener.local_addr().expect("local addr");
-
-    config.bind_addr = addr.to_string();
-    let (shutdown_tx, shutdown_rx) = broadcast::channel(1);
-    let server = KafkaGateway::new(config);
-    tokio::spawn(async move {
-        let _ = server.run(listener, shutdown_rx).await;
-    });
-
-    (addr, shutdown_tx)
+    let (addrs, shutdown) = spawn_gateway(KafkaGateway::new, config);
+    (addrs[0], shutdown)
 }
 
 /// Same as [`spawn_test_server_with_config`], with a verifier attached for the SASL suites.
 #[allow(clippy::unused_async)]
 pub async fn spawn_test_server_with_authenticator(
-    mut config: GatewayConfig,
+    config: GatewayConfig,
     authenticator: Arc<dyn SaslAuthenticator>,
 ) -> (SocketAddr, broadcast::Sender<()>) {
-    let listener = bind_listener("127.0.0.1:0").expect("bind ephemeral port");
-    let addr = listener.local_addr().expect("local addr");
+    let (addrs, shutdown) = spawn_gateway(
+        |config| KafkaGateway::new(config).with_authenticator(authenticator),
+        config,
+    );
+    (addrs[0], shutdown)
+}
 
-    config.bind_addr = addr.to_string();
+/// Starts a gateway built by `build` from `config`, with every listener rebound to an ephemeral
+/// port. Returns the bound addresses in the order of `config.listeners`.
+pub fn spawn_gateway(
+    build: impl FnOnce(GatewayConfig) -> KafkaGateway,
+    mut config: GatewayConfig,
+) -> (Vec<SocketAddr>, broadcast::Sender<()>) {
+    // Routed through the same tuned bind path as `main` (deep accept backlog via socket2), not a
+    // bare `TcpListener::bind`, so integration tests actually exercise it.
+    let mut listeners = Vec::with_capacity(config.listeners.len());
+    let mut addrs = Vec::with_capacity(config.listeners.len());
+    for listener in &mut config.listeners {
+        let socket = bind_listener("127.0.0.1:0").expect("bind ephemeral port");
+        let addr = socket.local_addr().expect("local addr");
+        listener.bind_addr = addr.to_string();
+        addrs.push(addr);
+        listeners.push(BoundListener::new(listener.clone(), socket));
+    }
     let (shutdown_tx, shutdown_rx) = broadcast::channel(1);
-    let server = KafkaGateway::new(config).with_authenticator(authenticator);
+    let server = build(config);
     tokio::spawn(async move {
-        let _ = server.run(listener, shutdown_rx).await;
+        let _ = server.run(listeners, shutdown_rx).await;
     });
+    (addrs, shutdown_tx)
+}
 
-    (addr, shutdown_tx)
+/// One listener of `protocol`, on a port [`spawn_gateway`] picks.
+pub fn listener(protocol: SecurityProtocol) -> ListenerConfig {
+    ListenerConfig::new(protocol, "127.0.0.1:0")
 }
diff --git a/gateways/kafka/tests/common/tcp.rs b/gateways/kafka/tests/common/tcp.rs
index 64156d11a..142da2256 100644
--- a/gateways/kafka/tests/common/tcp.rs
+++ b/gateways/kafka/tests/common/tcp.rs
@@ -26,7 +26,7 @@ use std::net::SocketAddr;
 use std::time::Duration;
 
 use bytes::{BufMut, Bytes, BytesMut};
-use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt};
 use tokio::net::TcpStream;
 use tokio::time;
 
@@ -84,7 +84,7 @@ const DEFAULT_RESPONSE_TIMEOUT: Duration = Duration::from_secs(10);
 /// Read one length-prefixed response frame from the stream.
 ///
 /// Bounded by [`DEFAULT_RESPONSE_TIMEOUT`] so a dropped response fails fast instead of hanging.
-pub async fn read_response_frame(stream: &mut TcpStream, max_size: usize) -> Bytes {
+pub async fn read_response_frame<S: AsyncRead + Unpin>(stream: &mut S, max_size: usize) -> Bytes {
     time::timeout(
         DEFAULT_RESPONSE_TIMEOUT,
         read_response_frame_raw(stream, max_size),
@@ -97,7 +97,7 @@ pub async fn read_response_frame(stream: &mut TcpStream, max_size: usize) -> Byt
     })
 }
 
-async fn read_response_frame_raw(stream: &mut TcpStream, max_size: usize) -> Bytes {
+async fn read_response_frame_raw<S: AsyncRead + Unpin>(stream: &mut S, max_size: usize) -> Bytes {
     let mut len_buf = [0u8; 4];
     stream
         .read_exact(&mut len_buf)
@@ -177,8 +177,8 @@ pub fn build_metadata_legacy_request(topic_names: &[&str]) -> Bytes {
 }
 
 /// Read one length-prefixed response frame, returning `None` on timeout.
-pub async fn read_response_frame_with_timeout(
-    stream: &mut TcpStream,
+pub async fn read_response_frame_with_timeout<S: AsyncRead + Unpin>(
+    stream: &mut S,
     max_size: usize,
     timeout: Duration,
 ) -> Option<Bytes> {
@@ -211,7 +211,10 @@ pub enum ByteRead {
 /// Read one byte, distinguishing a server-side close from an idle timeout so that
 /// "server must close the connection" tests can assert [`ByteRead::Closed`] explicitly
 /// instead of passing on a mere stall.
-pub async fn read_byte_with_timeout(stream: &mut TcpStream, timeout: Duration) -> ByteRead {
+pub async fn read_byte_with_timeout<S: AsyncRead + Unpin>(
+    stream: &mut S,
+    timeout: Duration,
+) -> ByteRead {
     let mut buf = [0u8; 1];
     match time::timeout(timeout, stream.read(&mut buf)).await {
         // 0 bytes = clean EOF; a reset / broken pipe is still a closed connection here.
diff --git a/gateways/kafka/tests/configs_handler_tests.rs b/gateways/kafka/tests/configs_handler_tests.rs
index f2da4f3bc..06499d692 100644
--- a/gateways/kafka/tests/configs_handler_tests.rs
+++ b/gateways/kafka/tests/configs_handler_tests.rs
@@ -49,10 +49,8 @@ const ALTER_VERSION: i16 = 2;
 
 fn state_without_bridge() -> GatewayState {
     GatewayState::new(
-        BrokerAdvertise::default(),
         None,
         8 * 1024 * 1024,
-        false,
         0,
         GroupCoordinator::new(GroupCoordinatorConfig::default(), CancellationToken::new()),
     )
diff --git a/gateways/kafka/tests/configs_java_client_tests.rs b/gateways/kafka/tests/configs_java_client_tests.rs
index 76ce7bd34..c36eef234 100644
--- a/gateways/kafka/tests/configs_java_client_tests.rs
+++ b/gateways/kafka/tests/configs_java_client_tests.rs
@@ -31,7 +31,8 @@ use std::time::{Duration, Instant};
 use tokio::sync::broadcast;
 
 use iggy_gateway_kafka::bridge::IggyBridge;
-use iggy_gateway_kafka::server::bind_listener;
+use iggy_gateway_kafka::listener::{ListenerConfig, SecurityProtocol};
+use iggy_gateway_kafka::server::{BoundListener, bind_listener};
 use iggy_gateway_kafka::{GatewayConfig, KafkaGateway};
 
 #[path = "common/iggy_server.rs"]
@@ -217,14 +218,14 @@ async fn spawn_gateway(server: &TestServer) -> SocketAddr {
         .expect("create topic");
     let listener = bind_listener("127.0.0.1:0").expect("bind");
     let addr = listener.local_addr().expect("local addr");
-    let gateway = KafkaGateway::new(GatewayConfig {
-        bind_addr: addr.to_string(),
-        ..GatewayConfig::default()
-    })
-    .with_bridge(Some(Arc::new(bridge)));
+    let listener = BoundListener::new(
+        ListenerConfig::new(SecurityProtocol::Plaintext, addr.to_string()),
+        listener,
+    );
+    let gateway = KafkaGateway::new(GatewayConfig::default()).with_bridge(Some(Arc::new(bridge)));
     let (shutdown, receiver) = broadcast::channel::<()>(1);
     tokio::spawn(async move {
-        let _ = gateway.run(listener, receiver).await;
+        let _ = gateway.run(vec![listener], receiver).await;
     });
     std::mem::forget(shutdown);
     addr
diff --git a/gateways/kafka/tests/configs_real_bridge_tests.rs b/gateways/kafka/tests/configs_real_bridge_tests.rs
index 7fa62837f..7bc06a564 100644
--- a/gateways/kafka/tests/configs_real_bridge_tests.rs
+++ b/gateways/kafka/tests/configs_real_bridge_tests.rs
@@ -36,8 +36,8 @@ use tokio_util::sync::CancellationToken;
 use iggy_gateway_kafka::bridge::IggyBridge;
 use iggy_gateway_kafka::group::{GroupCoordinator, GroupCoordinatorConfig};
 use iggy_gateway_kafka::protocol::api::{
-    BrokerAdvertise, ERROR_INVALID_CONFIG, ERROR_INVALID_REQUEST, ERROR_INVALID_TOPIC_EXCEPTION,
-    ERROR_NONE, ERROR_UNKNOWN_TOPIC_OR_PARTITION, GatewayState,
+    ERROR_INVALID_CONFIG, ERROR_INVALID_REQUEST, ERROR_INVALID_TOPIC_EXCEPTION, ERROR_NONE,
+    ERROR_UNKNOWN_TOPIC_OR_PARTITION, GatewayState,
 };
 use iggy_gateway_kafka::protocol::handlers::{alter_configs, describe_configs};
 
@@ -68,10 +68,8 @@ async fn connected_state(server: &TestServer) -> GatewayState {
         .await
         .expect("bridge connects");
     GatewayState::new(
-        BrokerAdvertise::default(),
         Some(Arc::new(bridge)),
         8 * 1024 * 1024,
-        false,
         0,
         GroupCoordinator::new(GroupCoordinatorConfig::default(), CancellationToken::new()),
     )
diff --git a/gateways/kafka/tests/consumer_group_tests.rs b/gateways/kafka/tests/consumer_group_tests.rs
index 30af75466..36bde8ce2 100644
--- a/gateways/kafka/tests/consumer_group_tests.rs
+++ b/gateways/kafka/tests/consumer_group_tests.rs
@@ -83,10 +83,8 @@ fn test_state(config: GroupCoordinatorConfig) -> Arc<GatewayState> {
 
 fn owned_state(config: GroupCoordinatorConfig, max_frame_size: usize) -> GatewayState {
     GatewayState::new(
-        BrokerAdvertise::default(),
         None,
         max_frame_size,
-        false,
         0,
         GroupCoordinator::new(config, CancellationToken::new()),
     )
diff --git a/gateways/kafka/tests/create_topics_real_bridge_tests.rs b/gateways/kafka/tests/create_topics_real_bridge_tests.rs
index b2470a55e..05a158ba7 100644
--- a/gateways/kafka/tests/create_topics_real_bridge_tests.rs
+++ b/gateways/kafka/tests/create_topics_real_bridge_tests.rs
@@ -38,9 +38,9 @@ use tokio_util::sync::CancellationToken;
 use iggy_gateway_kafka::bridge::IggyBridge;
 use iggy_gateway_kafka::group::{GroupCoordinator, GroupCoordinatorConfig};
 use iggy_gateway_kafka::protocol::api::{
-    BrokerAdvertise, ERROR_INVALID_CONFIG, ERROR_INVALID_PARTITIONS,
-    ERROR_INVALID_REPLICA_ASSIGNMENT, ERROR_INVALID_REQUEST, ERROR_INVALID_TOPIC_EXCEPTION,
-    ERROR_NONE, ERROR_POLICY_VIOLATION, ERROR_TOPIC_ALREADY_EXISTS, GatewayState,
+    ERROR_INVALID_CONFIG, ERROR_INVALID_PARTITIONS, ERROR_INVALID_REPLICA_ASSIGNMENT,
+    ERROR_INVALID_REQUEST, ERROR_INVALID_TOPIC_EXCEPTION, ERROR_NONE, ERROR_POLICY_VIOLATION,
+    ERROR_TOPIC_ALREADY_EXISTS, GatewayState,
 };
 use iggy_gateway_kafka::protocol::handlers::create_topics;
 
@@ -170,10 +170,8 @@ async fn connected_state(server: &TestServer) -> GatewayState {
         .await
         .expect("bridge should connect to a ready server");
     GatewayState::new(
-        BrokerAdvertise::default(),
         Some(Arc::new(bridge)),
         TEST_MAX_FRAME_SIZE,
-        false,
         0,
         GroupCoordinator::new(GroupCoordinatorConfig::default(), CancellationToken::new()),
     )
diff --git a/gateways/kafka/tests/delete_topics_real_bridge_tests.rs b/gateways/kafka/tests/delete_topics_real_bridge_tests.rs
index f125d3f2a..81adc88db 100644
--- a/gateways/kafka/tests/delete_topics_real_bridge_tests.rs
+++ b/gateways/kafka/tests/delete_topics_real_bridge_tests.rs
@@ -36,8 +36,8 @@ use tokio_util::sync::CancellationToken;
 use iggy_gateway_kafka::bridge::IggyBridge;
 use iggy_gateway_kafka::group::{GroupCoordinator, GroupCoordinatorConfig};
 use iggy_gateway_kafka::protocol::api::{
-    BrokerAdvertise, ERROR_INVALID_REQUEST, ERROR_NONE, ERROR_POLICY_VIOLATION,
-    ERROR_UNKNOWN_TOPIC_OR_PARTITION, GatewayState,
+    ERROR_INVALID_REQUEST, ERROR_NONE, ERROR_POLICY_VIOLATION, ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+    GatewayState,
 };
 use iggy_gateway_kafka::protocol::handlers::delete_topics;
 
@@ -104,10 +104,8 @@ async fn connected_state(server: &TestServer) -> GatewayState {
         .await
         .expect("bridge should connect to a ready server");
     GatewayState::new(
-        BrokerAdvertise::default(),
         Some(Arc::new(bridge)),
         TEST_MAX_FRAME_SIZE,
-        false,
         0,
         GroupCoordinator::new(GroupCoordinatorConfig::default(), CancellationToken::new()),
     )
diff --git a/gateways/kafka/tests/fetch_real_bridge_tests.rs b/gateways/kafka/tests/fetch_real_bridge_tests.rs
index 985969f0d..231520505 100644
--- a/gateways/kafka/tests/fetch_real_bridge_tests.rs
+++ b/gateways/kafka/tests/fetch_real_bridge_tests.rs
@@ -47,8 +47,8 @@ use tokio_util::sync::CancellationToken;
 use iggy_gateway_kafka::bridge::IggyBridge;
 use iggy_gateway_kafka::group::{GroupCoordinator, GroupCoordinatorConfig};
 use iggy_gateway_kafka::protocol::api::{
-    API_KEY_FETCH, API_KEY_PRODUCE, BrokerAdvertise, ConnectionState, GatewayState,
-    handle_connection_request, handle_request_bounded,
+    API_KEY_FETCH, API_KEY_PRODUCE, ConnectionState, GatewayState, handle_connection_request,
+    handle_request_bounded,
 };
 use iggy_gateway_kafka::records::{MAPPING_VERSION, TimestampWindow, VERSION_HEADER, to_iggy};
 
@@ -89,10 +89,8 @@ async fn gateway_with_topic(server: &TestServer, partitions: u32) -> GatewayStat
         .await
         .expect("the topic must exist before fetching from it");
     GatewayState::new(
-        BrokerAdvertise::default(),
         Some(Arc::new(bridge)),
         MAX_FRAME_SIZE,
-        false,
         0,
         GroupCoordinator::new(GroupCoordinatorConfig::default(), CancellationToken::new()),
     )
diff --git a/gateways/kafka/tests/idempotence_tests.rs b/gateways/kafka/tests/idempotence_tests.rs
index fec27abcb..5c1a54999 100644
--- a/gateways/kafka/tests/idempotence_tests.rs
+++ b/gateways/kafka/tests/idempotence_tests.rs
@@ -100,10 +100,8 @@ async fn init_producer_id(
 
 fn stub_state(instance_id: u16) -> GatewayState {
     GatewayState::new(
-        default_broker(),
         None,
         MAX_FRAME_SIZE,
-        false,
         instance_id,
         GroupCoordinator::new(GroupCoordinatorConfig::default(), CancellationToken::new()),
     )
@@ -375,9 +373,6 @@ async fn given_a_live_server_when_a_transactional_request_is_refused_should_keep
 async fn given_a_server_configured_with_an_instance_id_when_init_producer_id_should_reflect_it() {
     let instance_id = 0x0042u16;
     let (addr, _shutdown) = spawn_test_server_with_config(GatewayConfig {
-        bind_addr: String::new(),
-        advertised_host: None,
-        advertised_port: None,
         max_frame_size: MAX_FRAME_SIZE,
         max_connections: 1024,
         idle_timeout: Duration::from_secs(5),
diff --git a/gateways/kafka/tests/kafka_client_e2e_tests.rs b/gateways/kafka/tests/kafka_client_e2e_tests.rs
index ce835c239..ae1688e12 100644
--- a/gateways/kafka/tests/kafka_client_e2e_tests.rs
+++ b/gateways/kafka/tests/kafka_client_e2e_tests.rs
@@ -51,15 +51,20 @@ use tokio::task::JoinHandle;
 
 use iggy_gateway_kafka::auth::IggyAuthenticator;
 use iggy_gateway_kafka::bridge::{
-    DEFAULT_MAX_MESSAGE_SIZE, IggyBridge, IggyBridgeConfig, TopicMapping,
+    DEFAULT_MAX_MESSAGE_SIZE, IggyBridge, IggyBridgeConfig, IggyTls, TopicMapping,
 };
-use iggy_gateway_kafka::server::bind_listener;
+use iggy_gateway_kafka::listener::{ListenerConfig, SecurityProtocol};
+use iggy_gateway_kafka::server::{BoundListener, bind_listener};
 use iggy_gateway_kafka::{GatewayConfig, KafkaGateway};
 
+#[path = "common/certs.rs"]
+mod certs;
 #[path = "common/server.rs"]
 mod server;
 
-use server::spawn_test_server_with_authenticator;
+use certs::{Issued, TestPki};
+use iggy_gateway_kafka::tls::{ClientAuth, TlsConfig};
+use server::{spawn_gateway as spawn_listeners, spawn_test_server_with_authenticator};
 
 const KCAT_IMAGE: &str = "edenhill/kcat:1.7.1";
 const KAFKA_IMAGE: &str = "apache/kafka:3.9.0";
@@ -287,7 +292,10 @@ fn free_port() -> u16 {
 /// Starts the gateway with SASL on, verifying credentials against `iggy_address`.
 async fn spawn_gateway(iggy_address: &str) -> SocketAddr {
     let config = GatewayConfig {
-        sasl_enabled: true,
+        listeners: vec![ListenerConfig::new(
+            SecurityProtocol::SaslPlaintext,
+            "127.0.0.1:0",
+        )],
         ..GatewayConfig::default()
     };
     let authenticator = Arc::new(IggyAuthenticator::new(iggy_address.to_string()));
@@ -334,6 +342,7 @@ async fn start_bridged_gateway(server: &TestServer, topics: &[(&str, u32)]) -> B
         topic_mapping: TopicMapping::new("kafka".to_string(), HashMap::new())
             .expect("the default mapping is valid"),
         max_message_size: DEFAULT_MAX_MESSAGE_SIZE,
+        tls: IggyTls::default(),
     };
     let bridge = IggyBridge::connect(config)
         .await
@@ -346,14 +355,14 @@ async fn start_bridged_gateway(server: &TestServer, topics: &[(&str, u32)]) -> B
     }
     let listener = bind_listener("127.0.0.1:0").expect("bind ephemeral port");
     let addr = listener.local_addr().expect("local addr");
-    let config = GatewayConfig {
-        bind_addr: addr.to_string(),
-        ..GatewayConfig::default()
-    };
-    let gateway = KafkaGateway::new(config).with_bridge(Some(Arc::new(bridge)));
+    let listener = BoundListener::new(
+        ListenerConfig::new(SecurityProtocol::Plaintext, addr.to_string()),
+        listener,
+    );
+    let gateway = KafkaGateway::new(GatewayConfig::default()).with_bridge(Some(Arc::new(bridge)));
     let (shutdown, receiver) = broadcast::channel(1);
     let task = tokio::spawn(async move {
-        let _ = gateway.run(listener, receiver).await;
+        let _ = gateway.run(vec![listener], receiver).await;
     });
     BridgedGateway {
         addr,
@@ -1399,3 +1408,341 @@ fn records_by_partition(output: &[String]) -> BTreeMap<i64, Vec<i64>> {
     }
     read
 }
+
+/// The TLS-side stack: a bridged gateway with an `SSL` and a `SASL_SSL` listener, client
+/// certificates requested and mapped to Iggy users by common name, and the material every
+/// client needs on disk.
+struct TlsStack {
+    _server: TestServer,
+    ssl: SocketAddr,
+    sasl_ssl: SocketAddr,
+    _certs_dir: tempfile::TempDir,
+    ca_file: PathBuf,
+    /// A certificate whose common name is `TLS_USER`, an Iggy user the stack creates.
+    user_cert: Issued,
+    /// A certificate the CA signed for a name no Iggy user has.
+    stranger_cert: Issued,
+}
+
+/// The Iggy user a client certificate maps to. Created with a topic read so `DescribeAcls`
+/// renders a binding that names it.
+const TLS_USER: &str = "cert-alice";
+
+/// Brings up the TLS stack, or reports why it could not.
+async fn tls_stack() -> Option<TlsStack> {
+    let server = ready_server()?;
+    let token = root_token(&server.http_address);
+    create_user(
+        &server.http_address,
+        &token,
+        TLS_USER,
+        r#"{"global":{"manage_servers":false,"read_servers":false,"manage_users":false,
+           "read_users":false,"manage_streams":false,"read_streams":false,"manage_topics":false,
+           "read_topics":true,"poll_messages":false,"send_messages":false},"streams":null}"#,
+    );
+
+    let certs_dir = tempfile::tempdir().expect("certs dir");
+    let pki = TestPki::new();
+    let (cert_file, key_file) = pki.server_cert("gateway").write(certs_dir.path(), "server");
+    let ca_file = pki.write_ca(certs_dir.path());
+    let user_cert = pki.client_cert(TLS_USER, "Iggy");
+    let stranger_cert = pki.client_cert("nobody", "Iggy");
+
+    let bridge = IggyBridge::connect(IggyBridgeConfig {
+        address: server.address.clone(),
+        username: ROOT_USER.to_string(),
+        password: SecretString::from(ROOT_PASSWORD.to_string()),
+        topic_mapping: TopicMapping::new("kafka".to_string(), HashMap::new())
+            .expect("the default mapping is valid"),
+        max_message_size: DEFAULT_MAX_MESSAGE_SIZE,
+        tls: IggyTls::default(),
+    })
+    .await
+    .expect("the bridge connects to a ready server");
+    bridge
+        .ensure_stream_and_topic(TOPIC, 1)
+        .await
+        .expect("create the topic");
+    let authenticator = Arc::new(IggyAuthenticator::new(server.address.clone()));
+    let config = GatewayConfig {
+        listeners: vec![
+            ListenerConfig::new(SecurityProtocol::Ssl, "127.0.0.1:0"),
+            ListenerConfig::new(SecurityProtocol::SaslSsl, "127.0.0.1:0"),
+        ],
+        tls: Some(
+            TlsConfig::new(cert_file, key_file)
+                .with_client_auth(ClientAuth::Requested, &ca_file)
+                .with_principal_mapping("RULE:^CN=([^,]+).*$/$1/".parse().expect("valid rule")),
+        ),
+        ..GatewayConfig::default()
+    };
+    let (addrs, shutdown) = spawn_listeners(
+        move |config| {
+            KafkaGateway::new(config)
+                .with_bridge(Some(Arc::new(bridge)))
+                .with_authenticator(authenticator)
+        },
+        config,
+    );
+    // Held for the test's lifetime: dropping the sender shuts the gateway down mid-exchange.
+    std::mem::forget(shutdown);
+    Some(TlsStack {
+        _server: server,
+        ssl: addrs[0],
+        sasl_ssl: addrs[1],
+        _certs_dir: certs_dir,
+        ca_file,
+        user_cert,
+        stranger_cert,
+    })
+}
+
+impl TlsStack {
+    /// kcat against `addr` with `extra` librdkafka properties, trusting the stack's CA.
+    fn kcat_tls(&self, addr: SocketAddr, extra: &[&str], client: Option<&Issued>) -> ClientRun {
+        let dir = tempfile::tempdir().expect("client certs dir");
+        let mut args = vec![
+            "-b".to_string(),
+            addr.to_string(),
+            "-X".to_string(),
+            "ssl.ca.location=/tmp/certs/ca.pem".to_string(),
+        ];
+        let mut mounts = vec![(self.ca_file.display().to_string(), "/tmp/certs/ca.pem")];
+        let (cert_file, key_file) = client.map_or_else(
+            || (PathBuf::new(), PathBuf::new()),
+            |issued| issued.write(dir.path(), "client"),
+        );
+        if client.is_some() {
+            args.extend([
+                "-X".to_string(),
+                "ssl.certificate.location=/tmp/certs/client.pem".to_string(),
+                "-X".to_string(),
+                "ssl.key.location=/tmp/certs/client.key".to_string(),
+            ]);
+            mounts.push((cert_file.display().to_string(), "/tmp/certs/client.pem"));
+            mounts.push((key_file.display().to_string(), "/tmp/certs/client.key"));
+        }
+        for property in extra {
+            args.extend(["-X".to_string(), (*property).to_string()]);
+        }
+        args.push("-L".to_string());
+        let args: Vec<&str> = args.iter().map(String::as_str).collect();
+        let mounts: Vec<(&str, &str)> = mounts
+            .iter()
+            .map(|(host, guest)| (host.as_str(), *guest))
+            .collect();
+        run_client(KCAT_IMAGE, &args, &mounts)
+    }
+
+    /// Writes a Java client config for TLS with `extra` properties, plus the CA and, when
+    /// given, a PEM keystore. Returns the mounts the container needs.
+    fn java_tls_config(
+        &self,
+        extra: &str,
+        client: Option<&Issued>,
+    ) -> (tempfile::TempDir, Vec<(String, &'static str)>) {
+        let dir = tempfile::tempdir().expect("create config dir");
+        let mut mounts = vec![(self.ca_file.display().to_string(), "/tmp/certs/ca.pem")];
+        let mut properties = format!(
+            "ssl.truststore.type=PEM\n\
+             ssl.truststore.location=/tmp/certs/ca.pem\n\
+             request.timeout.ms={JAVA_CLIENT_TIMEOUT_MS}\n\
+             default.api.timeout.ms={JAVA_CLIENT_TIMEOUT_MS}\n\
+             {extra}\n"
+        );
+        if let Some(issued) = client {
+            let bundle = issued.write_bundle(dir.path(), "client");
+            mounts.push((bundle.display().to_string(), "/tmp/certs/client.pem"));
+            properties.push_str(
+                "ssl.keystore.type=PEM\n\
+                 ssl.keystore.location=/tmp/certs/client.pem\n",
+            );
+        }
+        let path = dir.path().join("client.properties");
+        std::fs::write(&path, properties).expect("write client config");
+        mounts.push((path.display().to_string(), "/tmp/client.properties"));
+        (dir, mounts)
+    }
+
+    fn java(
+        &self,
+        tool: &str,
+        addr: SocketAddr,
+        extra: &str,
+        client: Option<&Issued>,
+    ) -> ClientRun {
+        let (_dir, mounts) = self.java_tls_config(extra, client);
+        let mounts: Vec<(&str, &str)> = mounts
+            .iter()
+            .map(|(host, guest)| (host.as_str(), *guest))
+            .collect();
+        let bootstrap = addr.to_string();
+        let mut args = vec![
+            tool,
+            "--bootstrap-server",
+            &bootstrap,
+            "--command-config",
+            "/tmp/client.properties",
+        ];
+        if tool.ends_with("kafka-acls.sh") {
+            args.push("--list");
+        }
+        run_client(KAFKA_IMAGE, &args, &mounts)
+    }
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn given_an_ssl_listener_when_librdkafka_connects_with_ssl_should_serve_metadata() {
+    let Some(stack) = tls_stack().await else {
+        return;
+    };
+    let output = stack
+        .kcat_tls(stack.ssl, &["security.protocol=SSL"], None)
+        .expect_ran("kcat over SSL");
+    assert!(
+        output.contains("Metadata for all topics"),
+        "librdkafka must handshake against the gateway certificate and be served, got: {output}"
+    );
+    assert!(
+        output.contains(&format!("127.0.0.1:{}", stack.ssl.port())),
+        "the broker advertised must be the SSL listener the client used, got: {output}"
+    );
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn given_a_sasl_ssl_listener_when_librdkafka_authenticates_should_serve_metadata() {
+    let Some(stack) = tls_stack().await else {
+        return;
+    };
+    let sasl = |password: &str| {
+        stack.kcat_tls(
+            stack.sasl_ssl,
+            &[
+                "security.protocol=SASL_SSL",
+                "sasl.mechanisms=PLAIN",
+                &format!("sasl.username={ROOT_USER}"),
+                &format!("sasl.password={password}"),
+            ],
+            None,
+        )
+    };
+    let output = sasl(ROOT_PASSWORD).expect_ran("kcat over SASL_SSL");
+    assert!(
+        output.contains("Metadata for all topics"),
+        "librdkafka must authenticate inside TLS and be served, got: {output}"
+    );
+    assert!(
+        output.contains(&format!("127.0.0.1:{}", stack.sasl_ssl.port())),
+        "the broker advertised must be the SASL_SSL listener the client used, got: {output}"
+    );
+
+    // kcat exits non-zero here by design, so only its output is asserted.
+    let rejected = sasl("definitely-not-the-password").text();
+    assert!(
+        rejected.contains("Authentication failed"),
+        "a rejected credential must reach the client as an auth failure, got: {rejected}"
+    );
+    assert!(
+        !rejected.contains("Metadata for all topics"),
+        "nothing may be served to a rejected client"
+    );
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn given_a_client_certificate_when_librdkafka_connects_should_be_admitted_as_its_user() {
+    let Some(stack) = tls_stack().await else {
+        return;
+    };
+    let output = stack
+        .kcat_tls(
+            stack.ssl,
+            &["security.protocol=SSL"],
+            Some(&stack.user_cert),
+        )
+        .expect_ran("kcat with a client certificate");
+    assert!(
+        output.contains("Metadata for all topics"),
+        "a certificate naming an Iggy user must be admitted, got: {output}"
+    );
+
+    let stranger = stack.kcat_tls(
+        stack.ssl,
+        &["security.protocol=SSL"],
+        Some(&stack.stranger_cert),
+    );
+    assert!(
+        !stranger.text.contains("Metadata for all topics"),
+        "a certificate naming no Iggy user must not be served, got: {}",
+        stranger.text
+    );
+    assert!(
+        !stranger.succeeded,
+        "kcat must fail when the gateway closes on it, got: {}",
+        stranger.text
+    );
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn given_the_java_client_with_ssl_and_sasl_ssl_should_connect_through_both_listeners() {
+    let Some(stack) = tls_stack().await else {
+        return;
+    };
+    let ssl = stack
+        .java(
+            "/opt/kafka/bin/kafka-broker-api-versions.sh",
+            stack.ssl,
+            "security.protocol=SSL",
+            None,
+        )
+        .expect_ran("java client over SSL");
+    assert!(
+        ssl.contains(&format!("127.0.0.1:{}", stack.ssl.port())),
+        "the Java client reads Metadata and then dials the advertised SSL listener, got: {ssl}"
+    );
+    assert!(
+        ssl.contains("SaslHandshake(17): UNSUPPORTED"),
+        "an SSL listener advertises no SASL keys, got: {ssl}"
+    );
+
+    let sasl_ssl = stack
+        .java(
+            "/opt/kafka/bin/kafka-broker-api-versions.sh",
+            stack.sasl_ssl,
+            &format!(
+                "security.protocol=SASL_SSL\n\
+                 sasl.mechanism=PLAIN\n\
+                 sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule \
+                 required username=\"{ROOT_USER}\" password=\"{ROOT_PASSWORD}\";"
+            ),
+            None,
+        )
+        .expect_ran("java client over SASL_SSL");
+    assert!(
+        sasl_ssl.contains("SaslHandshake(17): 0 to 1")
+            && sasl_ssl.contains("SaslAuthenticate(36): 0 to 2"),
+        "the Java client must authenticate inside TLS and read the advertisement, got: {sasl_ssl}"
+    );
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn given_the_java_client_with_a_client_certificate_should_be_described_as_its_user() {
+    let Some(stack) = tls_stack().await else {
+        return;
+    };
+    let listing = stack
+        .java(
+            "/opt/kafka/bin/kafka-acls.sh",
+            stack.ssl,
+            "security.protocol=SSL",
+            Some(&stack.user_cert),
+        )
+        .expect_ran("java kafka-acls over mTLS");
+    assert!(
+        listing.contains(&format!("principal=User:{TLS_USER}")),
+        "the certificate's common name is the principal described, got: {listing}"
+    );
+    assert!(
+        grants(&listing, "TOPIC", "READ"),
+        "the mapped user's read_topics grant renders, got: {listing}"
+    );
+}
diff --git a/gateways/kafka/tests/list_offsets_real_bridge_tests.rs b/gateways/kafka/tests/list_offsets_real_bridge_tests.rs
index 25c28c4fc..99c776bc2 100644
--- a/gateways/kafka/tests/list_offsets_real_bridge_tests.rs
+++ b/gateways/kafka/tests/list_offsets_real_bridge_tests.rs
@@ -31,7 +31,7 @@ use tokio_util::sync::CancellationToken;
 use iggy_gateway_kafka::bridge::IggyBridge;
 use iggy_gateway_kafka::group::{GroupCoordinator, GroupCoordinatorConfig};
 use iggy_gateway_kafka::protocol::api::{
-    BrokerAdvertise, ERROR_NONE, ERROR_REQUEST_TIMED_OUT, ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+    ERROR_NONE, ERROR_REQUEST_TIMED_OUT, ERROR_UNKNOWN_TOPIC_OR_PARTITION,
     ERROR_UNSUPPORTED_FOR_MESSAGE_FORMAT, GatewayState,
 };
 use iggy_gateway_kafka::protocol::handlers::list_offsets;
@@ -171,10 +171,8 @@ async fn connected_state(server: &TestServer) -> (GatewayState, IggyBridge) {
         .await
         .expect("seed bridge should connect to a ready server");
     let state = GatewayState::new(
-        BrokerAdvertise::default(),
         Some(Arc::new(bridge)),
         TEST_MAX_FRAME_SIZE,
-        false,
         0,
         GroupCoordinator::new(GroupCoordinatorConfig::default(), CancellationToken::new()),
     );
diff --git a/gateways/kafka/tests/metadata_real_bridge_tests.rs b/gateways/kafka/tests/metadata_real_bridge_tests.rs
index 86ea39e7f..9a45bd8d4 100644
--- a/gateways/kafka/tests/metadata_real_bridge_tests.rs
+++ b/gateways/kafka/tests/metadata_real_bridge_tests.rs
@@ -31,7 +31,7 @@ use tokio_util::sync::CancellationToken;
 use iggy_gateway_kafka::bridge::{IggyBridge, TopicMapping, TopicOverride};
 use iggy_gateway_kafka::group::{GroupCoordinator, GroupCoordinatorConfig};
 use iggy_gateway_kafka::protocol::api::{
-    BrokerAdvertise, ERROR_NONE, ERROR_UNKNOWN_TOPIC_OR_PARTITION, GatewayState,
+    ConnectionState, ERROR_NONE, ERROR_UNKNOWN_TOPIC_OR_PARTITION, GatewayState,
 };
 use iggy_gateway_kafka::protocol::handlers::metadata;
 
@@ -145,7 +145,7 @@ fn expected_partitions(count: u32) -> Vec<PartitionEntry> {
 
 async fn send(state: &GatewayState, topics: Option<&[&str]>) -> Vec<TopicEntry> {
     let body = build_request(topics);
-    let outcome = metadata::handle(state, REQUEST_VERSION, body).await;
+    let outcome = metadata::handle(state, &ConnectionState::default(), REQUEST_VERSION, body).await;
     let resp_body = outcome.expect_response("Metadata request always answers");
     decode_topics(resp_body)
 }
@@ -158,10 +158,8 @@ async fn connected_state(server: &TestServer) -> (GatewayState, IggyBridge) {
         .await
         .expect("seed bridge should connect to a ready server");
     let state = GatewayState::new(
-        BrokerAdvertise::default(),
         Some(Arc::new(bridge)),
         TEST_MAX_FRAME_SIZE,
-        false,
         0,
         GroupCoordinator::new(GroupCoordinatorConfig::default(), CancellationToken::new()),
     );
@@ -280,10 +278,8 @@ async fn a_named_lookup_reports_the_kafka_side_name_through_a_topic_mapping_over
         .await
         .expect("bridge should connect to a ready server");
     let state = GatewayState::new(
-        BrokerAdvertise::default(),
         Some(Arc::new(bridge)),
         TEST_MAX_FRAME_SIZE,
-        false,
         0,
         GroupCoordinator::new(GroupCoordinatorConfig::default(), CancellationToken::new()),
     );
@@ -318,15 +314,19 @@ async fn a_response_projected_over_max_frame_size_closes_instead_of_answering()
     // 50 partitions * 64 bytes/partition (this crate's own conservative per-partition estimate)
     // = 3200 bytes, comfortably over a 512-byte max_frame_size.
     let tiny_state = GatewayState::new(
-        state.broker,
         state.bridge,
         512,
-        false,
         0,
         GroupCoordinator::new(GroupCoordinatorConfig::default(), CancellationToken::new()),
     );
     let body = build_request(Some(&["orders"]));
-    let outcome = metadata::handle(&tiny_state, REQUEST_VERSION, body).await;
+    let outcome = metadata::handle(
+        &tiny_state,
+        &ConnectionState::default(),
+        REQUEST_VERSION,
+        body,
+    )
+    .await;
     assert!(outcome.is_close(), "expected Close, got {outcome:?}");
 }
 
@@ -351,10 +351,8 @@ async fn an_all_topics_response_over_max_frame_size_truncates_instead_of_closing
     // = 3200 bytes, comfortably over a 512-byte max_frame_size - so the catalog as a whole cannot
     // fit, but neither topic's own partition count is malformed or attacker-shaped.
     let tiny_state = GatewayState::new(
-        state.broker,
         state.bridge,
         512,
-        false,
         0,
         GroupCoordinator::new(GroupCoordinatorConfig::default(), CancellationToken::new()),
     );
diff --git a/gateways/kafka/tests/offsets_real_bridge_tests.rs b/gateways/kafka/tests/offsets_real_bridge_tests.rs
index 83aea8418..3774843c4 100644
--- a/gateways/kafka/tests/offsets_real_bridge_tests.rs
+++ b/gateways/kafka/tests/offsets_real_bridge_tests.rs
@@ -36,9 +36,7 @@ use tokio_util::sync::CancellationToken;
 
 use iggy_gateway_kafka::bridge::{IggyBridge, OFFSET_GROUP_PREFIX};
 use iggy_gateway_kafka::group::{GroupCoordinator, GroupCoordinatorConfig};
-use iggy_gateway_kafka::protocol::api::{
-    BrokerAdvertise, ConnectionState, ERROR_NONE, GatewayState,
-};
+use iggy_gateway_kafka::protocol::api::{ConnectionState, ERROR_NONE, GatewayState};
 use iggy_gateway_kafka::protocol::handlers::{offset_commit, offset_fetch};
 
 use codec::Decoder;
@@ -61,10 +59,8 @@ async fn connected_state(server: &TestServer) -> GatewayState {
         .await
         .expect("bridge should connect to a ready server");
     GatewayState::new(
-        BrokerAdvertise::default(),
         Some(Arc::new(bridge)),
         TEST_MAX_FRAME_SIZE,
-        false,
         0,
         GroupCoordinator::new(GroupCoordinatorConfig::default(), CancellationToken::new()),
     )
diff --git a/gateways/kafka/tests/produce_real_bridge_tests.rs b/gateways/kafka/tests/produce_real_bridge_tests.rs
index 1db4ee69f..fb3e3071a 100644
--- a/gateways/kafka/tests/produce_real_bridge_tests.rs
+++ b/gateways/kafka/tests/produce_real_bridge_tests.rs
@@ -38,8 +38,8 @@ use tokio_util::sync::CancellationToken;
 use iggy_gateway_kafka::bridge::IggyBridge;
 use iggy_gateway_kafka::group::{GroupCoordinator, GroupCoordinatorConfig};
 use iggy_gateway_kafka::protocol::api::{
-    API_KEY_PRODUCE, BrokerAdvertise, ERROR_NONE, ERROR_NOT_LEADER_OR_FOLLOWER,
-    ERROR_UNKNOWN_TOPIC_OR_PARTITION, GatewayState, handle_request_bounded,
+    API_KEY_PRODUCE, ERROR_NONE, ERROR_NOT_LEADER_OR_FOLLOWER, ERROR_UNKNOWN_TOPIC_OR_PARTITION,
+    GatewayState, handle_request_bounded,
 };
 use iggy_gateway_kafka::records::{KEY_HEADER, MAPPING_VERSION, VERSION_HEADER, from_iggy};
 
@@ -74,10 +74,8 @@ async fn gateway_with_topic(server: &TestServer, partitions: u32) -> GatewayStat
         .await
         .expect("the topic must exist before producing to it");
     GatewayState::new(
-        BrokerAdvertise::default(),
         Some(Arc::new(bridge)),
         MAX_FRAME_SIZE,
-        false,
         0,
         GroupCoordinator::new(GroupCoordinatorConfig::default(), CancellationToken::new()),
     )
@@ -743,7 +741,7 @@ async fn given_an_idempotent_batch_sent_twice_when_handled_should_store_both_cop
 async fn given_no_bridge_when_handled_should_still_answer_the_retriable_stub() {
     // Every other suite drives this path, so a regression in it surfaces far from Produce.
     // Pinned here, next to the path that replaced it.
-    let state = GatewayState::stub(BrokerAdvertise::default(), MAX_FRAME_SIZE);
+    let state = GatewayState::stub(MAX_FRAME_SIZE);
     let entries = [(0, batch(&[record(0, None, b"v", &[])], Compression::None))];
 
     assert_eq!(
diff --git a/gateways/kafka/tests/sasl_tests.rs b/gateways/kafka/tests/sasl_tests.rs
index 476d0b84f..2c66f6217 100644
--- a/gateways/kafka/tests/sasl_tests.rs
+++ b/gateways/kafka/tests/sasl_tests.rs
@@ -33,6 +33,7 @@ use tokio::sync::SemaphorePermit;
 
 use iggy_gateway_kafka::GatewayConfig;
 use iggy_gateway_kafka::auth::{AuthError, AuthenticatedPrincipal, SaslAuthenticator};
+use iggy_gateway_kafka::listener::SecurityProtocol;
 use iggy_gateway_kafka::protocol::acl::PrincipalPermissions;
 use iggy_gateway_kafka::protocol::sasl::{MAX_PRE_AUTH_API_VERSIONS, PlainCredentials};
 
@@ -94,7 +95,7 @@ impl SaslAuthenticator for FixedCredentialAuthenticator {
 
 fn sasl_config() -> GatewayConfig {
     GatewayConfig {
-        sasl_enabled: true,
+        listeners: vec![server::listener(SecurityProtocol::SaslPlaintext)],
         idle_timeout: Duration::from_secs(5),
         read_timeout: Duration::from_secs(5),
         write_timeout: Duration::from_secs(5),
@@ -975,11 +976,14 @@ async fn given_sasl_enabled_without_an_authenticator_should_refuse_to_start() {
     // Driven through `run` directly: the shared spawn helper discards the Result, so a test
     // written against it would pass whatever this guard did.
     use iggy_gateway_kafka::KafkaGateway;
-    use iggy_gateway_kafka::server::bind_listener;
+    use iggy_gateway_kafka::server::{BoundListener, bind_listener};
 
     let listener = bind_listener("127.0.0.1:0").expect("bind ephemeral port");
+    let listener = BoundListener::new(server::listener(SecurityProtocol::SaslPlaintext), listener);
     let (_tx, rx) = tokio::sync::broadcast::channel(1);
-    let result = KafkaGateway::new(sasl_config()).run(listener, rx).await;
+    let result = KafkaGateway::new(sasl_config())
+        .run(vec![listener], rx)
+        .await;
     assert!(
         result.is_err(),
         "a gateway demanding SASL with nothing to verify against would reject every client"
@@ -991,9 +995,10 @@ async fn given_an_authenticator_without_sasl_enabled_should_refuse_to_start() {
     // The quieter half: a verifier attached while the flag is off serves everything
     // unauthenticated, with nothing in the log to say so.
     use iggy_gateway_kafka::KafkaGateway;
-    use iggy_gateway_kafka::server::bind_listener;
+    use iggy_gateway_kafka::server::{BoundListener, bind_listener};
 
     let listener = bind_listener("127.0.0.1:0").expect("bind ephemeral port");
+    let listener = BoundListener::new(server::listener(SecurityProtocol::Plaintext), listener);
     let (_tx, rx) = tokio::sync::broadcast::channel(1);
     let authenticator = Arc::new(FixedCredentialAuthenticator {
         username: "alice",
@@ -1001,12 +1006,12 @@ async fn given_an_authenticator_without_sasl_enabled_should_refuse_to_start() {
         permissions: PrincipalPermissions::default(),
     });
     let config = GatewayConfig {
-        sasl_enabled: false,
+        listeners: vec![server::listener(SecurityProtocol::Plaintext)],
         ..sasl_config()
     };
     let result = KafkaGateway::new(config)
         .with_authenticator(authenticator)
-        .run(listener, rx)
+        .run(vec![listener], rx)
         .await;
     assert!(
         result.is_err(),
diff --git a/gateways/kafka/tests/tls_listener_tests.rs b/gateways/kafka/tests/tls_listener_tests.rs
new file mode 100644
index 000000000..a922dd534
--- /dev/null
+++ b/gateways/kafka/tests/tls_listener_tests.rs
@@ -0,0 +1,677 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! The TLS listeners over a real socket: `SSL` and `SASL_SSL` beside `PLAINTEXT`, each
+//! advertising its own address, client certificates as Iggy identities, and certificate reload
+//! without a restart.
+//!
+//! A stub [`PrincipalResolver`] stands in for the bridge, so no Iggy server is needed; the
+//! certificate path against a real one is in `kafka_client_e2e_tests.rs`.
+
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+use async_trait::async_trait;
+use bytes::Bytes;
+use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt};
+use tokio::net::TcpStream;
+use tokio::sync::SemaphorePermit;
+
+use iggy_gateway_kafka::auth::{
+    AuthError, AuthenticatedPrincipal, PrincipalResolver, SaslAuthenticator,
+};
+use iggy_gateway_kafka::listener::SecurityProtocol;
+use iggy_gateway_kafka::protocol::acl::PrincipalPermissions;
+use iggy_gateway_kafka::protocol::sasl::PlainCredentials;
+use iggy_gateway_kafka::server::{BoundListener, bind_listener};
+use iggy_gateway_kafka::tls::{ClientAuth, TlsConfig};
+use iggy_gateway_kafka::{GatewayConfig, KafkaGateway};
+
+#[path = "common/certs.rs"]
+mod certs;
+#[path = "common/codec.rs"]
+mod codec;
+#[path = "common/server.rs"]
+mod server;
+#[path = "common/tcp.rs"]
+mod tcp;
+
+use certs::{Issued, TestPki, connect_tls};
+use codec::{Decoder, Encoder};
+use server::{listener, spawn_gateway};
+use tcp::{
+    ByteRead, build_metadata_legacy_request, build_request_frame, parse_response_payload,
+    read_byte_with_timeout, read_response_frame,
+};
+
+const API_KEY_METADATA: i16 = 3;
+const API_KEY_SASL_HANDSHAKE: i16 = 17;
+const API_KEY_API_VERSIONS: i16 = 18;
+const API_KEY_DESCRIBE_ACLS: i16 = 29;
+const API_KEY_SASL_AUTHENTICATE: i16 = 36;
+
+const ERROR_NONE: i16 = 0;
+const MAX_FRAME: usize = 8 * 1024 * 1024;
+
+const USERNAME: &str = "alice";
+const PASSWORD: &str = "s3cret";
+
+/// Every certificate a test needs, written where the gateway reads them.
+struct Pki {
+    authority: TestPki,
+    dir: tempfile::TempDir,
+    cert_file: std::path::PathBuf,
+    key_file: std::path::PathBuf,
+    ca_file: std::path::PathBuf,
+}
+
+impl Pki {
+    fn new() -> Self {
+        let pki = TestPki::new();
+        let dir = tempfile::tempdir().expect("tempdir");
+        let (cert_file, key_file) = pki.server_cert("gateway").write(dir.path(), "server");
+        let ca_file = pki.write_ca(dir.path());
+        Self {
+            authority: pki,
+            dir,
+            cert_file,
+            key_file,
+            ca_file,
+        }
+    }
+
+    fn tls(&self) -> TlsConfig {
+        TlsConfig::new(&self.cert_file, &self.key_file)
+    }
+
+    fn tls_with_client_auth(&self, mode: ClientAuth) -> TlsConfig {
+        self.tls().with_client_auth(mode, &self.ca_file)
+    }
+}
+
+/// Knows a fixed set of users, and remembers every name it was asked about.
+#[derive(Debug, Default)]
+struct KnownUsers {
+    users: HashMap<String, PrincipalPermissions>,
+    asked: Mutex<Vec<String>>,
+}
+
+impl KnownUsers {
+    fn with(username: &str, permissions: PrincipalPermissions) -> Arc<Self> {
+        let mut users = HashMap::new();
+        users.insert(username.to_string(), permissions);
+        Arc::new(Self {
+            users,
+            asked: Mutex::default(),
+        })
+    }
+
+    fn asked(&self) -> Vec<String> {
+        self.asked.lock().expect("not poisoned").clone()
+    }
+}
+
+#[async_trait]
+impl PrincipalResolver for KnownUsers {
+    async fn resolve(&self, username: &str) -> Result<AuthenticatedPrincipal, AuthError> {
+        self.asked
+            .lock()
+            .expect("not poisoned")
+            .push(username.to_string());
+        self.users
+            .get(username)
+            .map(|permissions| AuthenticatedPrincipal {
+                username: username.to_string(),
+                permissions: *permissions,
+                permissions_known: true,
+            })
+            .ok_or(AuthError::Rejected)
+    }
+}
+
+/// Accepts `USERNAME`/`PASSWORD` and nothing else.
+#[derive(Debug)]
+struct FixedCredentials;
+
+#[async_trait]
+impl SaslAuthenticator for FixedCredentials {
+    async fn authenticate(
+        &self,
+        credentials: &PlainCredentials,
+        _slot: SemaphorePermit<'_>,
+    ) -> Result<AuthenticatedPrincipal, AuthError> {
+        use secrecy::ExposeSecret;
+        if credentials.username == USERNAME && credentials.password.expose_secret() == PASSWORD {
+            Ok(AuthenticatedPrincipal {
+                username: credentials.username.clone(),
+                permissions: topic_reader(),
+                permissions_known: true,
+            })
+        } else {
+            Err(AuthError::Rejected)
+        }
+    }
+}
+
+fn topic_reader() -> PrincipalPermissions {
+    PrincipalPermissions {
+        read_topics: true,
+        poll_messages: true,
+        ..PrincipalPermissions::default()
+    }
+}
+
+fn quick_config(listeners: Vec<SecurityProtocol>, tls: Option<TlsConfig>) -> GatewayConfig {
+    GatewayConfig {
+        listeners: listeners.into_iter().map(listener).collect(),
+        tls,
+        idle_timeout: Duration::from_secs(5),
+        read_timeout: Duration::from_secs(5),
+        write_timeout: Duration::from_secs(5),
+        pre_auth_timeout: Duration::from_secs(5),
+        shutdown_drain_timeout: Duration::from_secs(5),
+        ..GatewayConfig::default()
+    }
+}
+
+/// Sends one request and returns the response body.
+async fn send<S: AsyncRead + AsyncWrite + Unpin>(
+    stream: &mut S,
+    api_key: i16,
+    api_version: i16,
+    body: &[u8],
+) -> Bytes {
+    let frame = build_request_frame(api_key, api_version, 7, Some("tls-test"), body);
+    stream.write_all(&frame).await.expect("write request");
+    let payload = read_response_frame(stream, MAX_FRAME).await;
+    let (_, body) = parse_response_payload(api_key, api_version, payload);
+    body
+}
+
+/// The advertised `(api_key, min, max)` rows of an `ApiVersions` v1 answer.
+async fn api_versions<S: AsyncRead + AsyncWrite + Unpin>(stream: &mut S) -> Vec<(i16, i16, i16)> {
+    let body = send(stream, API_KEY_API_VERSIONS, 1, &[]).await;
+    let mut decoder = Decoder::new(body);
+    assert_eq!(decoder.read_i16().expect("error code"), ERROR_NONE);
+    let count = decoder.read_i32().expect("count");
+    (0..count)
+        .map(|_| {
+            (
+                decoder.read_i16().expect("api key"),
+                decoder.read_i16().expect("min"),
+                decoder.read_i16().expect("max"),
+            )
+        })
+        .collect()
+}
+
+fn advertises(rows: &[(i16, i16, i16)], api_key: i16) -> bool {
+    rows.iter().any(|row| row.0 == api_key)
+}
+
+/// The broker `(host, port)` a Metadata v0 answer advertises.
+async fn advertised_broker<S: AsyncRead + AsyncWrite + Unpin>(stream: &mut S) -> (String, i32) {
+    let request = build_metadata_legacy_request(&[]);
+    let body = send(stream, API_KEY_METADATA, 0, &request).await;
+    let mut decoder = Decoder::new(body);
+    assert_eq!(decoder.read_i32().expect("broker count"), 1);
+    decoder.read_i32().expect("node id");
+    let host = decoder
+        .read_nullable_string()
+        .expect("host")
+        .expect("non-null host");
+    let port = decoder.read_i32().expect("port");
+    (host, port)
+}
+
+/// Runs the SASL/PLAIN exchange as `username`, returning the `SaslAuthenticate` error code.
+async fn sasl_plain<S: AsyncRead + AsyncWrite + Unpin>(
+    stream: &mut S,
+    username: &str,
+    password: &str,
+) -> i16 {
+    let mut handshake = Encoder::with_capacity(16);
+    handshake
+        .write_nullable_string(Some("PLAIN"))
+        .expect("mechanism");
+    let body = send(stream, API_KEY_SASL_HANDSHAKE, 1, &handshake.freeze()).await;
+    assert_eq!(
+        i16::from_be_bytes([body[0], body[1]]),
+        ERROR_NONE,
+        "handshake must accept PLAIN"
+    );
+
+    let mut token = vec![0u8];
+    token.extend_from_slice(username.as_bytes());
+    token.push(0);
+    token.extend_from_slice(password.as_bytes());
+    let mut authenticate = Encoder::with_capacity(64);
+    authenticate
+        .write_nullable_bytes(Some(&token))
+        .expect("token");
+    let body = send(stream, API_KEY_SASL_AUTHENTICATE, 1, &authenticate.freeze()).await;
+    i16::from_be_bytes([body[0], body[1]])
+}
+
+/// `DescribeAcls` v1 with a match-everything filter: the error code and the raw body.
+async fn describe_acls<S: AsyncRead + AsyncWrite + Unpin>(stream: &mut S) -> (i16, Bytes) {
+    let mut filter = Encoder::with_capacity(16);
+    filter.write_i8(1); // resource type ANY
+    filter.write_nullable_string(None).expect("name");
+    filter.write_i8(1); // pattern type ANY
+    filter.write_nullable_string(None).expect("principal");
+    filter.write_nullable_string(None).expect("host");
+    filter.write_i8(1); // operation ANY
+    filter.write_i8(1); // permission ANY
+    let body = send(stream, API_KEY_DESCRIBE_ACLS, 1, &filter.freeze()).await;
+    let mut decoder = Decoder::new(body.clone());
+    decoder.read_i32().expect("throttle");
+    (decoder.read_i16().expect("error code"), body)
+}
+
+fn mentions(body: &Bytes, text: &str) -> bool {
+    body.windows(text.len())
+        .any(|window| window == text.as_bytes())
+}
+
+#[tokio::test]
+async fn given_an_ssl_listener_when_a_tls_client_connects_should_be_served_without_sasl_keys() {
+    let pki = Pki::new();
+    let (addrs, _shutdown) = spawn_gateway(
+        KafkaGateway::new,
+        quick_config(vec![SecurityProtocol::Ssl], Some(pki.tls())),
+    );
+
+    let mut stream = connect_tls(addrs[0], pki.authority.client_config(None))
+        .await
+        .expect("TLS handshake against the gateway's certificate");
+    let rows = api_versions(&mut stream).await;
+    assert!(advertises(&rows, API_KEY_METADATA));
+    assert!(
+        !advertises(&rows, API_KEY_SASL_HANDSHAKE) && !advertises(&rows, API_KEY_SASL_AUTHENTICATE),
+        "an SSL listener runs no SASL exchange, got: {rows:?}"
+    );
+    assert!(
+        !advertises(&rows, API_KEY_DESCRIBE_ACLS),
+        "without client certificates an SSL listener names no principal, got: {rows:?}"
+    );
+}
+
+#[tokio::test]
+async fn given_several_listeners_when_asking_metadata_should_advertise_the_port_the_client_used() {
+    let pki = Pki::new();
+    let (addrs, _shutdown) = spawn_gateway(
+        |config| KafkaGateway::new(config).with_authenticator(Arc::new(FixedCredentials)),
+        quick_config(
+            vec![
+                SecurityProtocol::Plaintext,
+                SecurityProtocol::Ssl,
+                SecurityProtocol::SaslSsl,
+            ],
+            Some(pki.tls()),
+        ),
+    );
+    let [plaintext, ssl, sasl_ssl] = addrs[..] else {
+        panic!("three listeners")
+    };
+    assert!(plaintext != ssl && ssl != sasl_ssl);
+
+    let mut plain = TcpStream::connect(plaintext).await.expect("connect");
+    assert_eq!(
+        advertised_broker(&mut plain).await,
+        ("127.0.0.1".to_string(), i32::from(plaintext.port()))
+    );
+
+    let mut tls = connect_tls(ssl, pki.authority.client_config(None))
+        .await
+        .expect("TLS handshake");
+    assert_eq!(
+        advertised_broker(&mut tls).await,
+        ("127.0.0.1".to_string(), i32::from(ssl.port())),
+        "a TLS client pointed at the plaintext port would fail its next connection"
+    );
+
+    let mut authenticated = connect_tls(sasl_ssl, pki.authority.client_config(None))
+        .await
+        .expect("TLS handshake");
+    assert_eq!(
+        sasl_plain(&mut authenticated, USERNAME, PASSWORD).await,
+        ERROR_NONE
+    );
+    assert_eq!(
+        advertised_broker(&mut authenticated).await,
+        ("127.0.0.1".to_string(), i32::from(sasl_ssl.port()))
+    );
+}
+
+#[tokio::test]
+async fn given_an_ssl_listener_when_a_plaintext_client_connects_should_be_closed() {
+    let pki = Pki::new();
+    let (addrs, _shutdown) = spawn_gateway(
+        KafkaGateway::new,
+        quick_config(vec![SecurityProtocol::Ssl], Some(pki.tls())),
+    );
+
+    let mut stream = TcpStream::connect(addrs[0]).await.expect("connect");
+    let frame = build_request_frame(API_KEY_API_VERSIONS, 1, 1, Some("plaintext"), &[]);
+    stream.write_all(&frame).await.expect("write");
+    // A Kafka frame is not a ClientHello. rustls answers with a TLS alert record (content type
+    // 21) before closing, and either is a refusal; a Kafka frame starts with a length prefix
+    // whose first byte is 0 for any frame under 16 MiB.
+    let first = read_byte_with_timeout(&mut stream, Duration::from_secs(5)).await;
+    assert!(
+        matches!(first, ByteRead::Closed | ByteRead::Byte(21)),
+        "the gateway must not speak Kafka on the TLS port, got: {first:?}"
+    );
+}
+
+#[tokio::test]
+async fn given_a_sasl_ssl_listener_should_run_the_sasl_exchange_inside_tls() {
+    let pki = Pki::new();
+    let (addrs, _shutdown) = spawn_gateway(
+        |config| KafkaGateway::new(config).with_authenticator(Arc::new(FixedCredentials)),
+        quick_config(vec![SecurityProtocol::SaslSsl], Some(pki.tls())),
+    );
+
+    let mut stream = connect_tls(addrs[0], pki.authority.client_config(None))
+        .await
+        .expect("TLS handshake");
+    let rows = api_versions(&mut stream).await;
+    assert!(advertises(&rows, API_KEY_SASL_HANDSHAKE));
+    assert!(advertises(&rows, API_KEY_SASL_AUTHENTICATE));
+    assert!(advertises(&rows, API_KEY_DESCRIBE_ACLS));
+    assert_eq!(
+        sasl_plain(&mut stream, USERNAME, PASSWORD).await,
+        ERROR_NONE
+    );
+    let (code, body) = describe_acls(&mut stream).await;
+    assert_eq!(code, ERROR_NONE);
+    assert!(
+        mentions(&body, &format!("User:{USERNAME}")),
+        "the SASL principal is the one described"
+    );
+
+    let mut rejected = connect_tls(addrs[0], pki.authority.client_config(None))
+        .await
+        .expect("TLS handshake");
+    assert_ne!(
+        sasl_plain(&mut rejected, USERNAME, "wrong").await,
+        ERROR_NONE,
+        "a wrong password is still refused over TLS"
+    );
+}
+
+#[tokio::test]
+async fn given_required_client_auth_when_the_certificate_names_a_user_should_authenticate_as_it() {
+    let pki = Pki::new();
+    let users = KnownUsers::with(USERNAME, topic_reader());
+    let resolver = Arc::clone(&users);
+    let (addrs, _shutdown) = spawn_gateway(
+        move |config| KafkaGateway::new(config).with_principal_resolver(resolver),
+        quick_config(
+            vec![SecurityProtocol::Ssl],
+            Some(
+                pki.tls_with_client_auth(ClientAuth::Required)
+                    .with_principal_mapping("RULE:^CN=([^,]+).*$/$1/L".parse().expect("valid")),
+            ),
+        ),
+    );
+
+    let certificate = pki.authority.client_cert("Alice", "Example");
+    let mut stream = connect_tls(addrs[0], pki.authority.client_config(Some(&certificate)))
+        .await
+        .expect("mTLS handshake");
+    let rows = api_versions(&mut stream).await;
+    assert!(
+        advertises(&rows, API_KEY_DESCRIBE_ACLS),
+        "a listener that names principals advertises DescribeAcls, got: {rows:?}"
+    );
+    assert!(!advertises(&rows, API_KEY_SASL_HANDSHAKE));
+    let (code, body) = describe_acls(&mut stream).await;
+    assert_eq!(code, ERROR_NONE);
+    assert!(
+        mentions(&body, &format!("User:{USERNAME}")),
+        "the mapped, lowercased common name is the principal described"
+    );
+    assert_eq!(
+        users.asked(),
+        vec![USERNAME.to_string()],
+        "the mapping rule runs before the lookup, and the lookup happens once"
+    );
+}
+
+#[tokio::test]
+async fn given_required_client_auth_when_the_certificate_names_no_user_should_close() {
+    let pki = Pki::new();
+    let users = KnownUsers::with(USERNAME, topic_reader());
+    let (addrs, _shutdown) = spawn_gateway(
+        move |config| KafkaGateway::new(config).with_principal_resolver(users),
+        quick_config(
+            vec![SecurityProtocol::Ssl],
+            Some(
+                pki.tls_with_client_auth(ClientAuth::Required)
+                    .with_principal_mapping("RULE:^CN=([^,]+).*$/$1/".parse().expect("valid")),
+            ),
+        ),
+    );
+
+    let stranger = pki.authority.client_cert("mallory", "Example");
+    let mut stream = connect_tls(addrs[0], pki.authority.client_config(Some(&stranger)))
+        .await
+        .expect("the handshake itself succeeds: the CA signed the certificate");
+    let frame = build_request_frame(API_KEY_API_VERSIONS, 1, 1, Some("stranger"), &[]);
+    // The write may or may not land before the close; the read is the assertion.
+    let _ = stream.write_all(&frame).await;
+    assert_eq!(
+        read_byte_with_timeout(&mut stream, Duration::from_secs(5)).await,
+        ByteRead::Closed,
+        "a certificate for an account that does not exist admits nothing"
+    );
+}
+
+#[tokio::test]
+async fn given_required_client_auth_when_no_certificate_is_presented_should_fail_the_handshake() {
+    let pki = Pki::new();
+    let users = KnownUsers::with(USERNAME, topic_reader());
+    let (addrs, _shutdown) = spawn_gateway(
+        move |config| KafkaGateway::new(config).with_principal_resolver(users),
+        quick_config(
+            vec![SecurityProtocol::Ssl],
+            Some(pki.tls_with_client_auth(ClientAuth::Required)),
+        ),
+    );
+
+    // Under TLS 1.3 the client's side of the handshake completes before the server's
+    // `certificate_required` alert arrives, so the refusal shows on the first read.
+    let Ok(mut stream) = connect_tls(addrs[0], pki.authority.client_config(None)).await else {
+        return;
+    };
+    let frame = build_request_frame(API_KEY_API_VERSIONS, 1, 1, Some("anonymous"), &[]);
+    let _ = stream.write_all(&frame).await;
+    assert_eq!(
+        read_byte_with_timeout(&mut stream, Duration::from_secs(5)).await,
+        ByteRead::Closed,
+        "a client without a certificate must not be served on a listener that requires one"
+    );
+}
+
+#[tokio::test]
+async fn given_requested_client_auth_when_no_certificate_is_presented_should_serve_anonymously() {
+    let pki = Pki::new();
+    let users = KnownUsers::with(USERNAME, topic_reader());
+    let (addrs, _shutdown) = spawn_gateway(
+        move |config| KafkaGateway::new(config).with_principal_resolver(users),
+        quick_config(
+            vec![SecurityProtocol::Ssl],
+            Some(pki.tls_with_client_auth(ClientAuth::Requested)),
+        ),
+    );
+
+    let mut stream = connect_tls(addrs[0], pki.authority.client_config(None))
+        .await
+        .expect("a requested certificate may be withheld");
+    let rows = api_versions(&mut stream).await;
+    assert!(advertises(&rows, API_KEY_DESCRIBE_ACLS));
+    let (code, body) = describe_acls(&mut stream).await;
+    assert_eq!(
+        code, ERROR_NONE,
+        "Kafka's anonymous principal is described, not refused"
+    );
+    assert!(
+        !mentions(&body, "User:"),
+        "and it holds nothing, got a binding in: {body:?}"
+    );
+}
+
+#[tokio::test]
+async fn given_a_sasl_ssl_listener_with_client_auth_should_take_the_principal_from_sasl() {
+    let pki = Pki::new();
+    let users = KnownUsers::with("certificate-user", topic_reader());
+    let resolver = Arc::clone(&users);
+    let (addrs, _shutdown) = spawn_gateway(
+        move |config| {
+            KafkaGateway::new(config)
+                .with_authenticator(Arc::new(FixedCredentials))
+                .with_principal_resolver(resolver)
+        },
+        quick_config(
+            vec![SecurityProtocol::SaslSsl],
+            Some(
+                pki.tls_with_client_auth(ClientAuth::Required)
+                    .with_principal_mapping("RULE:^CN=([^,]+).*$/$1/".parse().expect("valid")),
+            ),
+        ),
+    );
+
+    let certificate = pki.authority.client_cert("certificate-user", "Example");
+    let mut stream = connect_tls(addrs[0], pki.authority.client_config(Some(&certificate)))
+        .await
+        .expect("mTLS handshake");
+    assert_eq!(
+        sasl_plain(&mut stream, USERNAME, PASSWORD).await,
+        ERROR_NONE
+    );
+    let (code, body) = describe_acls(&mut stream).await;
+    assert_eq!(code, ERROR_NONE);
+    assert!(
+        mentions(&body, &format!("User:{USERNAME}")) && !mentions(&body, "certificate-user"),
+        "with SASL the certificate gates the transport only, as on a Kafka SASL_SSL listener"
+    );
+    assert!(
+        users.asked().is_empty(),
+        "the certificate's subject is never looked up on a SASL listener"
+    );
+}
+
+#[tokio::test]
+async fn given_rotated_certificate_files_should_serve_the_new_certificate_without_a_restart() {
+    let pki = Pki::new();
+    let first = pki.authority.server_cert("first");
+    first.write(pki.dir.path(), "server");
+    let (addrs, _shutdown) = spawn_gateway(
+        KafkaGateway::new,
+        quick_config(
+            vec![SecurityProtocol::Ssl],
+            Some(pki.tls().with_reload_interval(Duration::from_millis(100))),
+        ),
+    );
+
+    let addr = addrs[0];
+    let served = |expected: &Issued| {
+        let config = pki.authority.client_config(None);
+        let expected = expected.der.clone();
+        async move {
+            let stream = connect_tls(addr, config).await.expect("TLS handshake");
+            let (_, connection) = stream.get_ref();
+            let leaf = connection
+                .peer_certificates()
+                .and_then(|chain| chain.first())
+                .expect("the server presented a certificate");
+            leaf.as_ref() == expected.as_slice()
+        }
+    };
+    assert!(served(&first).await, "the certificate loaded at startup");
+
+    let second = pki.authority.server_cert("second");
+    second.write(pki.dir.path(), "server");
+    let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
+    while !served(&second).await {
+        assert!(
+            tokio::time::Instant::now() < deadline,
+            "the rotated certificate never went live"
+        );
+        tokio::time::sleep(Duration::from_millis(100)).await;
+    }
+}
+
+#[tokio::test]
+async fn given_unusable_material_should_refuse_to_start() {
+    let pki = Pki::new();
+    let other = TestPki::new().server_cert("other");
+    // The key belongs to a different certificate.
+    std::fs::write(&pki.key_file, other.key_pem).expect("swap key");
+    let socket = bind_listener("127.0.0.1:0").expect("bind");
+    let (_tx, rx) = tokio::sync::broadcast::channel(1);
+    let error = KafkaGateway::new(quick_config(vec![SecurityProtocol::Ssl], Some(pki.tls())))
+        .run(
+            vec![BoundListener::new(listener(SecurityProtocol::Ssl), socket)],
+            rx,
+        )
+        .await
+        .unwrap_err()
+        .to_string();
+    assert!(error.contains("pair"), "got: {error}");
+}
+
+#[tokio::test]
+async fn given_certificate_identities_without_a_lookup_should_refuse_to_start() {
+    let pki = Pki::new();
+    let socket = bind_listener("127.0.0.1:0").expect("bind");
+    let (_tx, rx) = tokio::sync::broadcast::channel(1);
+    let config = quick_config(
+        vec![SecurityProtocol::Ssl],
+        Some(pki.tls_with_client_auth(ClientAuth::Required)),
+    );
+    let error = KafkaGateway::new(config)
+        .run(
+            vec![BoundListener::new(listener(SecurityProtocol::Ssl), socket)],
+            rx,
+        )
+        .await
+        .unwrap_err()
+        .to_string();
+    assert!(
+        error.contains("IGGY_KAFKA_BRIDGE_ENABLED"),
+        "a certificate names an Iggy user only a bridge session can look up, got: {error}"
+    );
+}
+
+/// Kept for the suites that pin the single-listener shape: a `SASL_PLAINTEXT` listener on an
+/// ephemeral port is what `IGGY_KAFKA_SASL_ENABLED=true` used to mean.
+#[tokio::test]
+async fn given_a_sasl_plaintext_listener_should_still_run_the_exchange_in_the_clear() {
+    let (addrs, _shutdown) = spawn_gateway(
+        |config| KafkaGateway::new(config).with_authenticator(Arc::new(FixedCredentials)),
+        quick_config(vec![SecurityProtocol::SaslPlaintext], None),
+    );
+    let mut stream = TcpStream::connect(addrs[0]).await.expect("connect");
+    assert_eq!(
+        sasl_plain(&mut stream, USERNAME, PASSWORD).await,
+        ERROR_NONE
+    );
+}


(iggy) 02/02: feat(gateways): add TLS listeners and mTLS client identities to Kafka gateway

Posted by gk...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

numinnex pushed a commit to branch mtls_kafka_proxy
in repository https://gitbox.apache.org/repos/asf/iggy.git

commit 2b987dc65eee028c43e9ba56a8356c207e96e14f
Author: Grzegorz Koszyk <g....@gmail.com>
AuthorDate: Tue Oct 13 21:04:27 2026 +0200

    feat(gateways): add TLS listeners and mTLS client identities to Kafka gateway
---
 Cargo.lock                                         |   1 +
 Cargo.toml                                         |   1 +
 gateways/kafka/Cargo.toml                          |   1 +
 gateways/kafka/README.md                           |  67 +-
 gateways/kafka/docs/AUTHENTICATION.md              |  47 +-
 gateways/kafka/docs/MANUAL_TESTING.md              |   9 +-
 gateways/kafka/docs/TEST_SUITE.md                  |   2 +-
 gateways/kafka/src/auth.rs                         |  19 +-
 gateways/kafka/src/bridge/config.rs                |  15 +
 gateways/kafka/src/bridge/iggy_bridge/mod.rs       |   6 +
 gateways/kafka/src/listener.rs                     |  34 +-
 gateways/kafka/src/main.rs                         | 144 ++--
 gateways/kafka/src/protocol/api.rs                 |   5 +-
 .../kafka/src/protocol/handlers/alter_configs.rs   |  13 +-
 .../kafka/src/protocol/handlers/delete_topics.rs   |  11 +-
 gateways/kafka/src/server.rs                       | 188 +++--
 gateways/kafka/src/tls/identity.rs                 | 790 ++++++++++++++++++---
 gateways/kafka/src/tls/mod.rs                      | 145 +++-
 gateways/kafka/tests/common/certs.rs               |   8 +
 .../kafka/tests/delete_topics_real_bridge_tests.rs | 136 +++-
 gateways/kafka/tests/tls_listener_tests.rs         | 316 ++++++++-
 21 files changed, 1627 insertions(+), 331 deletions(-)

diff --git a/Cargo.lock b/Cargo.lock
index cf4b6d4e7..e3d2dfb09 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -7123,6 +7123,7 @@ dependencies = [
  "lz4",
  "rcgen",
  "regex",
+ "regex-syntax",
  "rustls",
  "secrecy",
  "serde",
diff --git a/Cargo.toml b/Cargo.toml
index 34b32f0d3..b6efbbf6e 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -292,6 +292,7 @@ rand_xoshiro = "0.8.1"
 rayon = "1.12.0"
 rcgen = "0.14.10"
 regex = "1.13.1"
+regex-syntax = "0.8.11"
 reqwest = { version = "0.13.5", default-features = false, features = ["json", "rustls"] }
 reqwest-middleware = { version = "0.5.2", features = ["json", "query"] }
 reqwest-retry = "0.9.1"
diff --git a/gateways/kafka/Cargo.toml b/gateways/kafka/Cargo.toml
index 0451b073b..f1093285d 100644
--- a/gateways/kafka/Cargo.toml
+++ b/gateways/kafka/Cargo.toml
@@ -48,6 +48,7 @@ kafka-protocol = { workspace = true, features = ["gzip", "lz4", "snappy", "zstd"
 libc = { workspace = true }
 lz4 = { workspace = true }
 regex = { workspace = true }
+regex-syntax = { workspace = true }
 rustls = { workspace = true }
 secrecy = { workspace = true }
 serde = { workspace = true }
diff --git a/gateways/kafka/README.md b/gateways/kafka/README.md
index f7d05e126..6ba7425d6 100644
--- a/gateways/kafka/README.md
+++ b/gateways/kafka/README.md
@@ -45,18 +45,18 @@ Default bind: a `PLAINTEXT` listener on `127.0.0.1:9093`. Environment variables:
 
 | Variable | Default | Description |
 | --- | --- | --- |
-| `IGGY_KAFKA_LISTENERS` | unset | Kafka-style listener list, `PROTOCOL://ip:port` entries separated by commas, one per security protocol: `PLAINTEXT`, `SSL`, `SASL_PLAINTEXT`, `SASL_SSL`. Takes precedence over the three single-listener address variables below (the image bakes `IGGY_KAFKA_BIND_ADDR` in, so they are ignored with a warning) and is refused beside `IGGY_KAFKA_SASL_ENABLED`, since the listener protocols say where SASL runs. See [Listeners and TLS](#listeners-and-tls-4510) |
-| `IGGY_KAFKA_ADVERTISED_LISTENERS` | bind address of each listener | `PROTOCOL://host:port` per listener, the address clients are pointed back at. Required for any listener bound to `0.0.0.0`/`::` |
+| `IGGY_KAFKA_LISTENERS` | unset | Kafka-style listener list, `PROTOCOL://ip:port` entries separated by commas, one per security protocol: `PLAINTEXT`, `SSL`, `SASL_PLAINTEXT`, `SASL_SSL`. An IPv6 address is bracketed: `SSL://[::1]:9094`. Takes precedence over `IGGY_KAFKA_BIND_ADDR`, which the image bakes in and which is ignored with a warning. Refused beside `IGGY_KAFKA_ADVERTISED_HOST`, `IGGY_KAFKA_ADVERTISED_PORT` (advertise through `IGGY_KAFKA_ADVERTISED_LISTENERS` instead) and `IGGY [...]
+| `IGGY_KAFKA_ADVERTISED_LISTENERS` | bind address of each listener | `PROTOCOL://host:port` per listener, the address clients are pointed back at. An IPv6 host is bracketed: `SSL://[2001:db8::1]:9094`. Required for any listener bound to `0.0.0.0`/`::` |
 | `IGGY_KAFKA_BIND_ADDR` | `127.0.0.1:9093` | Single-listener form: TCP address to listen on |
 | `IGGY_KAFKA_ADVERTISED_HOST` | bind IP | Single-listener form: hostname/IP clients use to reach this broker (required when binding to `0.0.0.0`/`::`) |
 | `IGGY_KAFKA_ADVERTISED_PORT` | bind port | Single-listener form: port advertised in Metadata responses |
 | `IGGY_KAFKA_TLS_CERT_FILE` | unset | PEM certificate chain for every `SSL` and `SASL_SSL` listener, leaf first. Required when one exists, refused when none does |
 | `IGGY_KAFKA_TLS_KEY_FILE` | unset | PEM private key for the certificate (PKCS#8, PKCS#1 or SEC1) |
-| `IGGY_KAFKA_TLS_CLIENT_AUTH` | `none` | Kafka's `ssl.client.auth`: `none`, `requested` or `required`. On an `SSL` listener a verified client certificate names the Iggy user; on `SASL_SSL` it only gates the transport |
+| `IGGY_KAFKA_TLS_CLIENT_AUTH` | `none` | Kafka's `ssl.client.auth`: `none`, `requested` or `required`. Applies to `SSL` listeners, where a verified client certificate names the Iggy user. A `SASL_SSL` listener never asks for a client certificate, Kafka's default there. Refused without an `SSL` listener |
 | `IGGY_KAFKA_TLS_CLIENT_CA_FILE` | unset | PEM roots client certificates must chain to. Required with `requested` or `required`, refused with `none` |
 | `IGGY_KAFKA_TLS_PRINCIPAL_MAPPING_RULES` | `DEFAULT` | Kafka's `ssl.principal.mapping.rules`, turning a client certificate's subject into an Iggy username. Only with client authentication on an `SSL` listener |
 | `IGGY_KAFKA_TLS_RELOAD_INTERVAL_SECS` | `60` | How often the certificate, key and client CA files are re-read; a change goes live for new connections without a restart. `0` never re-reads them |
-| `IGGY_KAFKA_MAX_CONNECTIONS` | `1024` | Maximum concurrent connections before new ones are rejected |
+| `IGGY_KAFKA_MAX_CONNECTIONS` | `1024` | Maximum concurrent connections per listener before new ones are rejected. Each listener has its own allowance, so idle clients on one cannot lock clients out of another. Open connections can therefore reach the number of listeners times this value; size the file-descriptor limit (`ulimit -n`) for that |
 | `IGGY_KAFKA_MAX_FRAME_SIZE` | `8388608` | Maximum accepted request frame size in bytes |
 | `IGGY_KAFKA_IDLE_TIMEOUT_SECS` | `600` | Seconds a connection may sit idle before the next frame's length prefix arrives |
 | `IGGY_KAFKA_READ_TIMEOUT_SECS` | `15` | Seconds allowed to read a frame body once its length prefix arrives |
@@ -262,11 +262,21 @@ IGGY_KAFKA_LISTENERS=PLAINTEXT://127.0.0.1:9093,SSL://0.0.0.0:9094,SASL_SSL://0.
   cargo run -p iggy-gateway-kafka
 ```
 
+Each security protocol can be bound once, since the protocol is also the listener's name.
+
 TLS is rustls. One certificate serves every `SSL` and `SASL_SSL` listener, and the files are
 re-read every `IGGY_KAFKA_TLS_RELOAD_INTERVAL_SECS`: a rotated certificate takes effect for new
-connections without a restart, a half-written rotation or a key that does not match leaves the
-previous material serving and logs an error. There is no self-signed mode; mint a certificate
-(`docs/MANUAL_TESTING.md` has an `openssl` recipe) and give the Kafka client the CA.
+connections without a restart, a key that does not match leaves the previous material serving and
+logs an error. Rotate by writing the new files elsewhere and renaming them into place: a chain
+written in place can be read half written, and if what was read still parses and matches the key,
+the truncated chain serves until the next interval. There is no self-signed mode; mint a
+certificate (`docs/MANUAL_TESTING.md` has an `openssl` recipe) and give the Kafka client the CA.
+
+The certificate's subject alternative names must cover every host in
+`IGGY_KAFKA_ADVERTISED_LISTENERS`: a client verifies the name of each broker address Metadata
+hands it, so a host missing from the certificate fails the client's next connection, not the
+first. Client certificates are checked against the CA only; there is no CRL or OCSP revocation
+checking, so revoke access by deleting or deactivating the Iggy user a certificate maps to.
 
 ```bash
 kcat -b kafka.example.com:9094 -X security.protocol=SSL -X ssl.ca.location=ca.pem -L
@@ -276,23 +286,36 @@ kcat -b kafka.example.com:9095 -X security.protocol=SASL_SSL -X ssl.ca.location=
 
 ### Client certificates (mTLS)
 
-`IGGY_KAFKA_TLS_CLIENT_AUTH=required` (or `requested`) makes every TLS listener verify client
-certificates against `IGGY_KAFKA_TLS_CLIENT_CA_FILE`. What a verified certificate means depends on
-the listener, as it does on a Kafka broker:
-
-- On an `SSL` listener the certificate names the principal. Its subject, rendered the way Java
-  does (`CN=alice,OU=eng,O=Example`), goes through `IGGY_KAFKA_TLS_PRINCIPAL_MAPPING_RULES`, and
-  the result must be the name of an active Iggy user. The gateway looks the user up through the
-  bridge's own session, so the bridge is required and its Iggy user needs `read_users`. A
-  certificate naming no such user is closed after the handshake, with the name in the gateway's
-  log at `warn`. With `requested`, a client that presents no certificate is Kafka's `ANONYMOUS`
-  principal and is served as the bridge's user, exactly as on a plaintext listener.
-- On a `SASL_SSL` listener the certificate only gates the transport. SASL names the principal and
-  the subject is never mapped.
+`IGGY_KAFKA_TLS_CLIENT_AUTH=required` (or `requested`) makes every `SSL` listener verify client
+certificates against `IGGY_KAFKA_TLS_CLIENT_CA_FILE`, and the certificate names the principal
+there. Its subject, rendered the way Java does (`CN=alice,OU=eng,O=Example`), goes through
+`IGGY_KAFKA_TLS_PRINCIPAL_MAPPING_RULES`, and the result must be the name of an active Iggy user.
+The gateway looks the user up through the bridge's own session, so the bridge is required and its
+Iggy user needs `read_users`. A certificate whose subject no rule maps, or that names no such user,
+is closed after the handshake, with the subject or name in the gateway's log at `warn`.
+
+A `SASL_SSL` listener never asks for a client certificate, which is Kafka's default for that
+protocol: SASL names the principal there.
+
+With `requested`, a client that presents no certificate is Kafka's `ANONYMOUS` principal, which
+holds no permissions. Once any listener names principals (a SASL listener, or an `SSL` listener
+with client authentication), every connection that proved no identity is `ANONYMOUS`, on a
+`PLAINTEXT` listener beside it too. The requests the gateway checks against a principal,
+`DeleteTopics` and `AlterConfigs`, need `manage_topics` and are refused for it; everything else is
+served as the bridge's user. A gateway whose listeners name nobody serves every request as the
+bridge's user.
 
 The rules are Kafka's syntax, tried in order: `RULE:pattern/replacement/[LU]` applies when the
-pattern matches the whole subject, `DEFAULT` keeps the subject as is. A raw subject is not a valid
-Iggy username, so a deployment that maps identities sets at least one rule:
+pattern matches the whole subject, `DEFAULT` keeps the subject as is. Iggy accepts any username of
+3 to 50 characters, but a raw subject is usually longer than that, and is rarely the name the
+operator created, so a deployment that maps identities sets at least one rule. Patterns are a
+Java-compatible subset: `\d \s \w` match ASCII only and `.` stops at Java's line terminators, as on
+a broker, while `(?i)`, the `u` and `U` flags, `\p{..}`, POSIX classes and `\b` are refused at
+startup ([docs/AUTHENTICATION.md](docs/AUTHENTICATION.md) says why). A replacement that
+names a group the pattern does not have is refused at startup. That is stricter than Kafka, which
+writes such a `$N` literally: `RULE:^CN=(.*)$/$2/` maps to `$2` on a broker. The reverse case,
+`/$1\$2/`, makes Kafka throw while the gateway maps `alice` to `alice$2`, which is harmless because
+that Iggy user must still exist:
 
 ```bash
 IGGY_KAFKA_TLS_PRINCIPAL_MAPPING_RULES='RULE:^CN=([^,]+),OU=services.*$/svc-$1/L,RULE:^CN=([^,]+).*$/$1/'
diff --git a/gateways/kafka/docs/AUTHENTICATION.md b/gateways/kafka/docs/AUTHENTICATION.md
index 643642ba0..a217cb83c 100644
--- a/gateways/kafka/docs/AUTHENTICATION.md
+++ b/gateways/kafka/docs/AUTHENTICATION.md
@@ -227,24 +227,41 @@ Iggy password is capped at 100 bytes with a `u8` length prefix on the wire
 
 ## Client certificates
 
-`IGGY_KAFKA_TLS_CLIENT_AUTH` is Kafka's `ssl.client.auth`: `none`, `requested` or `required`. With it on,
-every TLS listener verifies the client certificate against `IGGY_KAFKA_TLS_CLIENT_CA_FILE` during the
-handshake, and what a verified certificate means follows the listener, as it does on a Kafka broker.
+`IGGY_KAFKA_TLS_CLIENT_AUTH` is Kafka's `ssl.client.auth`: `none`, `requested` or `required`. It applies
+to `SSL` listeners, which verify the client certificate against `IGGY_KAFKA_TLS_CLIENT_CA_FILE` during the
+handshake, and is refused when no `SSL` listener exists.
 
-On a `SASL_SSL` listener the certificate gates the transport only. SASL names the principal, and the
-subject is never mapped: Kafka does the same, and a deployment that wants certificate identities uses
-`SSL`.
+A `SASL_SSL` listener never asks for a client certificate. Kafka applies `ssl.client.auth` to a
+`SASL_SSL` listener only when that listener overrides it, and leaves it at `none` otherwise; SASL names
+the principal there. A deployment that wants certificate identities uses `SSL`.
 
 On an `SSL` listener the certificate names the principal, in three steps the connection takes before its
 first frame:
 
 1. **Render the subject** the way Java's `X500Principal.getName()` does, RFC 2253 with the most specific
    RDN first and no spaces: `CN=alice,OU=eng,O=Example`. Operators write mapping rules against Java's
-   rendering, so the gateway matches it, keyword set and escaping included.
+   rendering, so the gateway follows JDK 11 to 21's `AVA.toRFC2253String`: its keyword set, its escaping
+   (NUL as `\00`), Latin-1 for `PrintableString`, `IA5String` and `GeneralString`, and hex for the string
+   types Java does not decode, `UniversalString` among them. Malformed UTF-8 or BMP values are the one case
+   not checked against Java.
 2. **Map it** through `IGGY_KAFKA_TLS_PRINCIPAL_MAPPING_RULES`, Kafka's `ssl.principal.mapping.rules`
    syntax: `RULE:pattern/replacement/[LU]` applies when the pattern matches the whole subject, `DEFAULT`
-   keeps it, the first match wins, and a subject no rule matches closes the connection. The default is
-   `DEFAULT`, which is not a valid Iggy username, so a deployment sets at least one rule.
+   keeps it, the first match wins, and a subject no rule matches closes the connection with the subject in
+   the log at `warn`. The default is `DEFAULT`. Iggy only requires a username of 3 to 50 characters, but a
+   raw subject is usually longer than that and is rarely the name the operator created, so a deployment
+   sets at least one rule. A replacement with a bare `$`, or a `${name}` with no such named group, is
+   refused at startup, where Kafka would fail the first handshake it applies to. One that names a group
+   the pattern lacks is refused too, which is stricter than Kafka: a broker writes it literally, so
+   `RULE:^CN=(.*)$/$2/` maps to `$2`. The reverse case, `/$1\$2/`, makes Kafka throw while the gateway
+   maps `alice` to `alice$2`, which is harmless because that Iggy user must still exist. The replacement is applied as Java's `replaceAll`, to every match in the subject, so
+   `RULE:(.*)/$1@x/` maps `alice` to `alice@x@x` as it does on a broker. Patterns are the subset of
+   Java's regex syntax whose meaning the gateway can reproduce: `\d \s \w` and their negations match
+   ASCII only, and `.` outside `(?s)` stops at `\r`, U+0085, U+2028 and U+2029 as well as `\n`, both as
+   in Java. Rust would read them over Unicode, so a CA-signed `CN=\u212Aafka` (Kelvin sign) would match
+   `\w+` and lowercase to `kafka`. Case-insensitive matching (`(?i)`), the `u` and `U` flags, `\p{..}`
+   and `\P{..}`, POSIX classes such as `[[:alpha:]]`, and word boundaries (`\b`, `\B`) are refused at
+   startup with the construct named: each has no faithful translation. Non-ASCII names still map, so
+   `CN=Zoë` under `RULE:^CN=([^,]+).*$/$1/` maps to `Zoë` as on a broker.
 3. **Look the name up** through the bridge's own session. The user must exist and be active, or the
    connection is closed after the handshake with the name in the log at `warn`: a certificate the CA signed
    for an account that does not exist is a provisioning mistake, not something the client can correct. The
@@ -252,9 +269,15 @@ first frame:
    lookup, including one refused for want of that permission, closes the connection too and never admits
    the name unchecked.
 
-With `requested`, a client that presents no certificate is Kafka's `ANONYMOUS` principal: served as the
-bridge's user, the way a plaintext listener serves everyone, and described by `DescribeAcls` as holding
-nothing. With `required`, rustls fails the handshake instead.
+With `requested`, a client that presents no certificate is Kafka's `ANONYMOUS` principal, which holds no
+permissions: `DescribeAcls` describes it as holding nothing, and `DeleteTopics` and `AlterConfigs`, which
+need `manage_topics`, are refused. Everything else is served as the bridge's user. With `required`, rustls
+fails the handshake instead.
+
+The same holds on every listener that names nobody once any listener names principals: a `PLAINTEXT`
+listener beside a `SASL_SSL` or mTLS one serves `ANONYMOUS`, so it cannot do what an authenticated user
+without `manage_topics` cannot. Only a gateway whose listeners all name nobody leaves those requests
+ungated.
 
 The principal a certificate yields is the same `AuthenticatedPrincipal` a SASL login yields, with its
 permissions read at admission, so everything written about the SASL identity above holds: it is a snapshot,
diff --git a/gateways/kafka/docs/MANUAL_TESTING.md b/gateways/kafka/docs/MANUAL_TESTING.md
index 9354ad493..568c75ace 100644
--- a/gateways/kafka/docs/MANUAL_TESTING.md
+++ b/gateways/kafka/docs/MANUAL_TESTING.md
@@ -202,7 +202,8 @@ done
 ```
 
 Then a gateway with every listener, bridged (the bridge looks certificate identities up), with client
-certificates requested and the common name as the Iggy username:
+certificates requested on the `SSL` listener and the common name as the Iggy username. The `SASL_SSL`
+listener asks for no client certificate whatever `IGGY_KAFKA_TLS_CLIENT_AUTH` says:
 
 ```bash
 IGGY_KAFKA_LISTENERS=PLAINTEXT://127.0.0.1:9093,SSL://127.0.0.1:9094,SASL_SSL://127.0.0.1:9095 \
@@ -303,9 +304,9 @@ func main() {
 }
 ```
 
-Run it four ways, with `CA_FILE=/tmp/certs/ca.pem` exported: `go run . 127.0.0.1:19094`,
-`SASL_USER=iggy SASL_PASS=iggy go run . 127.0.0.1:19095`,
-`go run . 127.0.0.1:19094 /tmp/certs/iggy.pem /tmp/certs/iggy.key` and the same with
+Run it four ways, with `CA_FILE=/tmp/certs/ca.pem` exported: `go run . 127.0.0.1:9094`,
+`SASL_USER=iggy SASL_PASS=iggy go run . 127.0.0.1:9095`,
+`go run . 127.0.0.1:9094 /tmp/certs/iggy.pem /tmp/certs/iggy.key` and the same with
 `nobody.pem`/`nobody.key`. The first three print the one broker on the port they dialed, the SASL
 and certificate runs also list `User:iggy`'s bindings, and the last reports the broker closing the
 connection during `ApiVersions`.
diff --git a/gateways/kafka/docs/TEST_SUITE.md b/gateways/kafka/docs/TEST_SUITE.md
index ff2508361..5b6178c1a 100644
--- a/gateways/kafka/docs/TEST_SUITE.md
+++ b/gateways/kafka/docs/TEST_SUITE.md
@@ -78,7 +78,7 @@ file under `tests/` anymore.
 | [`server_e2e_tests.rs`](../tests/server_e2e_tests.rs) | Full `KafkaGateway` TCP round-trips | Partial |
 | [`listener_robustness_tests.rs`](../tests/listener_robustness_tests.rs) | TCP listener robustness — framing, pipelining, concurrency, connection limits | No |
 | [`sasl_tests.rs`](../tests/sasl_tests.rs) | SASL/PLAIN over a socket — full handshake, every refusal path, and the disabled default. Drives a stub verifier implementing `SaslAuthenticator`, so no Iggy server is needed | No |
-| [`tls_listener_tests.rs`](../tests/tls_listener_tests.rs) | The `SSL` and `SASL_SSL` listeners over a real socket with certificates minted per test: each listener advertising its own port, a plaintext client refused on the TLS port, SASL inside TLS, client certificates mapped to users through a stub `PrincipalResolver` (`required`, `requested`, unknown user, SASL precedence), certificate reload without a restart, and the startup refusals | No |
+| [`tls_listener_tests.rs`](../tests/tls_listener_tests.rs) | The `SSL` and `SASL_SSL` listeners over a real socket with certificates minted per test: each listener advertising its own port, a plaintext client refused on the TLS port, SASL inside TLS, client certificates mapped to users through a stub `PrincipalResolver` (`required`, `requested`, unknown user, a subject no rule maps, a failing or hung lookup, `SASL_SSL` asking for no certificate), a multi-MiB response to a slow reader, t [...]
 | [`kafka_client_e2e_tests.rs`](../tests/kafka_client_e2e_tests.rs) | **Real Kafka clients** against the whole stack: a spawned `iggy-server`, the gateway in-process with a real authenticator, and kcat / the Java tools from containers. With a bridge, kcat writes records, and kcat and the Java consumer read them back through Fetch. Java consumers in one group resume from their commits, across a gateway restart and a member leaving. librdkafka and the Java client connect with `security.pro [...]
 | [`bridge_iggy_integration_tests.rs`](../tests/bridge_iggy_integration_tests.rs) | `IggyBridge` against a real, spawned `iggy-server` — provisioning idempotency, high watermark, credential/connection edge cases, and the bridge dialing a TLS-only server over TLS | No (needs the `iggy-server` binary - see Prerequisites) |
 | [`list_offsets_real_bridge_tests.rs`](../tests/list_offsets_real_bridge_tests.rs) | ListOffsets (key 2) through the whole handler against a real, spawned `iggy-server`: LATEST, EARLIEST, codes 3 and 43 | No (needs the `iggy-server` binary - see Prerequisites) |
diff --git a/gateways/kafka/src/auth.rs b/gateways/kafka/src/auth.rs
index b10742091..97eee2e4e 100644
--- a/gateways/kafka/src/auth.rs
+++ b/gateways/kafka/src/auth.rs
@@ -215,6 +215,23 @@ pub struct AuthenticatedPrincipal {
     pub permissions_known: bool,
 }
 
+impl AuthenticatedPrincipal {
+    /// Kafka's name for a client that proved no identity, as `DescribeAcls` renders it.
+    pub const ANONYMOUS: &'static str = "ANONYMOUS";
+
+    /// A connection that proved no identity on a gateway that authenticates somewhere: it holds
+    /// nothing, and that is a real answer rather than a failed read. It is "authenticated" only in
+    /// the sense that the connection's identity has been decided.
+    #[must_use]
+    pub fn anonymous() -> Self {
+        Self {
+            username: Self::ANONYMOUS.to_string(),
+            permissions: PrincipalPermissions::default(),
+            permissions_known: true,
+        }
+    }
+}
+
 /// Verifies Kafka-supplied credentials.
 ///
 /// A trait rather than a concrete type so the protocol tests can drive the whole SASL exchange
@@ -246,7 +263,7 @@ pub trait SaslAuthenticator: Send + Sync + std::fmt::Debug {
 /// over its own session; the protocol tests drive the certificate path without an Iggy server
 /// through a stub.
 #[async_trait]
-pub trait PrincipalResolver: Send + Sync {
+pub trait PrincipalResolver: Send + Sync + std::fmt::Debug {
     /// Returns the principal when `username` names an active Iggy user.
     ///
     /// # Errors
diff --git a/gateways/kafka/src/bridge/config.rs b/gateways/kafka/src/bridge/config.rs
index ed66894a5..7c5e39874 100644
--- a/gateways/kafka/src/bridge/config.rs
+++ b/gateways/kafka/src/bridge/config.rs
@@ -244,6 +244,21 @@ mod tests {
     use serial_test::serial;
 
     use super::*;
+    use crate::auth::IggyAuthenticator;
+
+    #[test]
+    fn given_the_iggy_tls_variables_should_be_listed_by_every_reader() {
+        for var in IggyTls::KNOWN_ENV_VARS {
+            assert!(
+                IggyBridgeConfig::KNOWN_ENV_VARS.contains(var),
+                "{var} is read by the bridge and must be in its list"
+            );
+            assert!(
+                IggyAuthenticator::KNOWN_ENV_VARS.contains(var),
+                "{var} is read by the SASL credential check and must be in its list"
+            );
+        }
+    }
 
     fn test_config() -> IggyBridgeConfig {
         IggyBridgeConfig {
diff --git a/gateways/kafka/src/bridge/iggy_bridge/mod.rs b/gateways/kafka/src/bridge/iggy_bridge/mod.rs
index 2fa920d87..b77f9e370 100644
--- a/gateways/kafka/src/bridge/iggy_bridge/mod.rs
+++ b/gateways/kafka/src/bridge/iggy_bridge/mod.rs
@@ -264,6 +264,12 @@ async fn connect_client(config: &IggyBridgeConfig) -> Result<IggyClient, BridgeE
     Ok(client)
 }
 
+impl std::fmt::Debug for IggyBridge {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        f.debug_struct("IggyBridge").finish_non_exhaustive()
+    }
+}
+
 /// The bridge's own session answers for the users client certificates name. It runs as the
 /// bridge's Iggy user, so that account needs `read_users` for any certificate to be admitted.
 #[async_trait]
diff --git a/gateways/kafka/src/listener.rs b/gateways/kafka/src/listener.rs
index 1fe2c580c..221b66c8b 100644
--- a/gateways/kafka/src/listener.rs
+++ b/gateways/kafka/src/listener.rs
@@ -288,12 +288,18 @@ fn split_entry<'a>(var: &str, entry: &'a str) -> Result<(SecurityProtocol, &'a s
 }
 
 /// Splits `host:port`, with `[v6]:port` for an IPv6 literal, into a bracket-free host and the
-/// port text.
+/// port text. An unbracketed host containing `:` is refused, since its port cannot be told apart.
 fn split_host_port(address: &str) -> Option<(&str, &str)> {
-    let (host, port) = address.rsplit_once(':')?;
-    let host = host
-        .strip_prefix('[')
-        .map_or(host, |inner| inner.strip_suffix(']').unwrap_or(host));
+    let (host, port) = if let Some(bracketed) = address.strip_prefix('[') {
+        let (host, rest) = bracketed.split_once(']')?;
+        (host, rest.strip_prefix(':')?)
+    } else {
+        let (host, port) = address.rsplit_once(':')?;
+        if host.contains(':') {
+            return None;
+        }
+        (host, port)
+    };
     if host.is_empty() {
         return None;
     }
@@ -389,6 +395,24 @@ mod tests {
         }
     }
 
+    #[test]
+    fn given_an_unbracketed_ipv6_advertised_host_should_refuse() {
+        let mut listeners = parse_listeners("SSL://0.0.0.0:9094").expect("valid");
+        for raw in ["SSL://fe80::1", "SSL://fe80::1:9094", "SSL://[fe80::1]9094"] {
+            let error = apply_advertised_listeners(&mut listeners, raw)
+                .err()
+                .unwrap_or_else(|| panic!("'{raw}' must be rejected"))
+                .to_string();
+            assert!(
+                error.contains("IGGY_KAFKA_ADVERTISED_LISTENERS"),
+                "'{raw}' rejection must name the variable, got: {error}"
+            );
+        }
+        apply_advertised_listeners(&mut listeners, "SSL://[fe80::1]:9094")
+            .expect("a bracketed IPv6 literal is valid");
+        assert_eq!(listeners[0].advertised_host.as_deref(), Some("fe80::1"));
+    }
+
     #[test]
     fn given_a_wildcard_bind_without_an_advertised_host_should_refuse_and_name_the_listener() {
         let listener = ListenerConfig::new(SecurityProtocol::SaslSsl, "0.0.0.0:9095");
diff --git a/gateways/kafka/src/main.rs b/gateways/kafka/src/main.rs
index 9a138da72..dfb24d6f5 100644
--- a/gateways/kafka/src/main.rs
+++ b/gateways/kafka/src/main.rs
@@ -291,39 +291,42 @@ fn load_config() -> Result<GatewayConfig, String> {
              Iggy cluster needs its own value, or they hand out colliding producer ids"
         );
     }
-    reject_unread_iggy_tls(config.sasl_enabled(), bridge_enabled()?)?;
+    reject_unread_iggy_tls(
+        config.sasl_enabled(),
+        bridge_enabled()?,
+        env_var("IGGY_KAFKA_LISTENERS").is_some(),
+    )?;
 
     Ok(config)
 }
 
 /// The listeners, from `IGGY_KAFKA_LISTENERS` or from the single-listener variables.
 ///
-/// With a listener list, the single-listener address variables are ignored with a warning rather
-/// than refused: the gateway's own image bakes `IGGY_KAFKA_BIND_ADDR=0.0.0.0:9093` in, and
-/// refusing it would make `IGGY_KAFKA_LISTENERS` unusable there. `IGGY_KAFKA_SASL_ENABLED` is
-/// refused beside a list all the same. It is a security switch, and with a list the protocol of
-/// each listener says whether it runs SASL, so a `true` left over from the single-listener form
-/// would otherwise read as SASL on while nothing ran it.
+/// With a listener list, `IGGY_KAFKA_BIND_ADDR` is ignored with a warning rather than refused:
+/// the gateway's own image bakes `IGGY_KAFKA_BIND_ADDR=0.0.0.0:9093` in, and refusing it would
+/// make `IGGY_KAFKA_LISTENERS` unusable there. Every other single-listener variable is refused
+/// beside a list, since ignoring it would advertise or authenticate differently from what its
+/// operator set.
 fn load_listeners() -> Result<Vec<ListenerConfig>, String> {
-    let addressing: Vec<&str> = SINGLE_LISTENER_ENV_VARS
-        .iter()
-        .copied()
-        .filter(|var| *var != "IGGY_KAFKA_SASL_ENABLED" && env_var(var).is_some())
-        .collect();
     let advertised = env_var("IGGY_KAFKA_ADVERTISED_LISTENERS");
     if let Some(raw) = env_var("IGGY_KAFKA_LISTENERS") {
-        if env_var("IGGY_KAFKA_SASL_ENABLED").is_some() {
-            return Err(
-                "IGGY_KAFKA_LISTENERS and IGGY_KAFKA_SASL_ENABLED are both set; with a listener \
-                 list, a SASL_PLAINTEXT or SASL_SSL listener is what turns SASL on"
-                    .to_string(),
-            );
+        let refused: Vec<&str> = SINGLE_LISTENER_ENV_VARS
+            .iter()
+            .copied()
+            .filter(|var| *var != "IGGY_KAFKA_BIND_ADDR" && env_var(var).is_some())
+            .collect();
+        if !refused.is_empty() {
+            return Err(format!(
+                "IGGY_KAFKA_LISTENERS is set together with {}, which belong to the \
+                 single-listener form; advertise through IGGY_KAFKA_ADVERTISED_LISTENERS, and \
+                 turn SASL on with a SASL_PLAINTEXT or SASL_SSL listener",
+                refused.join(", ")
+            ));
         }
-        if !addressing.is_empty() {
+        if env_var("IGGY_KAFKA_BIND_ADDR").is_some() {
             warn!(
-                "{} set but IGGY_KAFKA_LISTENERS takes precedence; they are ignored (bind and \
-                 advertise through IGGY_KAFKA_LISTENERS and IGGY_KAFKA_ADVERTISED_LISTENERS)",
-                addressing.join(", ")
+                "IGGY_KAFKA_BIND_ADDR set but IGGY_KAFKA_LISTENERS takes precedence; it is \
+                 ignored (bind through IGGY_KAFKA_LISTENERS)"
             );
         }
         let mut listeners = parse_listeners(&raw).map_err(|e| e.to_string())?;
@@ -398,6 +401,16 @@ fn load_tls(listeners: &[ListenerConfig]) -> Result<Option<TlsConfig>, String> {
             .map_err(|e| format!("invalid IGGY_KAFKA_TLS_CLIENT_AUTH `{raw}`: {e}"))?,
         None => ClientAuth::None,
     };
+    let has_ssl_listener = listeners
+        .iter()
+        .any(|listener| listener.protocol.authenticates_by_certificate());
+    if client_auth.is_enabled() && !has_ssl_listener {
+        return Err(format!(
+            "IGGY_KAFKA_TLS_CLIENT_AUTH is {client_auth} but no SSL listener is configured; it \
+             applies to SSL listeners only, and a SASL_SSL listener asks for no client \
+             certificate"
+        ));
+    }
     match (
         client_auth.is_enabled(),
         env_var("IGGY_KAFKA_TLS_CLIENT_CA_FILE"),
@@ -419,11 +432,7 @@ fn load_tls(listeners: &[ListenerConfig]) -> Result<Option<TlsConfig>, String> {
         (false, None) => {}
     }
     if let Some(raw) = env_var("IGGY_KAFKA_TLS_PRINCIPAL_MAPPING_RULES") {
-        let maps_identities = client_auth.is_enabled()
-            && listeners
-                .iter()
-                .any(|listener| listener.protocol.authenticates_by_certificate());
-        if !maps_identities {
+        if !client_auth.is_enabled() {
             return Err(
                 "IGGY_KAFKA_TLS_PRINCIPAL_MAPPING_RULES is set but no SSL listener verifies \
                  client certificates; the rules apply to an SSL listener with \
@@ -452,7 +461,11 @@ fn load_tls(listeners: &[ListenerConfig]) -> Result<Option<TlsConfig>, String> {
 /// The bridge and the SASL credential check are the two things that dial Iggy. With both off,
 /// accepting the switches lets an operator believe the link to Iggy is encrypted when there is no
 /// link, the same mistake `IggyTls::from_env` refuses to start for.
-fn reject_unread_iggy_tls(sasl_enabled: bool, bridge_enabled: bool) -> Result<(), String> {
+fn reject_unread_iggy_tls(
+    sasl_enabled: bool,
+    bridge_enabled: bool,
+    listener_list: bool,
+) -> Result<(), String> {
     if sasl_enabled || bridge_enabled {
         return Ok(());
     }
@@ -464,9 +477,14 @@ fn reject_unread_iggy_tls(sasl_enabled: bool, bridge_enabled: bool) -> Result<()
     if set.is_empty() {
         return Ok(());
     }
+    let sasl_switch = if listener_list {
+        "no listener in IGGY_KAFKA_LISTENERS runs SASL"
+    } else {
+        "IGGY_KAFKA_SASL_ENABLED is not true"
+    };
     Err(format!(
-        "{} set but neither IGGY_KAFKA_SASL_ENABLED nor IGGY_KAFKA_BRIDGE_ENABLED is true; only \
-         the SASL credential check and the bridge dial Iggy, so nothing would be encrypted",
+        "{} set but {sasl_switch} and IGGY_KAFKA_BRIDGE_ENABLED is not true; only the SASL \
+         credential check and the bridge dial Iggy, so nothing would be encrypted",
         set.join(", ")
     ))
 }
@@ -662,15 +680,25 @@ mod tests {
         unsafe {
             std::env::set_var("IGGY_KAFKA_IGGY_TLS_ENABLED", "true");
         }
-        let nothing_reads_it = reject_unread_iggy_tls(false, false);
-        let sasl_reads_it = reject_unread_iggy_tls(true, false);
-        let bridge_reads_it = reject_unread_iggy_tls(false, true);
+        let nothing_reads_it = reject_unread_iggy_tls(false, false, false);
+        let nothing_reads_it_in_a_list = reject_unread_iggy_tls(false, false, true);
+        let sasl_reads_it = reject_unread_iggy_tls(true, false, false);
+        let bridge_reads_it = reject_unread_iggy_tls(false, true, false);
         unsafe {
             std::env::remove_var("IGGY_KAFKA_IGGY_TLS_ENABLED");
         }
         assert!(
-            nothing_reads_it.is_err(),
-            "nothing reads the TLS switch with SASL and the bridge off, so accepting it hides that"
+            nothing_reads_it
+                .expect_err(
+                    "nothing reads the TLS switch with SASL and the bridge off, so accepting it \
+                     hides that"
+                )
+                .contains("IGGY_KAFKA_SASL_ENABLED")
+        );
+        let in_a_list = nothing_reads_it_in_a_list.expect_err("refused with a listener list too");
+        assert!(
+            !in_a_list.contains("IGGY_KAFKA_SASL_ENABLED"),
+            "a listener list refuses that switch, so naming it misleads, got: {in_a_list}"
         );
         assert!(sasl_reads_it.is_ok());
         assert!(bridge_reads_it.is_ok());
@@ -706,14 +734,31 @@ mod tests {
 
     #[test]
     #[serial]
-    fn given_both_listener_forms_should_refuse_the_sasl_switch_and_ignore_the_addresses() {
-        let error = load_with(&[
-            ("IGGY_KAFKA_LISTENERS", "PLAINTEXT://127.0.0.1:9093"),
-            ("IGGY_KAFKA_SASL_ENABLED", "true"),
-        ])
-        .unwrap_err();
-        assert!(error.contains("IGGY_KAFKA_LISTENERS"), "got: {error}");
-        assert!(error.contains("IGGY_KAFKA_SASL_ENABLED"), "got: {error}");
+    fn given_both_listener_forms_should_refuse_all_but_the_bind_address() {
+        for var in [
+            "IGGY_KAFKA_SASL_ENABLED",
+            "IGGY_KAFKA_ADVERTISED_HOST",
+            "IGGY_KAFKA_ADVERTISED_PORT",
+        ] {
+            let value = if var == "IGGY_KAFKA_SASL_ENABLED" {
+                "true"
+            } else {
+                "9093"
+            };
+            let error = load_with(&[
+                ("IGGY_KAFKA_LISTENERS", "PLAINTEXT://127.0.0.1:9093"),
+                (var, value),
+            ])
+            .unwrap_err();
+            assert!(error.contains("IGGY_KAFKA_LISTENERS"), "got: {error}");
+            assert!(error.contains(var), "got: {error}");
+            if var != "IGGY_KAFKA_SASL_ENABLED" {
+                assert!(
+                    error.contains("IGGY_KAFKA_ADVERTISED_LISTENERS"),
+                    "got: {error}"
+                );
+            }
+        }
 
         // The image bakes a bind address in, so a listener list has to win over it.
         let config = load_with(&[
@@ -813,6 +858,19 @@ mod tests {
             "got: {no_auth}"
         );
 
+        let auth_without_ssl = load_with(&[
+            ("IGGY_KAFKA_LISTENERS", "SASL_SSL://0.0.0.0:9095"),
+            ("IGGY_KAFKA_TLS_CERT_FILE", "/etc/iggy/kafka.pem"),
+            ("IGGY_KAFKA_TLS_KEY_FILE", "/etc/iggy/kafka.key"),
+            ("IGGY_KAFKA_TLS_CLIENT_AUTH", "required"),
+            ("IGGY_KAFKA_TLS_CLIENT_CA_FILE", "/etc/iggy/ca.pem"),
+        ])
+        .unwrap_err();
+        assert!(
+            auth_without_ssl.contains("no SSL listener"),
+            "client authentication applies to SSL listeners only, got: {auth_without_ssl}"
+        );
+
         let rules_without_auth =
             with(&[("IGGY_KAFKA_TLS_PRINCIPAL_MAPPING_RULES", "DEFAULT")]).unwrap_err();
         assert!(
diff --git a/gateways/kafka/src/protocol/api.rs b/gateways/kafka/src/protocol/api.rs
index ef4f169cd..65c64fdec 100644
--- a/gateways/kafka/src/protocol/api.rs
+++ b/gateways/kafka/src/protocol/api.rs
@@ -483,8 +483,9 @@ pub async fn handle_request_bounded(
 
 /// [`handle_request_bounded`] for one request of `connection`.
 ///
-/// `principal` is `None` when SASL is off, or for a key the connection reached before
-/// authenticating - only `crate::server::route_frame` ever has a principal to pass.
+/// `principal` is `None` when no listener of the gateway names principals, or for a key the
+/// connection reached before authenticating. Only `crate::server::route_frame` ever has a
+/// principal to pass.
 pub async fn handle_connection_request(
     state: &GatewayState,
     connection: &ConnectionState,
diff --git a/gateways/kafka/src/protocol/handlers/alter_configs.rs b/gateways/kafka/src/protocol/handlers/alter_configs.rs
index 8386db6f9..a7e52ceb6 100644
--- a/gateways/kafka/src/protocol/handlers/alter_configs.rs
+++ b/gateways/kafka/src/protocol/handlers/alter_configs.rs
@@ -123,10 +123,10 @@ pub async fn handle(
     )
 }
 
-/// Denies every resource when `principal` is known but is not allowed to alter topic
-/// configuration, or when its permissions could not be read. `None` means SASL is off, which
-/// this gateway treats as no principal to enforce against - the same choice the rest of this
-/// gateway makes when authentication itself is not configured.
+/// Denies every resource when `principal` is not allowed to alter topic configuration, or when
+/// its permissions could not be read. `None` means no listener of this gateway names principals,
+/// so there is nothing to enforce against; once one does, a connection that proved no identity
+/// carries [`AuthenticatedPrincipal::anonymous`] instead and is denied here.
 fn authorize(
     principal: Option<&AuthenticatedPrincipal>,
     resources: &[AlterConfigsResource],
@@ -144,9 +144,8 @@ fn authorize(
             "AlterConfigs asked on a connection whose permissions were never read; denying"
         );
     }
-    let message = StrBytes::from_static_str(
-        "the authenticated principal is not authorized to alter topic configuration",
-    );
+    let message =
+        StrBytes::from_static_str("the principal is not authorized to alter topic configuration");
     Some(
         resources
             .iter()
diff --git a/gateways/kafka/src/protocol/handlers/delete_topics.rs b/gateways/kafka/src/protocol/handlers/delete_topics.rs
index bd41fd5ae..7d5318a0e 100644
--- a/gateways/kafka/src/protocol/handlers/delete_topics.rs
+++ b/gateways/kafka/src/protocol/handlers/delete_topics.rs
@@ -152,10 +152,10 @@ pub async fn handle(
     respond_or_close(encode_message(&resp, api_version, 256), "DeleteTopics")
 }
 
-/// Denies every requested topic when `principal` is known but is not allowed to delete topic
-/// data, or when its permissions could not be read. `None` means SASL is off, which this
-/// gateway treats as no principal to enforce against - the same choice the rest of this
-/// gateway makes when authentication itself is not configured.
+/// Denies every requested topic when `principal` is not allowed to delete topic data, or when
+/// its permissions could not be read. `None` means no listener of this gateway names principals,
+/// so there is nothing to enforce against; once one does, a connection that proved no identity
+/// carries [`AuthenticatedPrincipal::anonymous`] instead and is denied here.
 fn authorize(
     principal: Option<&AuthenticatedPrincipal>,
     topic_names: &[TopicName],
@@ -173,8 +173,7 @@ fn authorize(
             "DeleteTopics asked on a connection whose permissions were never read; denying"
         );
     }
-    let message =
-        StrBytes::from_static_str("the authenticated principal is not authorized to delete topics");
+    let message = StrBytes::from_static_str("the principal is not authorized to delete topics");
     Some(
         topic_names
             .iter()
diff --git a/gateways/kafka/src/server.rs b/gateways/kafka/src/server.rs
index 6000a8d54..3610a2690 100644
--- a/gateways/kafka/src/server.rs
+++ b/gateways/kafka/src/server.rs
@@ -25,7 +25,7 @@ use kafka_protocol::messages::RequestHeader;
 use kafka_protocol::protocol::Decodable;
 use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
 use tokio::net::{TcpListener, TcpStream};
-use tokio::sync::{Semaphore, broadcast};
+use tokio::sync::{Semaphore, SemaphorePermit, broadcast};
 use tokio::task::JoinSet;
 use tokio::time::{timeout, timeout_at};
 use tokio_util::sync::CancellationToken;
@@ -42,7 +42,6 @@ use crate::bridge::IggyBridge;
 use crate::error::{KafkaProtocolError, Result};
 use crate::group::{GroupCoordinator, GroupCoordinatorConfig};
 use crate::listener::{ListenerConfig, SecurityProtocol};
-use crate::protocol::acl::PrincipalPermissions;
 use crate::protocol::api::{
     API_KEY_DESCRIBE_ACLS, API_KEY_SASL_AUTHENTICATE, API_KEY_SASL_HANDSHAKE, BrokerAdvertise,
     ConnectionState, DEFAULT_KAFKA_PORT, ERROR_ILLEGAL_SASL_STATE, ERROR_INVALID_REQUEST,
@@ -55,17 +54,13 @@ use crate::protocol::api::{
 use crate::protocol::handlers::api_versions::Advertisement;
 use crate::protocol::header::{request_header_version, response_header_version};
 use crate::protocol::sasl::{
-    PlainCredentials, SASL_AUTHENTICATE_MAX_VERSION, SASL_HANDSHAKE_VERSION, SaslAction, SaslState,
-    parse_plain,
+    SASL_AUTHENTICATE_MAX_VERSION, SASL_HANDSHAKE_VERSION, SaslAction, SaslState, parse_plain,
 };
-use crate::tls::{TlsConfig, TlsState};
+use crate::tls::{IdentityError, TlsConfig, TlsState};
 
 const READ_CHUNK: usize = 65536;
 const GATEWAY_LOG_TARGET: &str = env!("CARGO_CRATE_NAME");
 
-/// Kafka's name for a client that proved no identity, as `DescribeAcls` renders it.
-const ANONYMOUS_PRINCIPAL: &str = "ANONYMOUS";
-
 /// Builds the log filter, forcing the Iggy SDK quiet unless the operator asked otherwise.
 ///
 /// This is a credential-disclosure control, not noise reduction. The SDK logs the username it
@@ -117,7 +112,8 @@ pub struct GatewayConfig {
     /// Required exactly when one of those exists.
     pub tls: Option<TlsConfig>,
     pub max_frame_size: usize,
-    /// Maximum concurrent connections accepted before new ones are rejected.
+    /// Maximum concurrent connections each listener accepts before rejecting new ones. Every
+    /// listener has its own allowance, so clients of one cannot use up another's.
     pub max_connections: usize,
     /// Bound on how long an accepted connection may sit idle before sending the next
     /// frame's length prefix. Kafka brokers default `connections.max.idle.ms` to 10 minutes;
@@ -344,6 +340,10 @@ struct Listener {
     /// Whether this listener names a principal, by SASL or by a verified client certificate.
     /// Decides whether `DescribeAcls` is advertised and answered.
     acls_enabled: bool,
+    /// Whether a connection here that names no principal is served as
+    /// [`AuthenticatedPrincipal::anonymous`]. True on every listener without SASL once any
+    /// listener of the gateway names principals, so the permission gates hold there too.
+    anonymous_without_principal: bool,
 }
 
 impl Listener {
@@ -421,7 +421,7 @@ impl KafkaGateway {
         listeners: Vec<BoundListener>,
         mut shutdown: broadcast::Receiver<()>,
     ) -> Result<()> {
-        self.check_sasl_wiring()?;
+        self.check_sasl_wiring(&listeners)?;
         let tls = self.check_tls_wiring(&listeners)?;
         if listeners.is_empty() {
             return Err(KafkaProtocolError::InvalidConfig(
@@ -436,6 +436,12 @@ impl KafkaGateway {
         let acls_by_certificate = tls
             .as_ref()
             .is_some_and(|tls| tls.config().client_auth.is_enabled());
+        let names_principals = |protocol: SecurityProtocol| {
+            protocol.uses_sasl() || (protocol.authenticates_by_certificate() && acls_by_certificate)
+        };
+        let any_names_principals = listeners
+            .iter()
+            .any(|listener| names_principals(listener.config.protocol));
 
         let mut bound = Vec::with_capacity(listeners.len());
         for BoundListener { config, socket } in listeners {
@@ -454,8 +460,8 @@ impl KafkaGateway {
                 Arc::new(Listener {
                     protocol,
                     broker,
-                    acls_enabled: protocol.uses_sasl()
-                        || (protocol.authenticates_by_certificate() && acls_by_certificate),
+                    acls_enabled: names_principals(protocol),
+                    anonymous_without_principal: any_names_principals && !protocol.uses_sasl(),
                 }),
                 socket,
             ));
@@ -478,7 +484,6 @@ impl KafkaGateway {
             self.config.max_concurrent_authentications,
         ));
         let tracker = TaskTracker::new();
-        let conn_limiter = Arc::new(Semaphore::new(self.config.max_connections));
         let drain_timeout = self.config.shutdown_drain_timeout;
 
         if let Some(tls) = &tls {
@@ -495,7 +500,7 @@ impl KafkaGateway {
                 state: Arc::clone(&state),
                 auth: Arc::clone(&shared_auth),
                 tracker: tracker.clone(),
-                conn_limiter: Arc::clone(&conn_limiter),
+                conn_limiter: Arc::new(Semaphore::new(self.config.max_connections)),
                 cancel: cancel.clone(),
                 tls: tls.clone(),
             }));
@@ -521,14 +526,18 @@ impl KafkaGateway {
                 Err(join_error) => Err(io::Error::other(join_error).into()),
             },
         };
-        drain(&tracker, &cancel, drain_timeout).await;
+        // The accept loops stop first, so no connection is spawned after the drain starts waiting.
+        cancel.cancel();
         accept_loops.shutdown().await;
+        drain(&tracker, &cancel, drain_timeout).await;
         outcome
     }
 
     /// Refuses to start when the SASL listeners and the configured authenticator disagree.
-    fn check_sasl_wiring(&self) -> Result<()> {
-        let sasl_enabled = self.config.sasl_enabled();
+    fn check_sasl_wiring(&self, listeners: &[BoundListener]) -> Result<()> {
+        let sasl_enabled = listeners
+            .iter()
+            .any(|listener| listener.config.protocol.uses_sasl());
         if !sasl_enabled && self.authenticator.is_some() {
             // The mirror of the guard below, and the quieter mistake: a verifier attached while no
             // listener runs SASL means every connection is served unauthenticated, with nothing
@@ -576,11 +585,20 @@ impl KafkaGateway {
                     .into(),
             ));
         }
-        let maps_identities = tls_config.client_auth.is_enabled()
-            && listeners
-                .iter()
-                .any(|listener| listener.config.protocol.authenticates_by_certificate());
-        if maps_identities && self.principal_resolver.is_none() && self.bridge.is_none() {
+        let has_ssl_listener = listeners
+            .iter()
+            .any(|listener| listener.config.protocol.authenticates_by_certificate());
+        if tls_config.client_auth.is_enabled() && !has_ssl_listener {
+            return Err(KafkaProtocolError::InvalidConfig(format!(
+                "client authentication is '{}' but no SSL listener is configured; it applies to \
+                 SSL listeners only, and a SASL_SSL listener asks for no client certificate",
+                tls_config.client_auth
+            )));
+        }
+        if tls_config.client_auth.is_enabled()
+            && self.principal_resolver.is_none()
+            && self.bridge.is_none()
+        {
             // A certificate names an Iggy user, and only an Iggy session can say whether that
             // user exists. Admitting the name unchecked would let any certificate from the CA
             // claim any account.
@@ -615,10 +633,13 @@ async fn accept_loop(this: AcceptLoop) -> Result<()> {
             () = this.cancel.cancelled() => return Ok(()),
             accepted = this.socket.accept() => accepted,
         };
+        if this.cancel.is_cancelled() {
+            return Ok(());
+        }
         match accepted {
             Ok((stream, peer)) => {
                 let Ok(permit) = Arc::clone(&this.conn_limiter).try_acquire_owned() else {
-                    warn!(%peer, max_connections = this.config.max_connections, "connection limit reached, rejecting");
+                    warn!(%peer, protocol = %this.listener.protocol, max_connections = this.config.max_connections, "listener connection limit reached, rejecting");
                     continue;
                 };
                 if let Err(e) = stream.set_nodelay(true) {
@@ -677,9 +698,16 @@ async fn serve_connection(stream: TcpStream, connection: Connection) {
         // unfinished handshake holds a `max_connections` permit.
         let handshake = timeout(
             connection.config.pre_auth_timeout,
-            tls.acceptor().accept(stream),
+            tls.acceptor(connection.listener.protocol).accept(stream),
         );
-        let tls_stream = match handshake.await {
+        let handshake = tokio::select! {
+            () = connection.cancel.cancelled() => {
+                debug!(%peer, "TLS handshake abandoned by shutdown");
+                return;
+            }
+            handshake = handshake => handshake,
+        };
+        let tls_stream = match handshake {
             Ok(Ok(tls_stream)) => tls_stream,
             Ok(Err(error)) => {
                 // debug!, not warn!: a plaintext client on the TLS port, an untrusted client
@@ -695,6 +723,12 @@ async fn serve_connection(stream: TcpStream, connection: Connection) {
         let certificate_name = if connection.listener.protocol.authenticates_by_certificate() {
             match tls.principal_name(tls_stream.get_ref().1) {
                 Ok(name) => name,
+                // warn!: the CA signed this certificate, so a subject no rule maps is a mapping
+                // rule the operator has to fix.
+                Err(IdentityError::NoMatchingRule { subject }) => {
+                    warn!(%peer, subject, "client certificate subject matches no principal mapping rule; closing");
+                    return;
+                }
                 Err(error) => {
                     debug!(%peer, %error, "client certificate names no principal; closing");
                     return;
@@ -937,6 +971,8 @@ where
             return Ok(());
         };
         Some(resolved)
+    } else if listener.anonymous_without_principal {
+        Some(AuthenticatedPrincipal::anonymous())
     } else {
         None
     };
@@ -1020,32 +1056,33 @@ async fn resolve_certificate_principal(
         error!(%peer, "a client certificate named a principal but nothing can look it up");
         return None;
     };
+    // The lookup is an Iggy call per handshake, so it shares the authentication slots with SASL.
+    let lookup = within_auth_budget(ctx, "certificate identity lookup", |slot| async move {
+        let _slot = slot;
+        resolver.resolve(username).await
+    });
     let outcome = tokio::select! {
         () = ctx.cancel.cancelled() => {
             debug!(%peer, "certificate identity lookup abandoned by shutdown");
             return None;
         }
-        outcome = timeout(ctx.config.pre_auth_timeout, resolver.resolve(username)) => outcome,
+        outcome = lookup => outcome?,
     };
     match outcome {
-        Ok(Ok(principal)) => {
+        Ok(principal) => {
             debug!(%peer, username, "client certificate authenticated");
             Some(principal)
         }
-        Ok(Err(AuthError::Rejected)) => {
+        Err(AuthError::Rejected) => {
             // warn!, not debug!: the certificate chained to the trusted CA, so this is an account
             // the operator meant to exist, or a mapping rule that produced the wrong name.
             warn!(%peer, username, "client certificate names no active Iggy user; closing");
             None
         }
-        Ok(Err(AuthError::Unavailable)) => {
+        Err(AuthError::Unavailable) => {
             warn!(%peer, username, "could not look up the certificate's Iggy user; closing");
             None
         }
-        Err(_elapsed) => {
-            warn!(%peer, username, "certificate identity lookup did not finish within the pre-authentication budget");
-            None
-        }
     }
 }
 
@@ -1097,7 +1134,9 @@ async fn authenticate_token(
             debug!(%peer, "SASL authentication abandoned by shutdown");
             return (HandleOutcome::Close, None);
         }
-        verified = verify_within_budget(ctx, authenticator, &credentials) => verified,
+        verified = within_auth_budget(ctx, "SASL authentication", |slot| {
+            authenticator.authenticate(&credentials, slot)
+        }) => verified,
     };
 
     let Some(result) = verified else {
@@ -1138,9 +1177,9 @@ async fn authenticate_token(
 ///
 /// Only reachable on a listener that names principals: elsewhere the key is not advertised and
 /// falls through to ordinary dispatch, which refuses it. On a SASL listener the SASL gate refuses
-/// every key but one before a principal exists, so a missing principal there is a gateway fault.
-/// On an `SSL` listener that only requests a certificate, a client that presented none is
-/// Kafka's anonymous principal, and is described as holding nothing.
+/// every key but one before a principal exists, and every other such listener starts each
+/// connection with a principal, anonymous when no certificate named one. A missing principal
+/// is therefore a gateway fault.
 fn describe_acls(
     ctx: &ConnectionContext<'_>,
     principal: Option<&AuthenticatedPrincipal>,
@@ -1148,26 +1187,14 @@ fn describe_acls(
     body: Bytes,
 ) -> HandleOutcome {
     let peer = ctx.peer;
-    let anonymous;
-    let principal = match principal {
-        Some(principal) => principal,
-        None if ctx.listener.protocol.uses_sasl() => {
-            // `error!` rather than `debug!` on purpose, unlike every other refusal here: reaching
-            // this means the routing guards above disagree with each other, which is a gateway
-            // fault and not something a client can provoke.
-            error!(%peer, "DescribeAcls reached a connection with no authenticated principal");
-            // Not `encode_error_for_key`: key 29 is absent from `SUPPORTED_RANGES`, so that helper
-            // always returns `Close` here and the code would read as if it answers when it cannot.
-            return respond_describe_acls_error(api_version, ERROR_ILLEGAL_SASL_STATE, true);
-        }
-        None => {
-            anonymous = AuthenticatedPrincipal {
-                username: ANONYMOUS_PRINCIPAL.to_string(),
-                permissions: PrincipalPermissions::default(),
-                permissions_known: true,
-            };
-            &anonymous
-        }
+    let Some(principal) = principal else {
+        // `error!` rather than `debug!` on purpose, unlike every other refusal here: reaching
+        // this means the routing guards above disagree with each other, which is a gateway
+        // fault and not something a client can provoke.
+        error!(%peer, "DescribeAcls reached a connection with no authenticated principal");
+        // Not `encode_error_for_key`: key 29 is absent from `SUPPORTED_RANGES`, so that helper
+        // always returns `Close` here and the code would read as if it answers when it cannot.
+        return respond_describe_acls_error(api_version, ERROR_ILLEGAL_SASL_STATE, true);
     };
     // The firewall table cannot cover this key: it is kept out of `SUPPORTED_RANGES` on purpose,
     // so the advertised range would otherwise be enforced only by whatever `kafka_protocol`'s
@@ -1199,32 +1226,37 @@ fn describe_acls(
     }
 }
 
-/// Waits for an authentication slot, then verifies, each within the pre-authentication budget.
+/// Waits for an authentication slot, then runs `work` holding it, each within the
+/// pre-authentication budget. `None` means a budget ran out.
 ///
 /// Two budgets rather than one shared deadline. The wait needs its own bound so a queued
 /// connection cannot hold a `max_connections` permit for as long as the backlog takes to drain,
-/// which is the invariant `pre_auth_timeout` is documented to enforce. The verification's budget
-/// starts once the slot is held, because cutting a verification short does not stop the login it
-/// started inside Iggy: a verification that inherited whatever the queue left of a shared deadline
-/// would be abandoned mid-hash and hand its slot to the next one while Iggy is still working.
-async fn verify_within_budget(
-    ctx: &ConnectionContext<'_>,
-    authenticator: &dyn SaslAuthenticator,
-    credentials: &PlainCredentials,
-) -> Option<std::result::Result<AuthenticatedPrincipal, AuthError>> {
+/// which is the invariant `pre_auth_timeout` is documented to enforce. The work's budget starts
+/// once the slot is held, because cutting it short does not stop the call it started inside Iggy:
+/// work that inherited whatever the queue left of a shared deadline would be abandoned mid-hash
+/// and hand its slot to the next one while Iggy is still working.
+async fn within_auth_budget<'a, T, Work, Fut>(
+    ctx: &ConnectionContext<'a>,
+    operation: &'static str,
+    work: Work,
+) -> Option<T>
+where
+    Work: FnOnce(SemaphorePermit<'a>) -> Fut,
+    Fut: Future<Output = T>,
+{
     let peer = ctx.peer;
     let budget = ctx.config.pre_auth_timeout;
     let Ok(acquired) = timeout(budget, ctx.auth_slots.acquire()).await else {
-        warn!(%peer, "no authentication slot came free within the pre-authentication budget");
+        warn!(%peer, operation, "no authentication slot came free within the pre-authentication budget");
         return None;
     };
     // Acquire fails only once the semaphore is closed, which this gateway never does.
     let Ok(slot) = acquired else {
-        error!(%peer, "authentication slots unavailable");
+        error!(%peer, operation, "authentication slots unavailable");
         return None;
     };
-    let Ok(result) = timeout(budget, authenticator.authenticate(credentials, slot)).await else {
-        warn!(%peer, "authentication did not complete within the pre-authentication budget");
+    let Ok(result) = timeout(budget, work(slot)).await else {
+        warn!(%peer, operation, "did not complete within the pre-authentication budget");
         return None;
     };
     Some(result)
@@ -1379,11 +1411,11 @@ async fn close_gracefully<S: AsyncRead + AsyncWrite + Unpin>(
     budget: Duration,
     cancel: &CancellationToken,
 ) {
-    if stream.shutdown().await.is_err() {
-        return;
-    }
     let mut discard = [0u8; 4096];
     let drain_input = async {
+        if stream.shutdown().await.is_err() {
+            return;
+        }
         while let Ok(read) = stream.read(&mut discard).await {
             if read == 0 {
                 break;
@@ -1427,7 +1459,13 @@ async fn send_response<S: AsyncWrite + Unpin>(
         prefix.put_u8(0); // empty tagged fields
     }
     let mut frame = prefix.freeze().chain(body);
-    timeout(write_timeout, stream.write_all_buf(&mut frame))
+    // The flush matters on TLS: the stream reports a write done once rustls holds the record,
+    // and the tail of a large response would otherwise sit unsent until the next write.
+    let write = async {
+        stream.write_all_buf(&mut frame).await?;
+        stream.flush().await
+    };
+    timeout(write_timeout, write)
         .await
         .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "write timeout"))??;
     Ok(())
diff --git a/gateways/kafka/src/tls/identity.rs b/gateways/kafka/src/tls/identity.rs
index e7917fe90..877e5061a 100644
--- a/gateways/kafka/src/tls/identity.rs
+++ b/gateways/kafka/src/tls/identity.rs
@@ -19,15 +19,23 @@
 //!
 //! Kafka hands `ssl.principal.mapping.rules` the subject as Java's `X500Principal.getName()`
 //! renders it: RFC 2253, most specific RDN first, no spaces after the commas. Operators write
-//! their rules against that rendering, so this one matches it rather than x509-parser's own
-//! `Display`, which keeps the certificate's order and pads with spaces.
+//! their rules against that rendering, so this one follows `sun.security.x509.AVA`'s
+//! `toRFC2253String` (JDK 11 to 21) rather than x509-parser's own `Display`, which keeps the
+//! certificate's order and pads with spaces. Malformed UTF-8 and BMP values are the one case not
+//! checked against Java: both sides substitute U+FFFD, possibly not one for one.
 
 use std::fmt::Write as _;
 use std::str::FromStr;
 
 use regex::{Captures, Regex};
+use regex_syntax::ast::{
+    self, Assertion, AssertionKind, Ast, ClassPerl, ClassPerlKind, ClassSetItem, Flag, Flags, Span,
+    Visitor,
+};
 use thiserror::Error;
 use x509_parser::asn1_rs::{Any, Tag, ToDer};
+use x509_parser::error::X509Error;
+use x509_parser::nom;
 use x509_parser::parse_x509_certificate;
 use x509_parser::x509::{AttributeTypeAndValue, RelativeDistinguishedName, X509Name};
 
@@ -35,19 +43,86 @@ use x509_parser::x509::{AttributeTypeAndValue, RelativeDistinguishedName, X509Na
 #[derive(Debug, Error)]
 pub enum IdentityError {
     #[error("the client certificate could not be parsed: {0}")]
-    Certificate(String),
+    Certificate(#[from] nom::Err<X509Error>),
     #[error("no principal mapping rule matches the certificate subject '{subject}'")]
     NoMatchingRule { subject: String },
 }
 
+/// Why `ssl.principal.mapping.rules` text did not parse.
+#[derive(Debug, Error)]
+pub enum MappingRuleError {
+    #[error("the rule list is empty; the default is DEFAULT")]
+    Empty,
+    #[error("the rule list ends with a comma")]
+    TrailingComma,
+    #[error("'{0}' is neither DEFAULT nor RULE:pattern/replacement/[LU]")]
+    UnknownRule(String),
+    #[error("expected ',' or the end of the list before '{0}'")]
+    MissingSeparator(String),
+    #[error("rule '{0}' has no '/' after its pattern")]
+    UnterminatedPattern(String),
+    #[error("rule '{0}' has no '/' after its replacement")]
+    UnterminatedReplacement(String),
+    #[error("rule pattern '{pattern}' is not a valid regex: {source}")]
+    InvalidPattern {
+        pattern: String,
+        #[source]
+        source: regex::Error,
+    },
+    #[error("rule pattern '{pattern}' uses '{construct}': {reason}")]
+    JavaIncompatible {
+        pattern: String,
+        construct: String,
+        reason: JavaIncompatibility,
+    },
+    #[error("replacement '{replacement}' of rule pattern '{pattern}' is invalid: {source}")]
+    InvalidReplacement {
+        pattern: String,
+        replacement: String,
+        #[source]
+        source: ReplacementError,
+    },
+}
+
+/// A pattern construct whose Rust `regex` meaning admits subjects Java's `Pattern` rejects.
+#[derive(Debug, Error, PartialEq, Eq, Clone, Copy)]
+pub enum JavaIncompatibility {
+    #[error(
+        "the case-insensitive flag folds Unicode in Rust (the Kelvin sign matches 'k'), ASCII in Java"
+    )]
+    CaseInsensitive,
+    #[error("the 'u' and 'U' flags mean different things in Rust and Java")]
+    UnicodeFlag,
+    #[error("Unicode property classes are not supported")]
+    UnicodeClass,
+    #[error("Java reads '[:name:]' as a set of literal characters, not a POSIX class")]
+    PosixClass,
+    #[error("word boundaries are not supported")]
+    WordBoundary,
+}
+
+/// A replacement that `java.util.regex.Matcher` would throw on when the rule is applied.
+#[derive(Debug, Error, PartialEq, Eq)]
+pub enum ReplacementError {
+    #[error("a trailing '\\' escapes nothing")]
+    DanglingEscape,
+    #[error("'$' is followed by neither a group number nor '{{name}}'")]
+    IllegalGroupReference,
+    #[error("the pattern has no group {0}")]
+    NoGroup(usize),
+    #[error("'${{' has no closing '}}'")]
+    UnterminatedGroupName,
+    #[error("the pattern has no group named '{0}'")]
+    NoNamedGroup(String),
+}
+
 /// The subject of a DER certificate, as Kafka's principal builder sees it.
 ///
 /// # Errors
 ///
 /// Returns [`IdentityError::Certificate`] when `certificate` is not a DER X.509 certificate.
 pub fn subject_distinguished_name(certificate: &[u8]) -> Result<String, IdentityError> {
-    let (_, parsed) = parse_x509_certificate(certificate)
-        .map_err(|error| IdentityError::Certificate(error.to_string()))?;
+    let (_, parsed) = parse_x509_certificate(certificate)?;
     Ok(render_rfc2253(parsed.subject()))
 }
 
@@ -76,17 +151,16 @@ fn render_rdn(rdn: &RelativeDistinguishedName<'_>) -> String {
     out
 }
 
-/// `KEYWORD=value` for the attribute types RFC 2253 and Java give a keyword, `OID=#hex` for the
-/// rest, and `#hex` of the DER for any value that is not a printable string. Java hex-encodes
-/// in exactly those cases, and a rule written against its output has to keep matching here.
+/// `KEYWORD=value` for the attribute types Java gives a keyword, `OID=#hex` for the rest, and
+/// `#hex` of the DER for a value whose string type Java does not decode.
 fn render_attribute(out: &mut String, attribute: &AttributeTypeAndValue<'_>) {
     let value = attribute.attr_value();
     if let Some(keyword) = rfc2253_keyword(&attribute.attr_type().to_string()) {
         out.push_str(keyword);
         out.push('=');
         match string_value(value) {
-            Some(text) if !text.chars().any(char::is_control) => escape_into(out, &text),
-            _ => push_hex(out, value),
+            Some(text) => escape_into(out, &text),
+            None => push_hex(out, value),
         }
     } else {
         let _ = write!(out, "{}=", attribute.attr_type());
@@ -112,22 +186,27 @@ fn rfc2253_keyword(oid: &str) -> Option<&'static str> {
     })
 }
 
-/// The text of a directory string, for the string types Java decodes rather than hex-encodes.
+/// The text of a directory string, decoded with the charset `AVA.getCharset` picks for its tag,
+/// or `None` for the tags `AVA.isDerString` rejects, which Java renders as hex
+/// (`NumericString` and `UniversalString` among them).
 fn string_value(value: &Any<'_>) -> Option<String> {
+    let data = value.data;
     match value.tag() {
-        Tag::Utf8String | Tag::PrintableString | Tag::Ia5String | Tag::NumericString => {
-            std::str::from_utf8(value.data).ok().map(str::to_owned)
+        // Latin-1, not ASCII: Java keeps a non-ASCII byte in these types as its own code point.
+        Tag::PrintableString | Tag::Ia5String | Tag::GeneralString | Tag::T61String => {
+            Some(data.iter().map(|&byte| char::from(byte)).collect())
         }
+        Tag::Utf8String => Some(String::from_utf8_lossy(data).into_owned()),
         Tag::BmpString => {
-            let units: Option<Vec<u16>> = value
-                .data
+            let units: Vec<u16> = data
                 .chunks(2)
-                .map(|pair| <[u8; 2]>::try_from(pair).ok().map(u16::from_be_bytes))
+                .map(|pair| match pair {
+                    [high, low] => u16::from_be_bytes([*high, *low]),
+                    _ => 0xFFFD,
+                })
                 .collect();
-            String::from_utf16(&units?).ok()
+            Some(String::from_utf16_lossy(&units))
         }
-        // T.61 is close enough to Latin-1 for the subjects that still carry it.
-        Tag::T61String => Some(value.data.iter().map(|&byte| char::from(byte)).collect()),
         _ => None,
     }
 }
@@ -142,18 +221,35 @@ fn push_hex(out: &mut String, value: &Any<'_>) {
     }
 }
 
-/// Backslash-escapes what Java's RFC 2253 rendering escapes: `,=+<>#;"\` anywhere, and a space
-/// at either end.
+/// Backslash-escapes what Java's RFC 2253 rendering escapes: `,=+<>#;"\` anywhere, NUL as `\00`,
+/// and every space or carriage return in the leading and trailing runs. Everything else, other
+/// control characters included, is written as is.
 fn escape_into(out: &mut String, text: &str) {
-    let last = text.chars().count().saturating_sub(1);
-    for (index, character) in text.chars().enumerate() {
-        let edge_space = character == ' ' && (index == 0 || index == last);
-        if edge_space
-            || matches!(
-                character,
-                ',' | '=' | '+' | '<' | '>' | '#' | ';' | '"' | '\\'
-            )
-        {
+    let mut escaped: Vec<char> = Vec::with_capacity(text.len());
+    for character in text.chars() {
+        if character == '\0' {
+            escaped.extend(['\\', '0', '0']);
+            continue;
+        }
+        if matches!(
+            character,
+            ',' | '=' | '+' | '<' | '>' | '#' | ';' | '"' | '\\'
+        ) {
+            escaped.push('\\');
+        }
+        escaped.push(character);
+    }
+    let is_edge_space = |character: &char| matches!(character, ' ' | '\r');
+    let lead = escaped
+        .iter()
+        .position(|character| !is_edge_space(character))
+        .unwrap_or(escaped.len());
+    let trail = escaped
+        .iter()
+        .rposition(|character| !is_edge_space(character));
+    for (index, character) in escaped.into_iter().enumerate() {
+        let in_trailing_run = trail.is_none_or(|trail| index > trail);
+        if index < lead || in_trailing_run {
             out.push('\\');
         }
         out.push(character);
@@ -161,7 +257,16 @@ fn escape_into(out: &mut String, text: &str) {
 }
 
 /// Kafka's `ssl.principal.mapping.rules`: `RULE:pattern/replacement/[LU]` and `DEFAULT`, comma
-/// separated, tried in order. The first rule whose pattern matches the whole subject decides.
+/// separated, tried in order.
+///
+/// A rule applies when its pattern matches the whole subject (Java's `matches()`). Its result is
+/// then Java's `subject.replaceAll(pattern, replacement)`: every match of the unanchored pattern
+/// in the subject is replaced, an empty match at the end included, so `RULE:(.*)/$1@x/` maps
+/// `alice` to `alice@x@x` exactly as Kafka does.
+///
+/// Patterns are a Java-compatible subset: `\d \s \w` are rewritten to ASCII classes and `.` to
+/// exclude Java's line terminators, and constructs whose Rust meaning is wider than Java's are
+/// refused as [`MappingRuleError::JavaIncompatible`].
 #[derive(Debug, Clone)]
 pub struct PrincipalMappingRules {
     rules: Vec<Rule>,
@@ -172,17 +277,21 @@ enum Rule {
     /// The subject string itself.
     Default,
     Rewrite {
-        /// The operator's pattern anchored at both ends, since Java's `matches()` demands the
-        /// whole subject.
         whole: Regex,
-        /// The pattern as written, for the replacement pass. Java runs `replaceAll` over the
-        /// subject with it unanchored, and `a|ab` on `ab` replaces `a` alone that way.
         finder: Regex,
-        replacement: String,
+        replacement: Vec<Piece>,
         case: Case,
     },
 }
 
+/// One part of a parsed replacement.
+#[derive(Debug, Clone, PartialEq, Eq)]
+enum Piece {
+    Literal(String),
+    Group(usize),
+    Named(String),
+}
+
 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
 enum Case {
     Keep,
@@ -213,11 +322,9 @@ impl PrincipalMappingRules {
                 if !whole.is_match(subject) {
                     return None;
                 }
-                let rewritten = finder.replace_all(subject, |captures: &Captures<'_>| {
-                    expand_replacement(replacement, captures)
-                });
+                let rewritten = replace_all(finder, subject, replacement);
                 Some(match case {
-                    Case::Keep => rewritten.into_owned(),
+                    Case::Keep => rewritten,
                     Case::Lower => rewritten.to_lowercase(),
                     Case::Upper => rewritten.to_uppercase(),
                 })
@@ -227,66 +334,220 @@ impl PrincipalMappingRules {
 }
 
 impl FromStr for PrincipalMappingRules {
-    type Err = String;
+    type Err = MappingRuleError;
 
     fn from_str(raw: &str) -> Result<Self, Self::Err> {
         let mut rules = Vec::new();
         let mut rest = raw.trim_start();
         if rest.is_empty() {
-            return Err("the rule list is empty; the default is DEFAULT".to_string());
+            return Err(MappingRuleError::Empty);
         }
         while !rest.is_empty() {
             if let Some(after) = rest.strip_prefix("DEFAULT") {
                 rules.push(Rule::Default);
                 rest = after;
             } else if let Some(after) = rest.strip_prefix("RULE:") {
-                let (pattern, after) = take_until_slash(after)
-                    .ok_or_else(|| format!("rule '{rest}' has no '/' after its pattern"))?;
-                let (replacement, after) = take_until_slash(after)
-                    .ok_or_else(|| format!("rule '{rest}' has no '/' after its replacement"))?;
-                let (case, after) = match after.chars().next() {
-                    Some('L') => (Case::Lower, &after[1..]),
-                    Some('U') => (Case::Upper, &after[1..]),
-                    _ => (Case::Keep, after),
-                };
-                let finder = Regex::new(&pattern).map_err(|error| {
-                    format!("rule pattern '{pattern}' is not a valid regex: {error}")
-                })?;
-                let whole = Regex::new(&format!("^(?:{pattern})$")).map_err(|error| {
-                    format!("rule pattern '{pattern}' is not a valid regex: {error}")
-                })?;
-                rules.push(Rule::Rewrite {
-                    whole,
-                    finder,
-                    replacement,
-                    case,
-                });
+                let (rule, after) = parse_rewrite(rest, after)?;
+                rules.push(rule);
                 rest = after;
             } else {
-                return Err(format!(
-                    "'{rest}' is neither DEFAULT nor RULE:pattern/replacement/[LU]"
-                ));
+                return Err(MappingRuleError::UnknownRule(rest.to_string()));
             }
             rest = rest.trim_start();
             match rest.strip_prefix(',') {
                 Some(after) => {
                     rest = after.trim_start();
                     if rest.is_empty() {
-                        return Err("the rule list ends with a comma".to_string());
+                        return Err(MappingRuleError::TrailingComma);
                     }
                 }
                 None if rest.is_empty() => {}
-                None => {
-                    return Err(format!(
-                        "expected ',' or the end of the list before '{rest}'"
-                    ));
-                }
+                None => return Err(MappingRuleError::MissingSeparator(rest.to_string())),
             }
         }
         Ok(Self { rules })
     }
 }
 
+/// Parses the `pattern/replacement/[LU]` after `RULE:`, returning the rule and what follows it.
+fn parse_rewrite<'a>(rule: &str, body: &'a str) -> Result<(Rule, &'a str), MappingRuleError> {
+    let (pattern, after) = take_until_slash(body)
+        .ok_or_else(|| MappingRuleError::UnterminatedPattern(rule.to_string()))?;
+    let (replacement, after) = take_until_slash(after)
+        .ok_or_else(|| MappingRuleError::UnterminatedReplacement(rule.to_string()))?;
+    let (case, after) = match after.chars().next() {
+        Some('L') => (Case::Lower, &after[1..]),
+        Some('U') => (Case::Upper, &after[1..]),
+        _ => (Case::Keep, after),
+    };
+    let invalid_pattern = |source| MappingRuleError::InvalidPattern {
+        pattern: pattern.clone(),
+        source,
+    };
+    let java = java_semantics(&pattern)?;
+    let finder = Regex::new(&java).map_err(invalid_pattern)?;
+    let whole = Regex::new(&format!("^(?:{java})$")).map_err(invalid_pattern)?;
+    let pieces = parse_replacement(&replacement, &finder).map_err(|source| {
+        MappingRuleError::InvalidReplacement {
+            pattern: pattern.clone(),
+            replacement: replacement.clone(),
+            source,
+        }
+    })?;
+    Ok((
+        Rule::Rewrite {
+            whole,
+            finder,
+            replacement: pieces,
+            case,
+        },
+        after,
+    ))
+}
+
+/// Rewrites `pattern` so Rust matches what `java.util.regex.Pattern` matches without flags:
+/// `\d \s \w` and their negations become ASCII classes, and `.` outside `(?s)` also stops at
+/// `\r`, U+0085, U+2028 and U+2029. Constructs with no faithful rewrite are refused with their
+/// span.
+fn java_semantics(pattern: &str) -> Result<String, MappingRuleError> {
+    let parsed = ast::parse::Parser::new().parse(pattern).map_err(|error| {
+        MappingRuleError::InvalidPattern {
+            pattern: pattern.to_string(),
+            source: regex::Error::Syntax(error.to_string()),
+        }
+    })?;
+    let rewriter = JavaRewriter {
+        dot_all: vec![false],
+        edits: Vec::new(),
+    };
+    let edits = ast::visit(&parsed, rewriter).map_err(|(span, reason)| {
+        MappingRuleError::JavaIncompatible {
+            pattern: pattern.to_string(),
+            construct: pattern[span.start.offset..span.end.offset].to_string(),
+            reason,
+        }
+    })?;
+    let mut rewritten = pattern.to_string();
+    for (span, replacement) in edits.iter().rev() {
+        rewritten.replace_range(span.start.offset..span.end.offset, replacement);
+    }
+    Ok(rewritten)
+}
+
+const JAVA_DOT: &str = r"[^\n\r\x{85}\x{2028}\x{2029}]";
+
+/// Collects `(span, replacement)` edits in pattern order.
+struct JavaRewriter {
+    /// Whether `.` matches line terminators, one entry per open group.
+    dot_all: Vec<bool>,
+    edits: Vec<(Span, String)>,
+}
+
+impl JavaRewriter {
+    fn apply_flags(&mut self, flags: &Flags) -> Result<(), (Span, JavaIncompatibility)> {
+        for item in &flags.items {
+            match item.kind {
+                ast::FlagsItemKind::Flag(Flag::CaseInsensitive)
+                    if flags.flag_state(Flag::CaseInsensitive) == Some(true) =>
+                {
+                    return Err((item.span, JavaIncompatibility::CaseInsensitive));
+                }
+                ast::FlagsItemKind::Flag(Flag::Unicode | Flag::SwapGreed) => {
+                    return Err((item.span, JavaIncompatibility::UnicodeFlag));
+                }
+                _ => {}
+            }
+        }
+        if let Some(dot_all) = flags.flag_state(Flag::DotMatchesNewLine)
+            && let Some(current) = self.dot_all.last_mut()
+        {
+            *current = dot_all;
+        }
+        Ok(())
+    }
+
+    fn perl(&mut self, class: &ClassPerl, bracketed: bool) {
+        let name = match class.kind {
+            ClassPerlKind::Digit => "digit",
+            ClassPerlKind::Space => "space",
+            ClassPerlKind::Word => "word",
+        };
+        let negation = if class.negated { "^" } else { "" };
+        let ascii = format!("[:{negation}{name}:]");
+        let replacement = if bracketed {
+            ascii
+        } else {
+            format!("[{ascii}]")
+        };
+        self.edits.push((class.span, replacement));
+    }
+}
+
+impl Visitor for JavaRewriter {
+    type Output = Vec<(Span, String)>;
+    type Err = (Span, JavaIncompatibility);
+
+    fn finish(self) -> Result<Self::Output, Self::Err> {
+        Ok(self.edits)
+    }
+
+    fn visit_pre(&mut self, node: &Ast) -> Result<(), Self::Err> {
+        match node {
+            Ast::Group(group) => {
+                let inherited = self.dot_all.last().copied().unwrap_or(false);
+                self.dot_all.push(inherited);
+                if let Some(flags) = group.flags() {
+                    self.apply_flags(flags)?;
+                }
+            }
+            Ast::Flags(set) => self.apply_flags(&set.flags)?,
+            Ast::Dot(span) => {
+                if !self.dot_all.last().copied().unwrap_or(false) {
+                    self.edits.push((**span, JAVA_DOT.to_string()));
+                }
+            }
+            Ast::ClassPerl(class) => self.perl(class, false),
+            Ast::ClassUnicode(class) => {
+                return Err((class.span, JavaIncompatibility::UnicodeClass));
+            }
+            Ast::Assertion(assertion) => refuse_word_boundary(assertion)?,
+            _ => {}
+        }
+        Ok(())
+    }
+
+    fn visit_post(&mut self, node: &Ast) -> Result<(), Self::Err> {
+        if let Ast::Group(_) = node {
+            self.dot_all.pop();
+        }
+        Ok(())
+    }
+
+    fn visit_class_set_item_pre(&mut self, item: &ClassSetItem) -> Result<(), Self::Err> {
+        match item {
+            ClassSetItem::Perl(class) => self.perl(class, true),
+            ClassSetItem::Unicode(class) => {
+                return Err((class.span, JavaIncompatibility::UnicodeClass));
+            }
+            ClassSetItem::Ascii(class) => {
+                return Err((class.span, JavaIncompatibility::PosixClass));
+            }
+            _ => {}
+        }
+        Ok(())
+    }
+}
+
+const fn refuse_word_boundary(assertion: &Assertion) -> Result<(), (Span, JavaIncompatibility)> {
+    match assertion.kind {
+        AssertionKind::StartLine
+        | AssertionKind::EndLine
+        | AssertionKind::StartText
+        | AssertionKind::EndText => Ok(()),
+        _ => Err((assertion.span, JavaIncompatibility::WordBoundary)),
+    }
+}
+
 /// Reads up to the first unescaped `/`, unescaping `\/` on the way and keeping every other
 /// escape for the regex engine. Returns the text and what follows the slash.
 fn take_until_slash(input: &str) -> Option<(String, &str)> {
@@ -309,57 +570,122 @@ fn take_until_slash(input: &str) -> Option<(String, &str)> {
     None
 }
 
-/// Expands a replacement the way `java.util.regex.Matcher` does: `$N` is a group, taking as
-/// many digits as still name an existing group, `${name}` a named group, and `\x` a literal
-/// `x`. A group that did not participate expands to nothing.
-fn expand_replacement(replacement: &str, captures: &Captures<'_>) -> String {
-    let mut out = String::new();
+/// Parses a replacement the way `java.util.regex.Matcher.appendReplacement` reads it: `$N` is a
+/// group, taking as many digits as still name an existing group, `${name}` a named group, and
+/// `\x` a literal `x`.
+///
+/// Stricter than Kafka, which writes `$N` literally when N exceeds a nonzero group count: that is
+/// refused here. The reverse, `$1\$2`, makes Kafka throw while this maps `alice` to `alice$2`,
+/// which is harmless because that Iggy user must still exist.
+fn parse_replacement(replacement: &str, finder: &Regex) -> Result<Vec<Piece>, ReplacementError> {
+    let group_count = finder.captures_len() - 1;
+    let mut pieces = Vec::new();
+    let mut literal = String::new();
     let mut chars = replacement.chars().peekable();
     while let Some(character) = chars.next() {
         match character {
-            '\\' => {
-                if let Some(escaped) = chars.next() {
-                    out.push(escaped);
-                }
-            }
-            '$' => match chars.peek() {
-                Some('{') => {
-                    chars.next();
-                    let name: String = chars.by_ref().take_while(|&c| c != '}').collect();
-                    if let Some(found) = captures.name(&name) {
-                        out.push_str(found.as_str());
-                    }
-                }
-                Some(digit) if digit.is_ascii_digit() => {
-                    let mut group = 0usize;
-                    let mut taken_any = false;
-                    while let Some(&next) = chars.peek() {
-                        let Some(value) = next.to_digit(10) else {
-                            break;
-                        };
-                        let candidate = group * 10 + value as usize;
-                        if taken_any && candidate >= captures.len() {
-                            break;
+            '\\' => literal.push(chars.next().ok_or(ReplacementError::DanglingEscape)?),
+            '$' => {
+                let piece = match chars.next() {
+                    Some('{') => {
+                        let mut name = String::new();
+                        loop {
+                            match chars.next() {
+                                Some('}') => break,
+                                Some(next) => name.push(next),
+                                None => return Err(ReplacementError::UnterminatedGroupName),
+                            }
+                        }
+                        if !finder.capture_names().flatten().any(|known| known == name) {
+                            return Err(ReplacementError::NoNamedGroup(name));
                         }
-                        group = candidate;
-                        taken_any = true;
-                        chars.next();
+                        Piece::Named(name)
                     }
-                    if let Some(found) = captures.get(group) {
-                        out.push_str(found.as_str());
+                    Some(digit) if digit.is_ascii_digit() => {
+                        let mut group = digit.to_digit(10).map_or(0, |value| value as usize);
+                        if group > group_count {
+                            return Err(ReplacementError::NoGroup(group));
+                        }
+                        while let Some(value) = chars.peek().and_then(|next| next.to_digit(10)) {
+                            let candidate = group * 10 + value as usize;
+                            if candidate > group_count {
+                                break;
+                            }
+                            group = candidate;
+                            chars.next();
+                        }
+                        Piece::Group(group)
                     }
+                    _ => return Err(ReplacementError::IllegalGroupReference),
+                };
+                if !literal.is_empty() {
+                    pieces.push(Piece::Literal(std::mem::take(&mut literal)));
                 }
-                _ => out.push('$'),
-            },
-            other => out.push(other),
+                pieces.push(piece);
+            }
+            other => literal.push(other),
         }
     }
+    if !literal.is_empty() {
+        pieces.push(Piece::Literal(literal));
+    }
+    Ok(pieces)
+}
+
+/// Java's `Matcher.replaceAll`: after an empty match the search resumes one character later, and
+/// an empty match right after a non-empty one still counts. Java steps one UTF-16 unit rather than
+/// one character, so the two differ only when an empty match lands before a supplementary-plane
+/// character.
+fn replace_all(finder: &Regex, subject: &str, replacement: &[Piece]) -> String {
+    let mut out = String::with_capacity(subject.len());
+    let mut copied_up_to = 0;
+    let mut search_from = 0;
+    while search_from <= subject.len() {
+        let Some(captures) = finder.captures_at(subject, search_from) else {
+            break;
+        };
+        let found = captures
+            .get(0)
+            .map_or(search_from..search_from, |m| m.range());
+        out.push_str(&subject[copied_up_to..found.start]);
+        expand_into(&mut out, replacement, &captures);
+        copied_up_to = found.end;
+        search_from = if found.is_empty() {
+            match subject[found.end..].chars().next() {
+                Some(next) => found.end + next.len_utf8(),
+                None => break,
+            }
+        } else {
+            found.end
+        };
+    }
+    out.push_str(&subject[copied_up_to..]);
     out
 }
 
+/// A group that did not participate in the match expands to nothing.
+fn expand_into(out: &mut String, replacement: &[Piece], captures: &Captures<'_>) {
+    for piece in replacement {
+        match piece {
+            Piece::Literal(text) => out.push_str(text),
+            Piece::Group(group) => {
+                if let Some(found) = captures.get(*group) {
+                    out.push_str(found.as_str());
+                }
+            }
+            Piece::Named(name) => {
+                if let Some(found) = captures.name(name) {
+                    out.push_str(found.as_str());
+                }
+            }
+        }
+    }
+}
+
 #[cfg(test)]
 mod tests {
     use rcgen::{CertificateParams, DistinguishedName, DnType, DnValue, KeyPair};
+    use x509_parser::prelude::FromDer;
 
     use super::*;
 
@@ -409,6 +735,75 @@ mod tests {
         assert_eq!(subject, r"CN=\ a b\ ");
     }
 
+    #[test]
+    fn given_runs_of_edge_spaces_should_escape_every_one_of_them() {
+        let subject = subject_of(|params| {
+            params
+                .distinguished_name
+                .push(DnType::CommonName, DnValue::Utf8String("  a  ".to_string()));
+        });
+        assert_eq!(subject, r"CN=\ \ a\ \ ");
+    }
+
+    #[test]
+    fn given_a_control_character_should_write_it_raw() {
+        let subject = subject_of(|params| {
+            params
+                .distinguished_name
+                .push(DnType::CommonName, DnValue::Utf8String("a\tb".to_string()));
+        });
+        assert_eq!(subject, "CN=a\tb");
+    }
+
+    #[test]
+    fn given_a_numeric_string_should_render_it_as_hex() {
+        // Name { RDN { CN, NumericString "123" } }; rcgen cannot emit a NumericString.
+        let der = [
+            0x30, 0x0e, 0x31, 0x0c, 0x30, 0x0a, 0x06, 0x03, 0x55, 0x04, 0x03, 0x12, 0x03, 0x31,
+            0x32, 0x33,
+        ];
+        let (_, name) = X509Name::from_der(&der).expect("a DER name");
+        assert_eq!(render_rfc2253(&name), "CN=#1203313233");
+    }
+
+    /// `Name { RDN { CN, value } }` around one DER-encoded value, for string types rcgen cannot
+    /// emit or contents it refuses.
+    fn common_name_with(value: &[u8]) -> String {
+        let attribute_len = u8::try_from(5 + value.len()).expect("a short value");
+        let mut der = vec![0x30, attribute_len + 4, 0x31, attribute_len + 2];
+        der.extend([0x30, attribute_len, 0x06, 0x03, 0x55, 0x04, 0x03]);
+        der.extend(value);
+        let (_, name) = X509Name::from_der(&der).expect("a DER name");
+        render_rfc2253(&name)
+    }
+
+    #[test]
+    fn given_non_ascii_bytes_in_an_ascii_string_type_should_decode_them_as_latin_1() {
+        for tag in [0x13, 0x16, 0x1b] {
+            assert_eq!(
+                common_name_with(&[tag, 0x03, b'a', 0xe9, b'b']),
+                "CN=a\u{e9}b",
+                "tag {tag:#04x}"
+            );
+        }
+    }
+
+    #[test]
+    fn given_a_universal_string_should_render_it_as_hex() {
+        assert_eq!(
+            common_name_with(&[0x1c, 0x04, 0x00, 0x00, 0x00, b'a']),
+            "CN=#1c0400000061"
+        );
+    }
+
+    #[test]
+    fn given_a_nul_character_should_escape_it_as_two_hex_digits() {
+        assert_eq!(
+            common_name_with(&[0x0c, 0x03, b'a', 0x00, b'b']),
+            "CN=a\\00b"
+        );
+    }
+
     #[test]
     fn given_an_attribute_without_a_keyword_should_render_its_oid_and_hex_value() {
         let subject = subject_of(|params| {
@@ -506,6 +901,63 @@ mod tests {
         assert_eq!(named.map("CN=bob,O=x").as_deref(), Some("bob"));
     }
 
+    #[test]
+    fn given_a_pattern_that_also_matches_empty_should_replace_like_java_replace_all() {
+        let rules: PrincipalMappingRules = "RULE:(.*)/$1@x/".parse().expect("valid");
+        assert_eq!(rules.map("alice").as_deref(), Some("alice@x@x"));
+    }
+
+    #[test]
+    fn given_more_digits_than_groups_should_take_the_longest_existing_group() {
+        let rules: PrincipalMappingRules = "RULE:^CN=(\\w+)$/$12/".parse().expect("valid");
+        assert_eq!(rules.map("CN=alice").as_deref(), Some("alice2"));
+    }
+
+    #[test]
+    fn given_a_group_beyond_the_patterns_count_should_refuse_what_kafka_writes_literally() {
+        match "RULE:^CN=(.*)$/$2/".parse::<PrincipalMappingRules>() {
+            Err(MappingRuleError::InvalidReplacement { source, .. }) => {
+                assert_eq!(source, ReplacementError::NoGroup(2));
+            }
+            other => panic!("Kafka maps this to '$2'; the gateway refuses it, got {other:?}"),
+        }
+    }
+
+    #[test]
+    fn given_an_escaped_dollar_after_a_group_should_write_it_literally() {
+        let rules: PrincipalMappingRules = "RULE:^CN=(.*)$/$1\\$2/".parse().expect("valid");
+        assert_eq!(rules.map("CN=alice").as_deref(), Some("alice$2"));
+    }
+
+    #[test]
+    fn given_a_replacement_java_would_throw_on_should_refuse_the_rule() {
+        for (raw, expected) in [
+            (
+                "RULE:^CN=(.*)$/$x/",
+                ReplacementError::IllegalGroupReference,
+            ),
+            (
+                "RULE:^CN=(.*)$/a$/",
+                ReplacementError::IllegalGroupReference,
+            ),
+            (
+                "RULE:^CN=(?P<user>.*)$/${nope}/",
+                ReplacementError::NoNamedGroup("nope".to_string()),
+            ),
+            (
+                "RULE:^CN=(?P<user>.*)$/${user/",
+                ReplacementError::UnterminatedGroupName,
+            ),
+        ] {
+            match raw.parse::<PrincipalMappingRules>() {
+                Err(MappingRuleError::InvalidReplacement { source, .. }) => {
+                    assert_eq!(source, expected, "for '{raw}'");
+                }
+                other => panic!("'{raw}' must be refused for its replacement, got {other:?}"),
+            }
+        }
+    }
+
     #[test]
     fn given_a_malformed_rule_list_should_refuse() {
         for raw in [
@@ -525,4 +977,126 @@ mod tests {
             );
         }
     }
+
+    #[test]
+    fn given_a_kelvin_sign_should_not_match_an_ascii_word_class() {
+        let rules: PrincipalMappingRules = r"RULE:^CN=(\w+)$/$1/L".parse().expect("valid");
+        assert_eq!(rules.map("CN=\u{212A}afka"), None);
+        assert_eq!(rules.map("CN=Kafka").as_deref(), Some("kafka"));
+        let bracketed: PrincipalMappingRules = r"RULE:^CN=([\w.]+)$/$1/".parse().expect("valid");
+        assert_eq!(bracketed.map("CN=\u{212A}afka"), None);
+        assert_eq!(bracketed.map("CN=k.afka").as_deref(), Some("k.afka"));
+    }
+
+    #[test]
+    fn given_non_ascii_digits_or_spaces_should_not_match_ascii_classes() {
+        let digits: PrincipalMappingRules = r"RULE:^CN=u(\d+)$/$1/".parse().expect("valid");
+        assert_eq!(digits.map("CN=u\u{0661}\u{0662}"), None);
+        assert_eq!(digits.map("CN=u12").as_deref(), Some("12"));
+        let spaces: PrincipalMappingRules = r"RULE:^CN=a\sb$/ab/".parse().expect("valid");
+        assert_eq!(spaces.map("CN=a\u{00A0}b"), None);
+        assert_eq!(spaces.map("CN=a b").as_deref(), Some("ab"));
+        let negated: PrincipalMappingRules = r"RULE:^CN=(\D+)$/$1/".parse().expect("valid");
+        assert_eq!(
+            negated.map("CN=\u{0661}").as_deref(),
+            Some("\u{0661}"),
+            "Java's \\D matches every non-ASCII digit"
+        );
+    }
+
+    #[test]
+    fn given_a_java_line_terminator_should_not_match_dot_outside_dotall() {
+        let rules: PrincipalMappingRules = "RULE:^CN=(.*)$/$1/".parse().expect("valid");
+        for terminator in ['\r', '\u{85}', '\u{2028}', '\u{2029}'] {
+            assert_eq!(rules.map(&format!("CN=a{terminator}b")), None);
+        }
+        let dot_all: PrincipalMappingRules = "RULE:(?s)^CN=(.*)$/$1/".parse().expect("valid");
+        assert_eq!(dot_all.map("CN=a\u{2028}b").as_deref(), Some("a\u{2028}b"));
+        let scoped: PrincipalMappingRules = "RULE:^CN=(?s:(.))(.)$/$1$2/".parse().expect("valid");
+        assert_eq!(scoped.map("CN=\u{85}x").as_deref(), Some("\u{85}x"));
+        assert_eq!(scoped.map("CN=x\u{85}"), None, "(?s:) ends with its group");
+    }
+
+    #[test]
+    fn given_a_non_ascii_name_should_still_map_like_kafka() {
+        for raw in ["RULE:^CN=([^,]+).*$/$1/", "RULE:^CN=(.*)$/$1/"] {
+            let rules: PrincipalMappingRules = raw.parse().expect("valid");
+            assert_eq!(
+                rules.map("CN=Zo\u{eb}").as_deref(),
+                Some("Zo\u{eb}"),
+                "{raw}"
+            );
+            assert_eq!(
+                rules.map("CN=Jos\u{e9}").as_deref(),
+                Some("Jos\u{e9}"),
+                "{raw}"
+            );
+        }
+    }
+
+    #[test]
+    fn given_a_construct_without_java_semantics_should_refuse_the_rule() {
+        for (raw, construct, expected) in [
+            (
+                "RULE:(?i)^CN=(\u{17F}vc)$/$1/",
+                "i",
+                JavaIncompatibility::CaseInsensitive,
+            ),
+            (
+                "RULE:^CN=(?i:kafka)$/$1/",
+                "i",
+                JavaIncompatibility::CaseInsensitive,
+            ),
+            (
+                "RULE:(?u)^CN=(.*)$/$1/",
+                "u",
+                JavaIncompatibility::UnicodeFlag,
+            ),
+            (
+                "RULE:(?U)^CN=(.*)$/$1/",
+                "U",
+                JavaIncompatibility::UnicodeFlag,
+            ),
+            (
+                r"RULE:^CN=(\pL+)$/$1/",
+                r"\pL",
+                JavaIncompatibility::UnicodeClass,
+            ),
+            (
+                r"RULE:^CN=([\p{Greek}a]+)$/$1/",
+                r"\p{Greek}",
+                JavaIncompatibility::UnicodeClass,
+            ),
+            (
+                "RULE:^CN=([[:alpha:]]+)$/$1/",
+                "[:alpha:]",
+                JavaIncompatibility::PosixClass,
+            ),
+            (
+                r"RULE:^CN=\b(.*)$/$1/",
+                r"\b",
+                JavaIncompatibility::WordBoundary,
+            ),
+            (
+                r"RULE:^CN=(.*)\B$/$1/",
+                r"\B",
+                JavaIncompatibility::WordBoundary,
+            ),
+        ] {
+            match raw.parse::<PrincipalMappingRules>() {
+                Err(MappingRuleError::JavaIncompatible {
+                    construct: found,
+                    reason,
+                    ..
+                }) => {
+                    assert_eq!((found.as_str(), reason), (construct, expected), "{raw}");
+                }
+                other => panic!("'{raw}' must be refused, got {other:?}"),
+            }
+        }
+        let case_sensitive: PrincipalMappingRules = "RULE:(?-i)^CN=(.*)$/$1/"
+            .parse()
+            .expect("(?-i) is Java's default");
+        assert_eq!(case_sensitive.map("CN=a").as_deref(), Some("a"));
+    }
 }
diff --git a/gateways/kafka/src/tls/mod.rs b/gateways/kafka/src/tls/mod.rs
index 85c3ef4f0..873ecef62 100644
--- a/gateways/kafka/src/tls/mod.rs
+++ b/gateways/kafka/src/tls/mod.rs
@@ -35,10 +35,14 @@ use tokio_util::sync::CancellationToken;
 use tracing::{error, info};
 
 use crate::error::{KafkaProtocolError, Result};
+use crate::listener::SecurityProtocol;
 
 pub mod identity;
 
-pub use identity::{IdentityError, PrincipalMappingRules, subject_distinguished_name};
+pub use identity::{
+    IdentityError, MappingRuleError, PrincipalMappingRules, ReplacementError,
+    subject_distinguished_name,
+};
 
 /// How often the certificate files are re-read when nothing else is configured.
 ///
@@ -97,6 +101,10 @@ impl fmt::Display for ClientAuth {
 }
 
 /// TLS material and policy shared by every `SSL` and `SASL_SSL` listener.
+///
+/// `client_auth` applies to `SSL` listeners only. A `SASL_SSL` listener never asks for a client
+/// certificate, as Kafka leaves `ssl.client.auth` at `none` there unless that listener
+/// overrides it.
 #[derive(Debug, Clone)]
 pub struct TlsConfig {
     /// PEM certificate chain, leaf first.
@@ -146,7 +154,7 @@ impl TlsConfig {
 }
 
 /// The bytes last read from disk, kept so a reload can tell whether anything changed.
-#[derive(PartialEq, Eq)]
+#[derive(Clone, PartialEq, Eq)]
 struct Material {
     certificate: Vec<u8>,
     key: Vec<u8>,
@@ -165,12 +173,51 @@ impl Material {
                 .transpose()?,
         })
     }
+
+    async fn read_async(config: &TlsConfig) -> Result<Self> {
+        let client_ca = match config.client_ca_file.as_deref() {
+            Some(path) => Some(read_file_async(path).await?),
+            None => None,
+        };
+        Ok(Self {
+            certificate: read_file_async(&config.cert_file).await?,
+            key: read_file_async(&config.key_file).await?,
+            client_ca,
+        })
+    }
 }
 
 fn read_file(path: &Path) -> Result<Vec<u8>> {
-    fs::read(path).map_err(|error| {
-        KafkaProtocolError::InvalidConfig(format!("cannot read {}: {error}", path.display()))
-    })
+    fs::read(path).map_err(|error| unreadable(path, &error))
+}
+
+async fn read_file_async(path: &Path) -> Result<Vec<u8>> {
+    tokio::fs::read(path)
+        .await
+        .map_err(|error| unreadable(path, &error))
+}
+
+fn unreadable(path: &Path, error: &std::io::Error) -> KafkaProtocolError {
+    KafkaProtocolError::InvalidConfig(format!("cannot read {}: {error}", path.display()))
+}
+
+/// The two server configurations one set of material builds: `SSL` listeners verify client
+/// certificates as `client_auth` says, `SASL_SSL` listeners never ask for one.
+struct ServerConfigs {
+    ssl: Arc<ServerConfig>,
+    sasl_ssl: Arc<ServerConfig>,
+}
+
+impl ServerConfigs {
+    fn build(config: &TlsConfig, material: &Material) -> Result<Self> {
+        let ssl = Arc::new(build_server_config(config, config.client_auth, material)?);
+        let sasl_ssl = if config.client_auth.is_enabled() {
+            Arc::new(build_server_config(config, ClientAuth::None, material)?)
+        } else {
+            Arc::clone(&ssl)
+        };
+        Ok(Self { ssl, sasl_ssl })
+    }
 }
 
 /// The live TLS configuration, swapped under running listeners when the files change.
@@ -180,7 +227,7 @@ fn read_file(path: &Path) -> Result<Vec<u8>> {
 /// lock in the accept path: the swap is an atomic pointer exchange.
 pub struct TlsState {
     config: TlsConfig,
-    current: ArcSwap<ServerConfig>,
+    current: ArcSwap<ServerConfigs>,
     loaded: Mutex<Material>,
 }
 
@@ -210,10 +257,10 @@ impl TlsState {
             )));
         }
         let material = Material::read(&config)?;
-        let server_config = build_server_config(&config, &material)?;
+        let server_configs = ServerConfigs::build(&config, &material)?;
         Ok(Self {
             config,
-            current: ArcSwap::from_pointee(server_config),
+            current: ArcSwap::from_pointee(server_configs),
             loaded: Mutex::new(material),
         })
     }
@@ -223,30 +270,38 @@ impl TlsState {
         &self.config
     }
 
-    /// An acceptor over the configuration current right now.
+    /// An acceptor over the configuration current right now, for a listener speaking
+    /// `protocol`. Only an `SSL` listener asks for a client certificate.
     #[must_use]
-    pub fn acceptor(&self) -> TlsAcceptor {
-        TlsAcceptor::from(self.current.load_full())
+    pub fn acceptor(&self, protocol: SecurityProtocol) -> TlsAcceptor {
+        let current = self.current.load();
+        let config = if protocol.authenticates_by_certificate() {
+            &current.ssl
+        } else {
+            &current.sasl_ssl
+        };
+        TlsAcceptor::from(Arc::clone(config))
     }
 
     /// Re-reads the files and swaps the configuration if they changed.
     ///
     /// Returns `Ok(true)` when new material went live. A read or build failure leaves the current
     /// material serving: a rotation that is half written, or a certificate that does not match
-    /// its key, must not take the listener down.
+    /// its key, must not take the listener down. Material that failed to build is retried on every
+    /// call, so each tick reports the failure until the files are fixed.
     ///
     /// # Errors
     ///
     /// The same conditions as [`Self::load`].
-    pub fn reload(&self) -> Result<bool> {
-        let material = Material::read(&self.config)?;
-        let unchanged = *self.loaded.lock().unwrap_or_else(PoisonError::into_inner) == material;
-        if unchanged {
+    pub async fn reload(&self) -> Result<bool> {
+        let material = Material::read_async(&self.config).await?;
+        if *self.loaded.lock().unwrap_or_else(PoisonError::into_inner) == material {
             return Ok(false);
         }
-        let server_config = build_server_config(&self.config, &material)?;
-        self.current.store(Arc::new(server_config));
+        let server_configs = ServerConfigs::build(&self.config, &material)?;
+        // Recorded only after a successful build, so a failed build is retried every tick.
         *self.loaded.lock().unwrap_or_else(PoisonError::into_inner) = material;
+        self.current.store(Arc::new(server_configs));
         Ok(true)
     }
 
@@ -261,7 +316,7 @@ impl TlsState {
                 () = cancel.cancelled() => return,
                 () = tokio::time::sleep(interval) => {}
             }
-            match self.reload() {
+            match self.reload().await {
                 Ok(true) => info!(
                     cert_file = %self.config.cert_file.display(),
                     "TLS certificate reloaded; new connections use the new material"
@@ -306,7 +361,11 @@ impl TlsState {
     }
 }
 
-fn build_server_config(config: &TlsConfig, material: &Material) -> Result<ServerConfig> {
+fn build_server_config(
+    config: &TlsConfig,
+    client_auth: ClientAuth,
+    material: &Material,
+) -> Result<ServerConfig> {
     // Named explicitly rather than taken from the process default: the Iggy SDK installs its own
     // provider lazily on its first TLS dial, and a listener that came up first would otherwise
     // decide for it, or panic because neither had chosen yet.
@@ -327,11 +386,7 @@ fn build_server_config(config: &TlsConfig, material: &Material) -> Result<Server
     let builder = ServerConfig::builder_with_provider(Arc::clone(&provider))
         .with_safe_default_protocol_versions()
         .map_err(|error| KafkaProtocolError::InvalidConfig(error.to_string()))?;
-    let builder = match (
-        config.client_auth,
-        &material.client_ca,
-        &config.client_ca_file,
-    ) {
+    let builder = match (client_auth, &material.client_ca, &config.client_ca_file) {
         (ClientAuth::None, _, _) => builder.with_no_client_auth(),
         (mode, Some(ca_pem), Some(ca_file)) => {
             let mut roots = RootCertStore::empty();
@@ -430,18 +485,18 @@ mod tests {
         }
     }
 
-    #[test]
-    fn given_a_certificate_and_key_should_load_and_report_no_change_on_reload() {
+    #[tokio::test]
+    async fn given_a_certificate_and_key_should_load_and_report_no_change_on_reload() {
         let dir = tempfile::tempdir().expect("tempdir");
         let (cert, key) = self_signed("first");
         let cert_file = write(dir.path(), "cert.pem", &cert);
         let key_file = write(dir.path(), "key.pem", &key);
         let state = TlsState::load(TlsConfig::new(cert_file, key_file)).expect("loads");
-        assert!(!state.reload().expect("reload reads the same files"));
+        assert!(!state.reload().await.expect("reload reads the same files"));
     }
 
-    #[test]
-    fn given_rotated_files_should_swap_and_keep_the_old_material_on_a_broken_rotation() {
+    #[tokio::test]
+    async fn given_rotated_files_should_swap_and_keep_the_old_material_on_a_broken_rotation() {
         let dir = tempfile::tempdir().expect("tempdir");
         let (cert, key) = self_signed("first");
         let cert_file = write(dir.path(), "cert.pem", &cert);
@@ -454,6 +509,7 @@ mod tests {
         fs::write(&cert_file, &next_cert).expect("rotate certificate");
         let error = state
             .reload()
+            .await
             .expect_err("a certificate that does not match the key must not go live");
         assert!(error.to_string().contains("pair"), "got: {error}");
         assert!(
@@ -462,9 +518,34 @@ mod tests {
         );
 
         fs::write(&key_file, &next_key).expect("rotate key");
-        assert!(state.reload().expect("the completed rotation loads"));
+        assert!(state.reload().await.expect("the completed rotation loads"));
         assert!(!Arc::ptr_eq(&before, &state.current.load_full()));
-        assert!(!state.reload().expect("nothing changed since"));
+        assert!(!state.reload().await.expect("nothing changed since"));
+    }
+
+    #[tokio::test]
+    async fn given_a_broken_rotation_should_report_it_on_every_reload_until_fixed() {
+        let dir = tempfile::tempdir().expect("tempdir");
+        let (cert, key) = self_signed("first");
+        let cert_file = write(dir.path(), "cert.pem", &cert);
+        let key_file = write(dir.path(), "key.pem", &key);
+        let state = TlsState::load(TlsConfig::new(&cert_file, &key_file)).expect("loads");
+
+        let (next_cert, next_key) = self_signed("second");
+        fs::write(&cert_file, &next_cert).expect("rotate certificate");
+        for attempt in 1..=2 {
+            let error = state
+                .reload()
+                .await
+                .expect_err("a mismatched pair must fail on every reload, not only the first");
+            assert!(
+                error.to_string().contains("pair"),
+                "attempt {attempt}: {error}"
+            );
+        }
+
+        fs::write(&key_file, &next_key).expect("rotate key");
+        assert!(state.reload().await.expect("the fixed rotation loads"));
     }
 
     #[test]
diff --git a/gateways/kafka/tests/common/certs.rs b/gateways/kafka/tests/common/certs.rs
index c7297fde9..7fa0dc601 100644
--- a/gateways/kafka/tests/common/certs.rs
+++ b/gateways/kafka/tests/common/certs.rs
@@ -173,6 +173,14 @@ pub async fn connect_tls(
     config: Arc<ClientConfig>,
 ) -> Result<TlsStream<TcpStream>, std::io::Error> {
     let tcp = TcpStream::connect(addr).await?;
+    connect_tls_over(tcp, config).await
+}
+
+/// Runs the client handshake over a socket the caller already connected.
+pub async fn connect_tls_over(
+    tcp: TcpStream,
+    config: Arc<ClientConfig>,
+) -> Result<TlsStream<TcpStream>, std::io::Error> {
     let server_name = ServerName::try_from("localhost").expect("valid server name");
     TlsConnector::from(config).connect(server_name, tcp).await
 }
diff --git a/gateways/kafka/tests/delete_topics_real_bridge_tests.rs b/gateways/kafka/tests/delete_topics_real_bridge_tests.rs
index 81adc88db..800880bbd 100644
--- a/gateways/kafka/tests/delete_topics_real_bridge_tests.rs
+++ b/gateways/kafka/tests/delete_topics_real_bridge_tests.rs
@@ -28,26 +28,44 @@
 
 use std::sync::Arc;
 
+use async_trait::async_trait;
 use bytes::Bytes;
 use iggy::prelude::{Identifier, StreamClient, TopicClient};
 use serial_test::serial;
+use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt};
+use tokio::net::TcpStream;
+use tokio::sync::SemaphorePermit;
 use tokio_util::sync::CancellationToken;
 
+use iggy_gateway_kafka::auth::{AuthError, AuthenticatedPrincipal, SaslAuthenticator};
 use iggy_gateway_kafka::bridge::IggyBridge;
 use iggy_gateway_kafka::group::{GroupCoordinator, GroupCoordinatorConfig};
+use iggy_gateway_kafka::listener::SecurityProtocol;
 use iggy_gateway_kafka::protocol::api::{
-    ERROR_INVALID_REQUEST, ERROR_NONE, ERROR_POLICY_VIOLATION, ERROR_UNKNOWN_TOPIC_OR_PARTITION,
-    GatewayState,
+    API_KEY_DELETE_TOPICS, ERROR_INVALID_REQUEST, ERROR_NONE, ERROR_POLICY_VIOLATION,
+    ERROR_TOPIC_AUTHORIZATION_FAILED, ERROR_UNKNOWN_TOPIC_OR_PARTITION, GatewayState,
 };
 use iggy_gateway_kafka::protocol::handlers::delete_topics;
+use iggy_gateway_kafka::protocol::sasl::PlainCredentials;
+use iggy_gateway_kafka::tls::{ClientAuth, TlsConfig};
+use iggy_gateway_kafka::{GatewayConfig, KafkaGateway};
 
+#[path = "common/certs.rs"]
+mod certs;
 #[path = "common/codec.rs"]
 mod codec;
 #[path = "common/iggy_server.rs"]
 mod iggy_server;
+#[path = "common/server.rs"]
+mod server;
+#[path = "common/tcp.rs"]
+mod tcp;
 
+use certs::{TestPki, connect_tls};
 use codec::{Decoder, Encoder};
 use iggy_server::{TestServer, raw_client};
+use server::{listener, spawn_gateway};
+use tcp::{build_request_frame, parse_response_payload, read_response_frame};
 
 const REQUEST_VERSION: i16 = 5;
 const TEST_MAX_FRAME_SIZE: usize = 8 * 1024 * 1024;
@@ -332,3 +350,117 @@ async fn delete_topics_over_cap_error_message_names_the_limit() {
         "error_message must name the actual cap"
     );
 }
+
+/// Refuses every login: these tests only need a SASL listener to exist beside the one they use.
+#[derive(Debug)]
+struct NoLogins;
+
+#[async_trait]
+impl SaslAuthenticator for NoLogins {
+    async fn authenticate(
+        &self,
+        _credentials: &PlainCredentials,
+        _slot: SemaphorePermit<'_>,
+    ) -> Result<AuthenticatedPrincipal, AuthError> {
+        Err(AuthError::Rejected)
+    }
+}
+
+/// Sends a v5 `DeleteTopics` for `names` over a gateway connection.
+async fn delete_over<S: AsyncRead + AsyncWrite + Unpin>(
+    stream: &mut S,
+    names: &[&str],
+) -> Vec<(Option<String>, i16)> {
+    let frame = build_request_frame(
+        API_KEY_DELETE_TOPICS,
+        REQUEST_VERSION,
+        1,
+        Some("anonymous"),
+        &build_request(names),
+    );
+    stream.write_all(&frame).await.expect("write DeleteTopics");
+    let payload = read_response_frame(stream, TEST_MAX_FRAME_SIZE).await;
+    let (_, body) = parse_response_payload(API_KEY_DELETE_TOPICS, REQUEST_VERSION, payload);
+    decode_all_results(body)
+}
+
+/// A bridge to `server` with one topic, `orders`, to delete.
+async fn bridge_with_a_topic(server: &TestServer) -> Arc<IggyBridge> {
+    let bridge = IggyBridge::connect(server.test_config())
+        .await
+        .expect("bridge should connect to a ready server");
+    bridge
+        .create_kafka_topic("orders", 1)
+        .await
+        .expect("create the topic to delete");
+    Arc::new(bridge)
+}
+
+fn tls_material(pki: &TestPki, dir: &std::path::Path) -> TlsConfig {
+    let (cert_file, key_file) = pki.server_cert("gateway").write(dir, "server");
+    TlsConfig::new(cert_file, key_file)
+}
+
+#[tokio::test]
+#[serial]
+async fn given_requested_client_auth_when_no_certificate_is_presented_should_deny_delete_topics() {
+    let data_dir = tempfile::tempdir().expect("tempdir");
+    let server = TestServer::spawn(data_dir.path()).await;
+    let bridge = bridge_with_a_topic(&server).await;
+    let certs_dir = tempfile::tempdir().expect("certs dir");
+    let pki = TestPki::new();
+    let ca_file = pki.write_ca(certs_dir.path());
+    let config = GatewayConfig {
+        listeners: vec![listener(SecurityProtocol::Ssl)],
+        tls: Some(
+            tls_material(&pki, certs_dir.path()).with_client_auth(ClientAuth::Requested, ca_file),
+        ),
+        ..GatewayConfig::default()
+    };
+    let (addrs, _shutdown) = spawn_gateway(
+        move |config| KafkaGateway::new(config).with_bridge(Some(bridge)),
+        config,
+    );
+
+    let mut stream = connect_tls(addrs[0], pki.client_config(None))
+        .await
+        .expect("a requested certificate may be withheld");
+    assert_eq!(
+        delete_over(&mut stream, &["orders"]).await,
+        vec![(Some("orders".to_string()), ERROR_TOPIC_AUTHORIZATION_FAILED)],
+        "a client that proved nothing holds less than any user, not more"
+    );
+}
+
+#[tokio::test]
+#[serial]
+async fn given_a_plaintext_listener_beside_sasl_ssl_should_deny_delete_topics_there() {
+    let data_dir = tempfile::tempdir().expect("tempdir");
+    let server = TestServer::spawn(data_dir.path()).await;
+    let bridge = bridge_with_a_topic(&server).await;
+    let certs_dir = tempfile::tempdir().expect("certs dir");
+    let pki = TestPki::new();
+    let config = GatewayConfig {
+        listeners: vec![
+            listener(SecurityProtocol::Plaintext),
+            listener(SecurityProtocol::SaslSsl),
+        ],
+        tls: Some(tls_material(&pki, certs_dir.path())),
+        ..GatewayConfig::default()
+    };
+    let (addrs, _shutdown) = spawn_gateway(
+        move |config| {
+            KafkaGateway::new(config)
+                .with_bridge(Some(bridge))
+                .with_authenticator(Arc::new(NoLogins))
+        },
+        config,
+    );
+
+    let mut stream = TcpStream::connect(addrs[0]).await.expect("connect");
+    assert_eq!(
+        delete_over(&mut stream, &["orders"]).await,
+        vec![(Some("orders".to_string()), ERROR_TOPIC_AUTHORIZATION_FAILED)],
+        "the plaintext listener must not bypass what the SASL listener enforces"
+    );
+}
diff --git a/gateways/kafka/tests/tls_listener_tests.rs b/gateways/kafka/tests/tls_listener_tests.rs
index a922dd534..6530edaa6 100644
--- a/gateways/kafka/tests/tls_listener_tests.rs
+++ b/gateways/kafka/tests/tls_listener_tests.rs
@@ -23,13 +23,14 @@
 //! certificate path against a real one is in `kafka_client_e2e_tests.rs`.
 
 use std::collections::HashMap;
+use std::sync::atomic::{AtomicUsize, Ordering};
 use std::sync::{Arc, Mutex};
 use std::time::Duration;
 
 use async_trait::async_trait;
 use bytes::Bytes;
-use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt};
-use tokio::net::TcpStream;
+use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
+use tokio::net::{TcpSocket, TcpStream};
 use tokio::sync::SemaphorePermit;
 
 use iggy_gateway_kafka::auth::{
@@ -51,7 +52,7 @@ mod server;
 #[path = "common/tcp.rs"]
 mod tcp;
 
-use certs::{Issued, TestPki, connect_tls};
+use certs::{Issued, TestPki, connect_tls, connect_tls_over};
 use codec::{Decoder, Encoder};
 use server::{listener, spawn_gateway};
 use tcp::{
@@ -144,6 +145,43 @@ impl PrincipalResolver for KnownUsers {
     }
 }
 
+/// Answers every lookup the same way, or never answers.
+#[derive(Debug)]
+enum BrokenResolver {
+    Unavailable,
+    Hangs,
+}
+
+#[async_trait]
+impl PrincipalResolver for BrokenResolver {
+    async fn resolve(&self, _username: &str) -> Result<AuthenticatedPrincipal, AuthError> {
+        match self {
+            Self::Unavailable => Err(AuthError::Unavailable),
+            Self::Hangs => std::future::pending().await,
+        }
+    }
+}
+
+/// Knows every user, after a fixed delay, and counts the lookups it started.
+#[derive(Debug)]
+struct SlowUsers {
+    delay: Duration,
+    started: AtomicUsize,
+}
+
+#[async_trait]
+impl PrincipalResolver for SlowUsers {
+    async fn resolve(&self, username: &str) -> Result<AuthenticatedPrincipal, AuthError> {
+        self.started.fetch_add(1, Ordering::SeqCst);
+        tokio::time::sleep(self.delay).await;
+        Ok(AuthenticatedPrincipal {
+            username: username.to_string(),
+            permissions: topic_reader(),
+            permissions_known: true,
+        })
+    }
+}
+
 /// Accepts `USERNAME`/`PASSWORD` and nothing else.
 #[derive(Debug)]
 struct FixedCredentials;
@@ -539,7 +577,8 @@ async fn given_requested_client_auth_when_no_certificate_is_presented_should_ser
 }
 
 #[tokio::test]
-async fn given_a_sasl_ssl_listener_with_client_auth_should_take_the_principal_from_sasl() {
+async fn given_client_auth_when_a_client_without_a_certificate_uses_sasl_ssl_should_authenticate_by_sasl()
+ {
     let pki = Pki::new();
     let users = KnownUsers::with("certificate-user", topic_reader());
     let resolver = Arc::clone(&users);
@@ -550,18 +589,20 @@ async fn given_a_sasl_ssl_listener_with_client_auth_should_take_the_principal_fr
                 .with_principal_resolver(resolver)
         },
         quick_config(
-            vec![SecurityProtocol::SaslSsl],
+            vec![SecurityProtocol::Ssl, SecurityProtocol::SaslSsl],
             Some(
                 pki.tls_with_client_auth(ClientAuth::Required)
                     .with_principal_mapping("RULE:^CN=([^,]+).*$/$1/".parse().expect("valid")),
             ),
         ),
     );
+    let [ssl, sasl_ssl] = addrs[..] else {
+        panic!("two listeners")
+    };
 
-    let certificate = pki.authority.client_cert("certificate-user", "Example");
-    let mut stream = connect_tls(addrs[0], pki.authority.client_config(Some(&certificate)))
+    let mut stream = connect_tls(sasl_ssl, pki.authority.client_config(None))
         .await
-        .expect("mTLS handshake");
+        .expect("SASL_SSL asks for no client certificate, as on a Kafka broker");
     assert_eq!(
         sasl_plain(&mut stream, USERNAME, PASSWORD).await,
         ERROR_NONE
@@ -569,13 +610,166 @@ async fn given_a_sasl_ssl_listener_with_client_auth_should_take_the_principal_fr
     let (code, body) = describe_acls(&mut stream).await;
     assert_eq!(code, ERROR_NONE);
     assert!(
-        mentions(&body, &format!("User:{USERNAME}")) && !mentions(&body, "certificate-user"),
-        "with SASL the certificate gates the transport only, as on a Kafka SASL_SSL listener"
+        mentions(&body, &format!("User:{USERNAME}")),
+        "the SASL principal is the one described"
     );
     assert!(
         users.asked().is_empty(),
-        "the certificate's subject is never looked up on a SASL listener"
+        "nothing is looked up by certificate on a SASL listener"
+    );
+
+    let Ok(mut refused) = connect_tls(ssl, pki.authority.client_config(None)).await else {
+        return;
+    };
+    let frame = build_request_frame(API_KEY_API_VERSIONS, 1, 1, Some("anonymous"), &[]);
+    let _ = refused.write_all(&frame).await;
+    assert_eq!(
+        read_byte_with_timeout(&mut refused, Duration::from_secs(5)).await,
+        ByteRead::Closed,
+        "the SSL listener beside it still requires a certificate"
+    );
+}
+
+#[tokio::test]
+async fn given_a_large_response_when_the_tls_client_reads_slowly_should_deliver_all_of_it() {
+    let pki = Pki::new();
+    // Small fixed buffers on both ends turn off autotuning, so the gateway's socket is full
+    // whenever rustls hands it the end of the response.
+    let socket = bind_listener("127.0.0.1:0").expect("bind");
+    socket2::SockRef::from(&socket)
+        .set_send_buffer_size(16 * 1024)
+        .expect("send buffer");
+    let addr = socket.local_addr().expect("local addr");
+    let (_shutdown, rx) = tokio::sync::broadcast::channel(1);
+    let config = GatewayConfig {
+        write_timeout: Duration::from_secs(30),
+        ..quick_config(vec![SecurityProtocol::Ssl], Some(pki.tls()))
+    };
+    tokio::spawn(KafkaGateway::new(config).run(
+        vec![BoundListener::new(listener(SecurityProtocol::Ssl), socket)],
+        rx,
+    ));
+    let client = TcpSocket::new_v4().expect("socket");
+    client
+        .set_recv_buffer_size(16 * 1024)
+        .expect("receive buffer");
+    let tcp = client.connect(addr).await.expect("connect");
+    let mut stream = connect_tls_over(tcp, pki.authority.client_config(None))
+        .await
+        .expect("TLS handshake");
+
+    // The stub echoes every requested topic name back, so the answer is about as large as the
+    // request.
+    let name = "t".repeat(16 * 1024);
+    let names: Vec<&str> = std::iter::repeat_n(name.as_str(), 128).collect();
+    let request = build_metadata_legacy_request(&names);
+    let frame = build_request_frame(API_KEY_METADATA, 0, 7, Some("tls-test"), &request);
+    stream.write_all(&frame).await.expect("write request");
+
+    let read = tokio::time::timeout(Duration::from_secs(20), async {
+        let mut prefix = [0u8; 4];
+        stream.read_exact(&mut prefix).await.expect("length prefix");
+        let frame_len = usize::try_from(i32::from_be_bytes(prefix)).expect("positive length");
+        let mut chunk = vec![0u8; 16 * 1024];
+        let mut received = 0;
+        while received < frame_len {
+            let read = stream.read(&mut chunk).await.expect("read");
+            assert_ne!(read, 0, "closed after {received} of {frame_len} bytes");
+            received += read;
+            tokio::time::sleep(Duration::from_millis(1)).await;
+        }
+        frame_len
+    })
+    .await;
+    let frame_len = read.expect("the whole response arrives; its tail must not wait for a flush");
+    assert!(frame_len > 2 * 1024 * 1024, "got only {frame_len} bytes");
+}
+
+#[tokio::test]
+async fn given_required_client_auth_when_no_rule_maps_the_subject_should_close() {
+    let pki = Pki::new();
+    let users = KnownUsers::with(USERNAME, topic_reader());
+    let resolver = Arc::clone(&users);
+    let (addrs, _shutdown) = spawn_gateway(
+        move |config| KafkaGateway::new(config).with_principal_resolver(resolver),
+        quick_config(
+            vec![SecurityProtocol::Ssl],
+            Some(
+                pki.tls_with_client_auth(ClientAuth::Required)
+                    .with_principal_mapping(
+                        "RULE:^CN=([^,]+),O=Allowed$/$1/".parse().expect("valid"),
+                    ),
+            ),
+        ),
+    );
+
+    let unmapped = pki.authority.client_cert(USERNAME, "Example");
+    let mut stream = connect_tls(addrs[0], pki.authority.client_config(Some(&unmapped)))
+        .await
+        .expect("the CA signed the certificate, so the handshake succeeds");
+    let frame = build_request_frame(API_KEY_API_VERSIONS, 1, 1, Some("unmapped"), &[]);
+    let _ = stream.write_all(&frame).await;
+    assert_eq!(
+        read_byte_with_timeout(&mut stream, Duration::from_secs(5)).await,
+        ByteRead::Closed,
+        "a subject no rule maps names nobody, and is not served as anonymous"
     );
+    assert!(users.asked().is_empty(), "nothing was looked up");
+}
+
+#[tokio::test]
+async fn given_a_client_that_never_starts_the_handshake_should_close_it_within_the_budget() {
+    let pki = Pki::new();
+    let (addrs, _shutdown) = spawn_gateway(
+        KafkaGateway::new,
+        GatewayConfig {
+            pre_auth_timeout: Duration::from_millis(300),
+            ..quick_config(vec![SecurityProtocol::Ssl], Some(pki.tls()))
+        },
+    );
+
+    let mut stream = TcpStream::connect(addrs[0]).await.expect("connect");
+    assert_eq!(
+        read_byte_with_timeout(&mut stream, Duration::from_secs(3)).await,
+        ByteRead::Closed,
+        "a silent client must not hold a connection slot past the pre-authentication budget"
+    );
+}
+
+#[tokio::test]
+async fn given_a_lookup_that_fails_or_hangs_should_close_the_certificate_connection() {
+    for resolver in [BrokenResolver::Unavailable, BrokenResolver::Hangs] {
+        let pki = Pki::new();
+        let label = format!("{resolver:?}");
+        let resolver = Arc::new(resolver);
+        let (addrs, _shutdown) = spawn_gateway(
+            move |config| KafkaGateway::new(config).with_principal_resolver(resolver),
+            GatewayConfig {
+                pre_auth_timeout: Duration::from_millis(300),
+                ..quick_config(
+                    vec![SecurityProtocol::Ssl],
+                    Some(
+                        pki.tls_with_client_auth(ClientAuth::Required)
+                            .with_principal_mapping(
+                                "RULE:^CN=([^,]+).*$/$1/".parse().expect("valid"),
+                            ),
+                    ),
+                )
+            },
+        );
+
+        let certificate = pki.authority.client_cert(USERNAME, "Example");
+        let mut stream = connect_tls(addrs[0], pki.authority.client_config(Some(&certificate)))
+            .await
+            .expect("mTLS handshake");
+        let frame = build_request_frame(API_KEY_API_VERSIONS, 1, 1, Some("lookup"), &[]);
+        let _ = stream.write_all(&frame).await;
+        assert_eq!(
+            read_byte_with_timeout(&mut stream, Duration::from_secs(3)).await,
+            ByteRead::Closed,
+            "{label}: an identity that cannot be confirmed admits nothing"
+        );
+    }
 }
 
 #[tokio::test]
@@ -661,6 +855,106 @@ async fn given_certificate_identities_without_a_lookup_should_refuse_to_start()
     );
 }
 
+#[tokio::test]
+async fn given_a_lookup_queued_behind_another_should_get_its_own_budget_once_it_holds_the_slot() {
+    // Each lookup fits the budget alone, but the queued one's wait plus its own lookup does not:
+    // it is served only if the budget restarts when the slot is acquired.
+    let budget = Duration::from_millis(1000);
+    let pki = Pki::new();
+    let users = Arc::new(SlowUsers {
+        delay: Duration::from_millis(800),
+        started: AtomicUsize::new(0),
+    });
+    let resolver = Arc::clone(&users);
+    let (addrs, _shutdown) = spawn_gateway(
+        move |config| KafkaGateway::new(config).with_principal_resolver(resolver),
+        GatewayConfig {
+            pre_auth_timeout: budget,
+            max_concurrent_authentications: 1,
+            ..quick_config(
+                vec![SecurityProtocol::Ssl],
+                Some(
+                    pki.tls_with_client_auth(ClientAuth::Required)
+                        .with_principal_mapping("RULE:^CN=([^,]+).*$/$1/".parse().expect("valid")),
+                ),
+            )
+        },
+    );
+    let certificate = pki.authority.client_cert(USERNAME, "Example");
+    let client_config = pki.authority.client_config(Some(&certificate));
+
+    let mut first = connect_tls(addrs[0], Arc::clone(&client_config))
+        .await
+        .expect("first mTLS handshake");
+    while users.started.load(Ordering::SeqCst) == 0 {
+        tokio::time::sleep(Duration::from_millis(5)).await;
+    }
+    let mut queued = connect_tls(addrs[0], client_config)
+        .await
+        .expect("queued mTLS handshake");
+
+    let (first_rows, queued_rows) =
+        tokio::join!(api_versions(&mut first), api_versions(&mut queued));
+    assert!(advertises(&first_rows, API_KEY_DESCRIBE_ACLS));
+    assert!(
+        advertises(&queued_rows, API_KEY_DESCRIBE_ACLS),
+        "the queued lookup must not inherit what the wait left of a shared deadline"
+    );
+}
+
+#[tokio::test]
+async fn given_one_listener_at_its_connection_limit_should_still_serve_another_listener() {
+    let (addrs, _shutdown) = spawn_gateway(
+        KafkaGateway::new,
+        GatewayConfig {
+            max_connections: 1,
+            ..quick_config(
+                vec![SecurityProtocol::Plaintext, SecurityProtocol::Plaintext],
+                None,
+            )
+        },
+    );
+
+    let mut held = TcpStream::connect(addrs[0]).await.expect("connect");
+    assert!(advertises(&api_versions(&mut held).await, API_KEY_METADATA));
+    let mut refused = TcpStream::connect(addrs[0]).await.expect("connect");
+    assert_eq!(
+        read_byte_with_timeout(&mut refused, Duration::from_secs(3)).await,
+        ByteRead::Closed,
+        "the first listener is full"
+    );
+
+    let mut other = TcpStream::connect(addrs[1]).await.expect("connect");
+    assert!(
+        advertises(&api_versions(&mut other).await, API_KEY_METADATA),
+        "each listener has its own connection pool"
+    );
+}
+
+#[tokio::test]
+async fn given_client_auth_without_an_ssl_listener_should_refuse_to_start() {
+    let pki = Pki::new();
+    let socket = bind_listener("127.0.0.1:0").expect("bind");
+    let (_tx, rx) = tokio::sync::broadcast::channel(1);
+    let config = quick_config(
+        vec![SecurityProtocol::SaslSsl],
+        Some(pki.tls_with_client_auth(ClientAuth::Required)),
+    );
+    let error = KafkaGateway::new(config)
+        .with_authenticator(Arc::new(FixedCredentials))
+        .run(
+            vec![BoundListener::new(
+                listener(SecurityProtocol::SaslSsl),
+                socket,
+            )],
+            rx,
+        )
+        .await
+        .unwrap_err()
+        .to_string();
+    assert!(error.contains("no SSL listener"), "got: {error}");
+}
+
 /// Kept for the suites that pin the single-listener shape: a `SASL_PLAINTEXT` listener on an
 /// ephemeral port is what `IGGY_KAFKA_SASL_ENABLED=true` used to mean.
 #[tokio::test]