Skip to content

Messaging Security ​

“Redis is designed to be accessed by trusted clients inside trusted environments.” — Redis documentation, Redis security

Summary: A broker concentrates every important business event in one place; securing it means deciding who may connect, publish, consume and administer, and what an attacker learns from bytes on the wire, on disk and in copies. Focus: Threat model, TLS and mTLS, SASL/SCRAM/OAuth authentication, RabbitMQ/Kafka/Redis authorization, secrets, payload encryption and signing, PII retention and erasure, multi-tenancy and audit. Learning goal: Configure a least-privilege, verified, encrypted connection for each broker in Go and Laravel, and design payloads so that a broker, a backup or a log leak does not expose personal data.

This chapter owns messaging-specific security: transport, identity, permissions, payload protection and retention of personal data in queues and logs. The wire-level TLS handshake, certificate chains and openssl s_client live in TLS in practice; service-to-service mTLS design lives in mTLS service security; database roles and column encryption live in database security and encryption in use. Envelope fields and schema rules are in message design; immutable event stores are in event sourcing.

Page map ​

Looking forGo to
What can go wrong around a brokerThreat model
TLS ports, security.protocol, rediss://, hostname checksTransport security
Client certificates as identityMutual TLS
PLAIN, SCRAM, GSSAPI, OAUTHBEARER, delegation tokens, Redis AUTHAuthentication
vhosts and regex permissions, kafka-acls, Redis ACL rulesAuthorization
Passwords in URLs, logs, .env and vaultsSecrets management
KMS, data keys, AES-GCM, ShouldBeEncryptedPayload encryption
HMAC, JWS, replay windowsIntegrity and replay
GDPR erasure in a Kafka logPII, retention and erasure
Tenants sharing one clusterMulti-tenant isolation
Management UI exposure, audit trailsAudit and management plane
A hardening checklist per brokerSolutions
Go and Laravel codeGo, Laravel, Broker differences

Everything in one minute ​

ThreatPlain wordsControlRabbitMQKafkaRedis Streams
EavesdroppingSomeone on the network reads messagesTLS with chain and hostname verificationAMQPS on 5671security.protocol=SSL or SASL_SSLtls-port, rediss://
ImpersonationA client pretends to be a serviceAuthenticationPLAIN over TLS, EXTERNAL (x509), OAuth 2.0 pluginSCRAM-SHA-512, mTLS, OAUTHBEARER, GSSAPIACL users with AUTH username password, client certificates
Over-privilegeA valid identity does too muchLeast-privilege authorizationvhost + configure/write/read regex, topic permissionsACLs on Topic/Group/Cluster/TransactionalIdACL rules on commands, keys, channels
Payload leakageBroker disk, backup, DLQ or log reveals dataData minimisation, envelope encryptionNot encrypted at rest by the broker“does not encrypt data at rest”No per-entry encryption
Tampering and replayA message is altered or sent twice on purposeHMAC/JWS signature, message id, freshness windowApplication headersRecord headersStream fields
Erasure obligationPersonal data must be deletableRetention limits, tombstones, crypto-shreddingTTL, queue deletionretention.ms, compaction tombstonesXTRIM, XDEL, key deletion
Exposed admin planeAnyone can reach the UI or Admin APIPrivate network, TLS, admin identities, auditManagement on 15672/15671, user tagsAdmin API ACLs on Cluster, JMX locked down-@admin -@dangerous for apps
Default out of the boxRabbitMQKafkaRedis
TransportPlain AMQP on 5672; TLS listener only when configuredPLAINTEXT on every listenerPlain TCP on 6379; TLS only if built with BUILD_TLS=yes and configured
Identityguest/guest, limited to loopback by loopback_users; ANONYMOUS mechanism enabledNonedefault user with nopass
AuthorizationPer-vhost permissions; new users have noneNo authorizer: every principal may do everythingdefault user has ~* &* +@all
Safety netRemote guest login refusedNoneProtected mode answers only loopback when no password is set

Where it comes from ​

Early message-oriented middleware ran inside one data centre and trusted the network. AMQP 0-9-1 adopted SASL, the IETF authentication framework (today RFC 4422), which is why RabbitMQ speaks of “mechanisms” such as PLAIN and EXTERNAL. Kafka started without security; SSL and Kerberos (SASL/GSSAPI) arrived in 0.9.0.0, SASL/PLAIN in 0.10.0.0, SCRAM in 0.10.2.0 and OAUTHBEARER in 2.0, according to the Kafka security overview. SCRAM itself is RFC 5802 (2010), with SHA-256 added by RFC 7677. Redis added TLS and ACLs in version 6; before that the only control was the shared requirepass password.

The privacy side came from regulation rather than protocol design. Event logs are designed to be immutable and replayable, while data-protection law expects personal data to be minimised and deletable. Crypto-shredding, the practice of deleting the key instead of the data, is an industry technique rather than a standard; this page describes it as a design option, not as a compliance certificate.

Why it exists ​

A broker is a shared, durable copy of business facts. One stolen credential with wildcard read permission can drain every topic; one unauthenticated port can let anyone publish a fake PaymentApproved; one verbose log line can copy an IBAN into a system with no retention policy.

Weaker postureStronger posture
Plain TCP inside “trusted” networksTLS everywhere, including inter-broker and replication links
One shared admin accountOne identity per service and per human, least privilege
Credentials in URLs, YAML and logsSecrets mounted at runtime, redacted logs, rotation
Payload in clear text, protected only by the brokerMinimised payload, envelope encryption for sensitive fields
“Kafka keeps everything forever”Retention per topic, tombstones, crypto-shredding plan
Faster to set up, fewer moving partsMore certificates, keys and policies to operate

The everyday picture used through this page is a post office sorting hall: who may enter the building (network), how the van is sealed (TLS), the badge at the door (authentication), which sorting rooms the badge opens (authorization), whether the letters are sealed envelopes or postcards (payload encryption), and how long the hall keeps copies (retention).

Three misunderstandings to remove first: TLS does not hide messages from the broker or its operators; authentication without an authorizer gives every authenticated client full access on Kafka; encrypting a field does not make it deletable unless the key can be destroyed independently.

What it is really about ​

Security for messaging is a chain of independent questions. Each control answers one; none answers the others.

Application networkBroker trust boundaryConsumers and operatorsProducer serviceidentity: orders-producerLaravel web appdispatches jobsAttacker on networksniffs, spoofs, replaysBroker clusterRabbitMQ / Kafka / Redislisteners, vhosts, topicsDisk, snapshots, backupsplain bytes at restManagement planeUI 15672, Admin API, JMXConsumer serviceidentity: billingDLQ, logs, failed_jobscopies of payloadsOperators and CIadmin credentials1234561 eavesdrop or impersonate 2 over-privileged consumer 3 replay or poison 4 payload leakage at rest 5 PII copied downstream 6 exposed admin plane
STRIDE categoryMessaging examplePrimary control
SpoofingFake producer publishes RefundIssuedAuthentication, mTLS
TamperingProxy changes amount in flight or a DLQ operator edits a bodyTLS in transit, HMAC/JWS end to end
RepudiationNobody can tell who published a destructive commandPer-service identities, audit log
Information disclosureBackup of Kafka log segments sold onlineEncryption at rest, payload encryption, minimisation
Denial of serviceTenant floods the cluster or creates 10,000 queuesQuotas, vhost limits, connection limits
Elevation of privilegeConsumer credential can also delete topicsLeast-privilege ACLs, separate admin identity
LayerMechanismsStopsNetwork exposureprivate listeners, firewall, no public 5672 / 9092 / 6379 / 15672random internet scansTransport: TLS / mTLSAMQPS 5671, SASL_SSL, rediss, verify chain + hostnameeavesdrop, MITMAuthenticationEXTERNAL x509, SCRAM-SHA-512, OAUTHBEARER, ACL usersspoofed clientAuthorizationvhost regex, Kafka ACLs, Redis ACL rules, least privilegeover-privileged identityPayload: encrypt + signenvelope encryption (KMS), HMAC / JWS, replay windowbroker/backup reader, tamperingRetention and erasureTTL, retention.ms, tombstones, crypto-shreddingPII kept foreverEach layer assumes the one above can fail; TLS alone leaves data readable inside the broker.

An everyday picture ​

A post office sorting hall has a fence, a guarded door, badges, rooms, sealed envelopes and an archive. A sealed van (TLS) protects letters on the road but the sorters inside can read every postcard. A badge (authentication) tells the guard who you are; the list of rooms your badge opens (authorization) is a separate decision. A letter in a sealed envelope with a wax stamp (encryption and signature) stays private and tamper-evident even inside the hall. The archive (retention) must have shredding rules, and shredding the only key to a locked box is as good as shredding the box.

Concept catalogue ​

Threat model and trust boundaries Must-know ​

In plain words: List who touches the broker, what each may do, and what happens if one of them is hostile or compromised.

Common misunderstanding: “The broker is on a private network, so it is safe.” Lateral movement after one compromised pod, a misrouted security group, or a curious operator all start inside the private network.

Definition: A threat model for messaging enumerates actors (producers, consumers, operators, CI, brokers, attackers), assets (messages, credentials, offsets, topology, metadata), trust boundaries (network, broker process, disk, management plane, downstream copies) and threats: eavesdropping, impersonation, over-privilege, replay, poisoning, payload leakage and administrative takeover.

text
1 Attacker -> compromised analytics pod: steals mounted Kafka credential
2 Attacker -> broker: credential has READ on Topic '*' (wildcard grant)
3 Attacker -> payments.events: consumes card-holder names for 30 days of retention
4 Attacker -> orders.commands: credential also has WRITE; publishes forged CancelOrder
5 Defender -> audit: no per-service identity, cannot tell which service did it

Real scenarios: an internet-facing Redis without a password whose data is wiped with FLUSHALL (the Redis docs name this exact risk); a RabbitMQ management UI reachable from the office Wi-Fi with an administrator account; a Kafka Connect worker whose sink credential can also alter ACLs; a poison message crafted to crash every consumer (see dead-letter queue).

AssetWho legitimately needs itTypical leak path
Message bodiesProducer, owning consumersWildcard read ACL, DLQ copies, logs, backups
CredentialsOne service eachURL in logs, Git, CI variables printed in jobs
Topology (queues, topics, ACLs)Platform teamManagement UI, Admin API, Terraform state
Offsets / consumer groupsConsumerA foreign group id resets or steals offsets
Metrics and tracesOperatorsPayload attributes in spans

How to use it: write the table above for each cluster before the first producer goes live, and revisit it when a new consumer or tenant joins. Every row becomes a control on this page.

Transport security: TLS, certificate verification and SNI Must-know ​

In plain words: Encrypt the connection and check that the server is really the broker you meant.

Common misunderstanding: “TLS is on, so we are safe.” InsecureSkipVerify: true, verify_peer off, or ssl.endpoint.identification.algorithm= (empty) encrypt the bytes to whoever answers, including an attacker in the middle.

Definition: TLS (RFC 8446 for 1.3) provides confidentiality and integrity in transit and authenticates the server certificate. Certificate verification has two halves: the chain must lead to a trusted CA, and the certificate's subject alternative name must match the host the client dialled. SNI (Server Name Indication) sends that host name in the handshake so a proxy or broker with several certificates can present the right one.

text
1 Client -> DNS: broker-1.internal
2 Client -> broker-1.internal:9093: ClientHello, SNI=broker-1.internal, TLS 1.3
3 Broker -> client: certificate chain (leaf SAN broker-1.internal, intermediate)
4 Client: verify chain to private CA, verify SAN == broker-1.internal
5 Client -> broker: SASL handshake inside the encrypted channel

Real scenarios: a Kafka client bootstraps through a load balancer name but then connects to each broker's advertised listener, so every broker certificate needs its own SAN; a RabbitMQ cluster behind HAProxy with TLS termination on the proxy leaves the proxy-to-node hop unencrypted unless re-encrypted; Redis replicas need tls-replication yes or the replication link stays clear text.

ItemRabbitMQKafkaRedis
TLS client port5671 (AMQP), 5551 (streams), 15671 (HTTPS management)Listener named SSL:// or SASL_SSL://, often 9093tls-port 6379 with port 0
Client switchamqps:// URLsecurity.protocol=SSL or SASL_SSLrediss:// URL or TLSConfig
Hostname verificationClient side; Go amqp091 verifies by default with amqps://ssl.endpoint.identification.algorithm=https (default since 2.0)Client side (go-redis uses Go crypto/tls)
Version floorssl_options.versions.1 = tlsv1.3 (and .2 = tlsv1.2 if needed)ssl.enabled.protocols default TLSv1.2,TLSv1.3tls-protocols in redis.conf
Internal linksInter-node Erlang distribution on 25672 needs separate TLS setupsecurity.inter.broker.protocol, controller listenertls-replication yes, tls-cluster yes

How to use it: set a minimum of TLS 1.2, prefer 1.3, keep cipher suites at library defaults unless a policy demands a list, and treat any flag that disables verification as a production incident. The Go helper in this chapter refuses to build a configuration without a CA bundle and has a test that a certificate for broker.internal is rejected when the client expects attacker.example. Wire-level debugging with openssl s_client -servername is covered in TLS in practice.

Mutual TLS and certificate identity Important ​

In plain words: The client also shows a certificate, and the broker turns that certificate into a user name.

Common misunderstanding: “Requesting a client certificate is the same as requiring one.” Kafka's ssl.client.auth=requested lets clients without a certificate connect; the Kafka docs call it “a false sense of security”. RabbitMQ's fail_if_no_peer_cert=false behaves the same way.

Definition: mTLS adds client authentication to TLS. RabbitMQ needs ssl_options.verify = verify_peer, ssl_options.fail_if_no_peer_cert = true, the rabbitmq_auth_mechanism_ssl plugin and the EXTERNAL mechanism; ssl_cert_login_from chooses the distinguished name (default), common_name or a subject alternative name as the user name. Kafka uses ssl.client.auth=required and maps the distinguished name through ssl.principal.mapping.rules. Redis uses mutual TLS by default when TLS is enabled; tls-auth-clients no turns client certificates off.

text
1 Client -> broker: ClientHello
2 Broker -> client: CertificateRequest (CA list)
3 Client -> broker: certificate CN=billing-consumer,OU=svc + proof of key
4 Broker: verify chain; map DN -> user "billing-consumer"
5 Broker: apply that user's permissions; no password exchanged

Real scenarios: service meshes that issue short-lived workload certificates; broker-to-broker links where Kafka recommends mTLS because no shared password exists; IoT devices with per-device certificates that can be revoked one by one.

ConcernRabbitMQKafkaRedis
Require certificatefail_if_no_peer_cert = truessl.client.auth=requiredDefault when TLS on; tls-auth-clients yes
Certificate becomes userssl_cert_login_from (DN, CN, SAN) + EXTERNALssl.principal.mapping.rules or custom KafkaPrincipalBuilderCertificate proves possession; the connection still uses an ACL user (default unless AUTH)
Chain depthssl_options.depth (default 1)JVM truststoreOpenSSL defaults

How to use it: automate issuance and rotation (short lifetimes make revocation lists less important), give every workload its own subject, and map subjects to broker users explicitly. In Go, pass the client key pair through tls.Config.Certificates and select amqp.ExternalAuth for RabbitMQ.

Authentication mechanisms Must-know ​

In plain words: Proving which service is connecting: a password, a challenge-response, a ticket, a token or a certificate.

Common misunderstanding: “SASL means encrypted.” SASL is an authentication framework. Kafka SASL_PLAINTEXT authenticates over a clear-text connection, and SASL/PLAIN sends the password itself; Kafka's docs say PLAIN “should be used only with SSL as transport layer”.

Definition: The mechanisms you meet are: SASL/PLAIN (user and password in clear inside the channel); SCRAM-SHA-256 / SCRAM-SHA-512 (RFC 5802/7677 salted challenge-response: the server stores salted, iterated keys and the password never crosses the wire); GSSAPI (Kerberos tickets from a KDC); OAUTHBEARER (an OAuth 2.0 JWT validated against the identity provider's JWKS); delegation tokens (Kafka-issued shared secrets, used through SCRAM, for frameworks fanning out to many tasks); RabbitMQ EXTERNAL (identity from the TLS certificate); Redis AUTH (AUTH password for the legacy requirepass default user, AUTH username password for ACL users).

text
SCRAM-SHA-512 (client first)            Server stores salt, iterations, StoredKey, ServerKey
1 C -> S: n,,n=billing,r=<client nonce>
2 S -> C: r=<client+server nonce>,s=<salt>,i=4096
3 C -> S: c=biws,r=...,p=<ClientProof from salted password>
4 S -> C: v=<ServerSignature>   client verifies the server knew the key too

Real scenarios: Kafka on Kubernetes using SCRAM users managed by an operator; Kafka in an enterprise with an existing KDC using GSSAPI; RabbitMQ behind Keycloak or Entra ID with the OAuth 2.0 plugin and scopes such as rabbitmq.read:orders/*; Spark or Flink jobs requesting a Kafka delegation token so 200 executors do not each carry the Kerberos keytab.

MechanismWhereSecret on the wireGood forWatch out
SASL/PLAINRabbitMQ default, KafkaPassword (inside TLS)Simple setups, external password backendsNever over SASL_PLAINTEXT or AMQP 5672
SCRAM-SHA-256/512Kafka (credentials in KRaft metadata)Proof onlyMost self-managed KafkaDefault 4096 iterations; still use TLS
GSSAPIKafkaKerberos ticketExisting Kerberos estatesKDC availability, clock skew
OAUTHBEARERKafka; RabbitMQ OAuth 2.0 pluginShort-lived JWTCentral identity provider, scopesKafka's default unsecured JWT is for testing only
Delegation tokenKafkaToken HMAC via SCRAMDistributed frameworksDefault renew every 24 h, max 7 days
EXTERNALRabbitMQ with rabbitmq_auth_mechanism_sslNone (certificate)Per-workload PKIMap subjects carefully
ANONYMOUSRabbitMQ (enabled by default)NoneDevelopment onlyActs as anonymous_login_user (guest); remove in production
AUTH / ACL usersRedis 6+Password (needs TLS)Named users per rolerequirepass only sets the default user's password

How to use it: pick SCRAM-SHA-512 or mTLS for Kafka services, mTLS or PLAIN-over-TLS per service for RabbitMQ (OAuth 2.0 where an identity provider exists), and one ACL user per role for Redis. RabbitMQ OAuth tokens expire; on AMQP 0-9-1 the client refreshes with the update-secret method (Connection.UpdateSecret in amqp091-go), otherwise it must reconnect.

Authorization and least privilege Must-know ​

In plain words: After the broker knows who you are, it decides exactly which queues, topics, keys and commands you may touch.

Common misunderstanding: “Our Kafka has SASL, so only authorised clients can read.” The Kafka security model states: “If no authorizer is configured, all authenticated principals have full access.”

Definition: Least privilege gives each identity the minimum operations on the minimum resources. RabbitMQ scopes permissions per virtual host as three regular expressions: configure (declare/delete), write (publish, bind as destination) and read (consume, bind as source); topic permissions add a routing-key regex for topic exchanges. Kafka ACLs are tuples of the form: principal P is allowed or denied operation O from host H on resources matching resource pattern RP, with LITERAL or PREFIXED patterns, enforced by StandardAuthorizer in KRaft clusters; super.users bypass checks. Redis ACL rules list allowed commands (+xadd, -@all, +@stream), key patterns (~stream:orders:*, %R~, %W~) and Pub/Sub channels (&).

text
1 billing -> RabbitMQ vhost orders: basic.consume queue "orders.billing"
2 RabbitMQ: read regex ^orders\.billing$ matches -> allowed
3 billing -> queue.declare "billing.tmp"
4 RabbitMQ: configure regex ^$ matches nothing -> 403 ACCESS_REFUSED
5 billing -> Kafka: JoinGroup "billing" -> needs READ on Group:billing
6 billing -> Kafka: Fetch "orders.events" -> needs READ on Topic; else TOPIC_AUTHORIZATION_FAILED (29)

Real scenarios: a producer that can also declare queues re-declares one with different arguments and breaks consumers; a consumer that can write to its input topic can inject events that look authentic; a Redis worker with +@all ~tenant1:* can still run FLUSHALL because whole-keyspace commands ignore key patterns (the Redis ACL docs call this out).

RabbitMQvhost: ordersuser: billingconfigure: ^$write: ^billing\..*read: ^orders\.billing$topic: write ^order\..*Kafkaprincipal: User:billingoperation: Readresource: Topic orders.pattern: PREFIXEDhost: *permission: ALLOWRedisuser: orders-consumeron #sha256resetkeys ~stream:orders:*resetchannels-@all+xreadgroup +xackdefault: no permissions for new usersdefault with authorizer: deny unless ACLdefault user: nopass ~* &* +@all
RoleRabbitMQ (configure / write / read)Kafka ACLsRedis ACL
Producer^$ / ^orders\.events$ / ^$WRITE + DESCRIBE on Topic orders.events; IDEMPOTENT_WRITE on Cluster or WRITE on TransactionalId-@all +xadd ~stream:orders:*
Consumer^$ / ^$ / ^orders\.billing$READ + DESCRIBE on Topic, READ on Group billing-@all +xreadgroup +xack +xautoclaim ~stream:orders:*
Topology deployer^orders\..* / ^orders\..* / ^orders\..*CREATE/ALTER on Topic prefix orders.+@stream plus XGROUP on its keys
Monitoring^$ / ^$ / ^$ + tag monitoringDESCRIBE, DESCRIBE_CONFIGS+info +ping without key access
Admin (human, break-glass)administrator tag on a separate usersuper.users entry or ALTER on Cluster+@admin on a separate user

How to use it: generate permissions from code (Terraform, rabbitmqctl, kafka-acls, ACL files) and review them like code. Prefer prefixed ACLs and naming conventions over wildcards. Remember RabbitMQ caches permission checks per connection or channel, so revocation can need a reconnect; deleting the user closes its connections.

Secrets management Must-know ​

In plain words: Credentials are delivered to the process at runtime, rotated, and never printed.

Common misunderstanding: “The password is in an environment variable, so it is secure.” Environment variables leak through crash dumps, /proc, debug pages and CI logs; a connection URL such as amqps://user:pass@host is the most frequently logged secret of all.

Definition: Secrets management covers storage (a vault or cloud secret manager), delivery (mounted file, sidecar, short-lived token), rotation (two valid credentials during overlap), revocation and audit. Kafka supports ConfigProvider indirection (FileConfigProvider, DirectoryConfigProvider) instead of clear-text secrets in properties files. Laravel reads config/queue.php from env(), can encrypt .env into .env.encrypted with php artisan env:encrypt, and supports graceful APP_KEY rotation through APP_PREVIOUS_KEYS.

text
1 Vault agent -> /run/secrets/kafka-password (mode 0600), lease 24h
2 Consumer -> SCRAM callback: read file on every new connection
3 Platform -> Kafka: add new SCRAM credential, keep old one
4 Vault agent: rewrites file; next reconnect uses new password
5 Platform -> Kafka: delete old SCRAM credential after all clients rotated

Real scenarios: a Laravel error page in debug mode showing RABBITMQ_PASSWORD; a Go program logging amqp.Dial(url) failures with the URL; Terraform state files containing Kafka SCRAM passwords; Docker images built with ENV secrets (OWASP warns against hardcoding secrets with ENV or ARG).

PracticeDoAvoid
StorageVault, AWS Secrets Manager, GCP Secret Manager, Kubernetes secrets with encryptionGit, images, wiki pages
DeliveryFile mounted per pod, read at connect timeURL with userinfo, command-line flags (ps shows them)
LoggingRedacted values, connection names, user namesFull URLs, configuration dumps
RotationOverlap two credentials; per-connection credential callbacksRestart-the-world rotations
Laravelenv() only in config files, config:cache, env:encrypt for checked-in filesenv() in application code, APP_DEBUG=true in production

How to use it: the Go secret.File helper refuses files readable by group or other users and is called inside the franz-go SCRAM callback and the go-redis CredentialsProviderContext, so rotation works without restarts. amqp091-go's PlainAuth.String() returns a redacted value, but nothing protects a URL you format yourself.

Payload encryption: envelope and field-level Important ​

In plain words: Lock the sensitive part of the message so that the broker, its disks and its backups only ever see ciphertext.

Common misunderstanding: “Disk encryption solves it.” Filesystem encryption protects against a stolen disk, not against anyone who can log in to the broker, read a DLQ, or run a console consumer. Kafka's docs say message-level encryption “is the only option that protects records from broker operators”.

Definition: Envelope encryption encrypts the payload with a random data key (DEK) and encrypts that data key with a key-encryption key (KEK) held in a KMS. The message carries the key id, the wrapped DEK, the nonce and the ciphertext. AES-GCM (NIST SP 800-38D) is authenticated encryption: it detects tampering and can bind additional authenticated data (AAD) such as topic and message id. The GCM rule that matters in practice: a nonce must never repeat under the same key. Field-level encryption applies this to selected fields so routing keys and headers stay usable.

Producerfresh DEK per messageKMSKEK per tenant/subjectnever leaves KMSConsumerKMS decrypt permissionwrap(DEK)unwrap(wrapped DEK)Broker message (stored as-is)header enc-kid: customer-42header enc-dek: wrapped DEKheader enc-nonce: 96-bit randombody: AES-256-GCM ciphertext + tagpublishconsumeAAD = version + key id + topic + msg idmoved or relabelled message failsDestroy KEK customer-42every copy in logs, DLQ, backups unreadablecrypto-shredding
text
1 Producer -> crypto/rand: 32-byte DEK, 12-byte nonce
2 Producer: ct = AES-256-GCM(DEK, nonce, body, AAD=v1|kid|topic|msg-id)
3 Producer -> KMS: Wrap(kid=customer-42, DEK) -> wrapped DEK
4 Producer -> broker: headers enc-kid, enc-dek, enc-nonce; body = ct
5 Consumer -> KMS: Unwrap(customer-42, wrapped DEK)   (IAM + audit per call)
6 Consumer: GCM Open with the same AAD; a moved or altered message fails

Real scenarios: card-holder names in payment events that only the payment service may read; health data on a shared analytics cluster; tenant data where each tenant has its own KEK; Laravel jobs carrying a customer's address through Redis.

OptionProtects againstDoes not protect againstExample
TLS onlyNetwork eavesdroppingBroker operators, disk theft, backups, DLQ readersAMQPS, SASL_SSL
Disk/volume encryptionStolen disks, misdirected snapshotsAnyone with broker loginLUKS, EBS encryption
Whole-payload envelope encryptionBroker operators, backups, wrong consumersMetadata in headers, traffic analysisGo envelope package
Field-level encryptionSame, for chosen fields; routing still worksFields left in clearLaravel EnvelopeCipher on address
Laravel ShouldBeEncryptedReaders of the queue storeAnyone holding APP_KEY; envelope fieldsEncrypted job command

How to use it: generate a fresh DEK per message (or per small batch) so the random 96-bit nonce never meets the same key twice; never reuse a nonce with a long-lived key; cache unwrapped DEKs briefly if KMS latency matters; put the key id in a header so consumers can rotate. Laravel's ShouldBeEncrypted encrypts the serialized job command with APP_KEY (Crypt uses AES-256-CBC with a MAC by default); its uuid, displayName and timing fields stay readable, so class names must not carry personal data.

Message integrity, signing and replay Important ​

In plain words: Prove that a message came from the expected producer, was not changed, and is not an old message sent again.

Common misunderstanding: “TLS already guarantees integrity.” TLS protects one hop. A message that passes through a bridge, a DLQ repair tool, a Kafka MirrorMaker or a human replay is outside any single TLS session. TLS 1.3 itself states: “There are no guarantees of non-replay between connections” for 0-RTT data.

Definition: An HMAC (RFC 2104) is a keyed hash shared by producer and consumer; anyone with the key can create valid tags. A JWS (RFC 7515) wraps a payload with a MAC or a digital signature; with asymmetric keys (ES256, EdDSA) consumers can verify without being able to sign. A replay attack resubmits a valid, signed message; defence needs a unique message id, a timestamp inside a freshness window, and a replay cache that lasts at least as long as the window.

text
1 Producer: sig = HMAC-SHA256(k-2026-11, v1|kid|ts|msg-id|body)
2 Broker -> consumer: message + sig-kid, sig-ts, sig-msg-id, sig
3 Consumer: constant-time compare MAC          -> fail: ErrBadSignature
4 Consumer: |now - ts| <= 5 min                -> fail: ErrStale
5 Consumer: msg-id seen in last 5 min?         -> yes: ErrReplay
6 Attacker -> broker: resends step 2 bytes     -> rejected at step 5

Real scenarios: a refund command bus where a captured message replayed later would pay twice; webhooks bridged into a queue; regulated audit events that must be provably unaltered; cross-company integrations through a shared broker.

NeedChooseNote
One producer, few trusted consumersHMAC-SHA256 with key idEvery verifier can forge
Many consumers, non-repudiationJWS with ES256/EdDSAProducer keeps private key
Confidentiality and integrityAES-GCM envelope (AEAD)Integrity for holders of the data key
Replay protectionMessage id + timestamp + replay cacheSame id also feeds the idempotent consumer

How to use it: verify the MAC before recording the message id, otherwise unsigned junk can poison the replay cache (the Go test TestForgedMessageDoesNotPoisonReplayCache covers this). Keep business deduplication in the inbox table; the security replay cache is a short-window guard, not a substitute.

PII, retention and right to erasure Must-know ​

In plain words: Personal data in messages must be minimal, kept only as long as needed, and removable on request, even in logs designed never to change.

Common misunderstanding: “Kafka retention will delete it eventually, so we comply.” Retention may be infinite on compacted topics, copies sit in DLQs, MirrorMaker targets, data lakes, Laravel failed_jobs rows and backups, and deletion is per segment, not per record.

Definition: PII (personally identifiable information) is any data relating to an identifiable person. Retention limits how long records live (retention.ms, queue TTL, XTRIM). The right to erasure (GDPR Article 17) obliges deletion in many cases. In Kafka, log compaction keeps the latest value per key, and a tombstone (a record with that key and a null value) makes compaction remove earlier values for the key, after delete.retention.ms. Crypto-shredding encrypts each subject's data under its own key and deletes the key on request, so every copy becomes unreadable at once.

text
1 t0  user-42 profile v1 -> topic customers (compacted), key=user-42
2 t1  user-42 profile v2 -> same key
3 t2  erasure request    -> produce key=user-42, value=null (tombstone)
4 t3  log cleaner runs   -> v1, v2 removed from the cleaned segment
5 t4  delete.retention.ms passes -> tombstone itself removed
6 BUT orders.events (not compacted) still holds user-42 address in 90 days of history
7 Fix: address was envelope-encrypted under kid=user-42; KMS deletes kid -> unreadable everywhere

Real scenarios: an event-sourced customer aggregate (see event sourcing) that cannot rewrite history; a DLQ holding six months of failed orders with addresses; Redis Streams capped with MAXLEN where old entries still contain email addresses until trimmed.

TechniqueHowAdvantageLimitation
Data minimisationSend ids, load PII at the consumerNothing to erase in the brokerConsumer needs a lookup
Short retentionretention.ms, queue TTL, XTRIM MINIDSimple, automaticReplays lose history too
Compaction + tombstoneNull value for the subject's keyNative Kafka erasure for keyed topicsOnly for topics keyed by subject; timing depends on the log cleaner
Crypto-shreddingPer-subject key in KMS, delete on requestCovers every copy, including backupsKey management cost; metadata stays
PseudonymisationReplace identity with a token, mapping elsewhereAnalytics stay usefulMapping table becomes the sensitive store

How to use it: keep PII out of keys, headers, topic names and trace attributes; separate “facts about an order” from “facts about a person”; record the subject-to-key mapping in a key registry (SQL below). Describe the result to auditors as “made unreadable by key destruction”, and let your legal team decide whether that meets a specific obligation.

Multi-tenant isolation and quotas Important ​

In plain words: Several teams or customers share one cluster without reading, breaking or starving each other.

Common misunderstanding: “RabbitMQ vhosts isolate tenants completely.” The RabbitMQ docs say “Separation of physical resources is not a goal of virtual hosts”; a noisy tenant still shares memory, disk and CPU.

Definition: Logical isolation uses namespaces: RabbitMQ virtual hosts (permissions are per vhost), Kafka topic prefixes enforced with prefixed ACLs, Redis key prefixes enforced with ACL key patterns. Resource isolation uses limits: RabbitMQ max-connections and max-queues per vhost, Kafka client quotas (bytes and request rate per principal) and broker connection limits, Redis maxmemory per instance (or separate instances).

text
1 Tenant acme -> Kafka: CreateTopics "acme.invoices" -> prefixed CREATE on "acme." -> allowed
2 Tenant acme -> Kafka: Produce "globex.invoices"     -> no ACL -> denied
3 Tenant acme -> Kafka: 400 MB/s burst                -> quota throttles acme only
4 Tenant globex latency unchanged
IsolationRabbitMQKafkaRedis
Namespacevhost per tenant or environmentPrefix (acme.) + prefixed ACLsKey prefix + ~acme:*
Limitsrabbitmqctl set_vhost_limits (max-connections, max-queues)Client quotas, connection limitsSeparate instance or maxmemory
Hard isolationSeparate clusterSeparate clusterSeparate instance

How to use it: use vhosts or prefixes for logical separation, quotas for fairness, and separate clusters where a regulator or contract demands physical isolation. Never let a tenant's name in a message choose the destination without an allow-list.

Audit logging and the management plane Good to know ​

In plain words: Record who connected, who was refused and who changed permissions, and keep admin tools off the public internet.

Common misunderstanding: “Monitoring access is harmless.” A management UI user can often read message bodies with “Get messages”, and a Kafka console consumer with a monitoring credential is still a consumer.

Definition: The management plane is every interface that changes or inspects the broker: RabbitMQ management UI/HTTP API (15672, HTTPS 15671) with user tags management, policymaker, monitoring, administrator; Kafka Admin API (gated by ACLs on the Cluster resource) and JMX; Redis CONFIG, ACL, MONITOR, DEBUG (category @admin). Audit sources: RabbitMQ logs (“PLAIN login refused …”) and the event exchange plugin, Kafka kafka.authorizer.logger (INFO records denials, DEBUG records allowed requests), Redis ACL LOG (reasons auth, command, key, channel).

text
1 Unknown host -> 15672: login admin/admin   -> refused, logged
2 Operator -> UI: "Get messages" on payments queue -> body visible (needs read on queue)
3 CI deploy -> kafka-acls --add ...           -> ALTER on Cluster, authorizer log line
4 Worker -> Redis: CONFIG SET dir /tmp        -> NOPERM, ACL LOG reason=command
ExposureRabbitMQKafkaRedis
Admin endpoint15672/15671, rabbitmqadmin, CLI on 25672/35672-35682Admin API on broker listeners, controller listener, JMXSame port as data; @admin commands
Bind privatelymanagement.tcp.ip, firewallSeparate internal listener; never expose controller listenerbind, protected mode, firewall
AuditLogs, event exchangekafka.authorizer.logger, kafka.request.loggerACL LOG, slowlog, external proxy logs

How to use it: ship audit logs off the broker to append-only storage; Kafka's docs note there is “no built-in tamper-evident audit trail”. Alert on spikes of authentication failures and on any ACL change outside the deployment pipeline. Detailed metric pipelines are in messaging observability.

Mechanics and exact controls ​

Ports and listeners Must-know ​

PortBrokerPurposeExpose to
5672 / 5671RabbitMQAMQP 0-9-1 and 1.0 without / with TLS5671 only, to application subnets
5552 / 5551RabbitMQStream protocol without / with TLS5551 only
15672 / 15671RabbitMQManagement UI and HTTP API without / with TLSOperator network, via VPN or bastion
25672, 4369, 35672-35682RabbitMQInter-node (Erlang distribution), epmd, CLI toolsCluster nodes only
9092 / 9093 (convention)KafkaClient listeners (PLAINTEXT / SSL or SASL_SSL)TLS listener only
Controller listenerKafkaKRaft controller quorumNever client networks
6379RedisData port (port or tls-port)Application subnets; port 0 when TLS-only
16379 (port + 10000)Redis ClusterCluster bus (tls-cluster yes)Cluster nodes only

Kafka listener protocols and client properties Must-know ​

security.protocolAuthenticationEncryptionUse
PLAINTEXTNoneNoneClosed test environments only
SSLOptional mTLSTLSCertificate-based identity
SASL_PLAINTEXTSASLNoneNever with PLAIN; avoid in production
SASL_SSLSASL (+ optional mTLS)TLSDefault choice for services
properties
# Java/librdkafka-style client properties (Go uses kgo options instead)
security.protocol=SASL_SSL
sasl.mechanism=SCRAM-SHA-512
ssl.truststore.location=/run/secrets/kafka-truststore.jks
ssl.endpoint.identification.algorithm=https
config.providers=file
config.providers.file.class=org.apache.kafka.common.config.provider.FileConfigProvider
sasl.jaas.config=${file:/run/secrets/kafka.properties:jaas}

Broker side: listeners=SASL_SSL://:9093, sasl.enabled.mechanisms=SCRAM-SHA-512, security.inter.broker.protocol=SASL_SSL, authorizer.class.name=org.apache.kafka.metadata.authorizer.StandardAuthorizer, super.users=User:admin, and allow.everyone.if.no.acl.found=false (the default). SCRAM credentials are created with kafka-storage.sh format --add-scram before the first start or kafka-configs.sh --alter --add-config 'SCRAM-SHA-512=[iterations=8192,password=...]' later; Kafka requires at least 4096 iterations.

RabbitMQ permission checks Important ​

Operationconfigurewriteread
queue.declare (non-passive)queue
queue.bindqueueexchange
basic.publishexchange
basic.consume, basic.get, queue.purgequeue
exchange.declare with alternate exchangeexchangeexchange (AE)exchange
Passive declare (4.3.1+)any one of configure, write or read on the resource

Regexes are anchored by you: ^orders\.billing$. ^$ (or an empty string) matches nothing; built-in names start with amq. and server-generated queues with amq.gen. The default exchange is checked as amq.default. Variable expansion supports username, vhost and (MQTT) client_id, so ^{username}-.* grants per-user prefixes.

bash
# expected, not run
rabbitmqctl add_vhost orders --default-queue-type quorum
rabbitmqctl add_user billing "$(cat /run/secrets/billing-pass)"
rabbitmqctl set_permissions -p orders billing '^$' '^$' '^orders\.billing$'
rabbitmqctl set_topic_permissions -p orders orders-producer amq.topic '^order\..*' '^$'
rabbitmqctl set_vhost_limits -p orders '{"max-connections": 256, "max-queues": 1024}'
rabbitmqctl delete_user guest

Redis ACL semantics Important ​

Rules apply left to right and ACL SETUSER is incremental: calling it twice adds to the user rather than replacing it. New users start off, with no passwords, no keys, no channels and -@all. Since Redis 7.0 acl-pubsub-default is resetchannels. Key permissions: ~pattern is read and write, %R~ read, %W~ write; LPUSH needs only write, LPOP needs read and write. Commands that touch the whole keyspace (FLUSHALL, FLUSHDB, SWAPDB) are not limited by key patterns, so remove them explicitly. Passwords are stored as SHA-256 hashes (#hash in an aclfile); persist runtime changes with ACL SAVE (CONFIG REWRITE does not).

text
ACL SETUSER orders-consumer on >********** resetkeys ~stream:orders:* resetchannels -@all +xreadgroup +xack +xautoclaim +xpending +ping +hello
ACL SETUSER orders-consumer +xadd          # incremental: now it can also produce
ACL LOG 1                                  # reason=command, username=orders-consumer

Error messages you will meet Must-know ​

SignalMeaningFirst check
PLAIN login refused: user 'guest' can only connect via localhostRabbitMQ loopback_users defaultCreate a real user; do not set loopback_users = none
access to vhost '/' refused for user 'user2'No permissions in that vhostrabbitmqctl set_permissions -p
AMQP 403 ACCESS_REFUSEDPermission regex did not matchWhich of configure/write/read the operation needs
amqp091 ErrSASL / ErrCredentialsNo shared mechanism / bad credentialsEXTERNAL plugin enabled? correct user?
Kafka TOPIC_AUTHORIZATION_FAILED (29)No ACL for the topic operationkafka-acls --list --topic t --resource-pattern-type match
Kafka GROUP_AUTHORIZATION_FAILED (30)Consumer lacks READ on its groupACL on --group
Kafka CLUSTER_AUTHORIZATION_FAILED (31)Admin or idempotent-write operation deniedCluster-level ACL
Kafka TRANSACTIONAL_ID_AUTHORIZATION_FAILED (53)Transactional producer lacks WRITE on its id--transactional-id ACL
Redis NOPERM this user has no permissions to run the 'set' commandACL command ruleACL GETUSER, ACL LOG
Redis WRONGPASSBad user/password or user disabledSecret rotation, user on
Go tls: failed to verify certificate: x509: certificate is valid for broker.internal, not attacker.exampleHostname verification workedDNS, SAN list, ServerName
Go x509: certificate signed by unknown authority (Linux; macOS reports “certificate is not trusted”)CA bundle missingRootCAs, mounted CA file

Solving the classic problems ​

Hardening a fresh broker ​

StepRabbitMQKafkaRedis
Remove defaultsDelete guest, remove ANONYMOUS from auth_mechanismsConfigure an authorizer; keep allow.everyone.if.no.acl.found=falseDisable default user or give it no permissions
EncryptTLS listener 5671 only, management on 15671SASL_SSL listeners, TLS inter-brokerport 0, tls-port 6379, tls-replication yes
IdentitiesOne user (or certificate) per serviceSCRAM user or certificate per serviceACL user per role
PermissionsPer-vhost regexes, topic permissionsLiteral or prefixed ACLsCommand + key + channel rules
Limitsvhost limitsQuotasmaxmemory, separate instances
Admin planeBind management privately, TLSPrivate controller listener, JMX auth or localhost-@admin -@dangerous for apps
AuditShip logs; alert on refusalskafka.authorizer.logger at INFOACL LOG scraping

Rotating credentials without downtime ​

ProblemSolutionAdvantageLimitation
SCRAM password rotationAdd new credential, update secret file, clients reconnect via callback, remove oldNo restartOld credential valid during overlap
RabbitMQ password rotationrabbitmqctl change_password, reconnect clientsSimpleOpen connections keep working until reconnect
OAuth token expiryupdate-secret on AMQP 0-9-1; Kafka OAUTHBEARER refreshShort-lived credentialsNeeds IdP availability
Certificate rotationOverlapping validity, reload (Kafka dynamic broker config)No shared secretPKI automation required
Redis ACL rotationAdd second password with >new, rotate, remove with <oldTwo passwords per user supportedPersist with ACL SAVE

Erasing a person from an immutable log ​

Keep a key registry: one KEK per data subject (or per tenant), recorded with its status. The registry itself contains no PII beyond the subject identifier.

sql
CREATE TABLE subject_key (
    subject_id   text PRIMARY KEY,           -- e.g. 'customer-42'
    kms_key_id   text NOT NULL UNIQUE,       -- KMS key ARN or Vault key name
    created_at   timestamptz NOT NULL DEFAULT now(),
    shredded_at  timestamptz,                -- set when the KEK is scheduled for deletion
    shredded_by  text
);

CREATE TABLE security_audit (
    id          bigserial PRIMARY KEY,
    occurred_at timestamptz NOT NULL DEFAULT now(),
    actor       text NOT NULL,               -- service or human identity
    action      text NOT NULL,               -- 'key.shred', 'acl.change', 'replay.approved'
    subject     text,
    detail      jsonb NOT NULL DEFAULT '{}'
);

-- Erasure request: mark, then schedule KEK deletion in the KMS from the same workflow.
UPDATE subject_key SET shredded_at = now(), shredded_by = 'privacy-service'
WHERE subject_id = 'customer-42' AND shredded_at IS NULL;
INSERT INTO security_audit (actor, action, subject) VALUES ('privacy-service', 'key.shred', 'customer-42');

The Kafka side is a tombstone for compacted, subject-keyed topics plus key destruction for everything else. The Go envelope test TestCryptoShredding shows the effect: after Destroy, Open returns ErrUnknownKey for every stored copy.

Leaking PII through logs, traces and DLQs ​

ProblemSolutionAdvantageLimitation
Payload logged on failureLog ids, reason codes, sizesLogs need no special retentionDebugging needs a secured lookup
Span attributes contain bodiesAllow-list attributes in OTelTraces safe to shareLess detail
DLQ keeps PII for monthsEncrypt payloads; DLQ retention aligned with policyRecovery still possibleReplay needs KMS access
failed_jobs stores serialized jobShouldBeEncrypted, queue:prune-failedLaravel-nativeAPP_KEY holders can read

Choosing a protection level ​

SituationRecommendationExtra techniqueReason
Internal events, no personal dataTLS + per-service identity + least privilegePrefixed ACLsBaseline for any production broker
Payment or health data in eventsBaseline + envelope encryption of sensitive fieldsPer-tenant KEK, short retentionBroker operators and backups must not read it
Commands that move moneyBaseline + signature + replay windowIdempotency key in the inboxA replay must not repeat the effect
Event-sourced aggregates with personal dataCrypto-shredding by subjectKeep PII in a separate, deletable storeImmutable history plus erasure
Multi-tenant SaaS on one clustervhost/prefix per tenant + quotasPer-tenant KEKIsolation of data and capacity
Kafka Connect / stream processorsDedicated principals, delegation tokensACLs per connectorFramework processes fan out widely
Laravel app on Redis queueACL user, TLS, ShouldBeEncryptedPass ids, not models with PIIQueue store holds serialized jobs
Development laptopLocal-only bindingStill no wildcard admin in shared dev clustersHabits move to production

Go ​

Before ​

The demo connection embeds the password in the URL, logs it twice and disables certificate verification. It compiles and connects, which is why it survives code review.

go
// Before: works in a demo, fails a security review. Credentials live in the
// URL and the logs, certificate verification is off, and one admin identity
// with ".*" permissions on the default vhost is shared by every service.
package main

import (
	"crypto/tls"
	"log"
	"os"

	amqp "github.com/rabbitmq/amqp091-go"
)

func main() {
	password := os.Getenv("AMQP_PASSWORD")
	if password == "" {
		log.Println("AMQP_PASSWORD not set; nothing to do")
		return
	}
	url := "amqps://admin:" + password + "@broker.internal:5671/"
	log.Printf("connecting to %s", url) // the password is now in every log sink

	// Accepts any certificate, including one presented by an attacker in the
	// middle. TLS still encrypts, but to whom is unknown.
	conn, err := amqp.DialTLS(url, &tls.Config{InsecureSkipVerify: true})
	if err != nil {
		log.Fatalf("dial %s: %v", url, err) // and again in the error path
	}
	defer conn.Close()
}

After ​

The shared TLS helper requires a CA bundle, sets TLS 1.2 as the floor and loads an optional client certificate. Its tests start a loopback TLS server with a generated CA and prove that the wrong hostname is rejected and that a server requiring client certificates rejects a client without one.

go
// Package tlsconf builds verified client TLS configurations shared by the
// RabbitMQ, Kafka and Redis examples. It never disables verification.
package tlsconf

import (
	"crypto/tls"
	"crypto/x509"
	"errors"
	"fmt"
	"os"
)

// Options names PEM files mounted into the process (for example by a
// secrets agent). Paths are configuration; the file contents are secrets.
type Options struct {
	CAFile     string // private CA bundle that signed the broker certificates
	CertFile   string // optional client certificate for mTLS
	KeyFile    string // private key matching CertFile
	ServerName string // optional SNI and hostname to verify; defaults to the dialed host
}

// ErrNoCA is returned when the CA bundle contains no usable certificate.
var ErrNoCA = errors.New("tlsconf: CA bundle contains no certificates")

// Client returns a TLS 1.2+ client configuration that verifies the broker
// chain against the private CA and, when configured, presents a client
// certificate. InsecureSkipVerify is never set.
func Client(o Options) (*tls.Config, error) {
	if o.CAFile == "" {
		return nil, errors.New("tlsconf: CAFile is required; refusing to trust any certificate")
	}
	pemBytes, err := os.ReadFile(o.CAFile)
	if err != nil {
		return nil, fmt.Errorf("tlsconf: read CA bundle: %w", err)
	}
	pool := x509.NewCertPool()
	if !pool.AppendCertsFromPEM(pemBytes) {
		return nil, ErrNoCA
	}
	cfg := &tls.Config{
		MinVersion: tls.VersionTLS12,
		RootCAs:    pool,
		ServerName: o.ServerName,
	}
	if o.CertFile != "" || o.KeyFile != "" {
		if o.CertFile == "" || o.KeyFile == "" {
			return nil, errors.New("tlsconf: client certificate and key must be set together")
		}
		pair, err := tls.LoadX509KeyPair(o.CertFile, o.KeyFile)
		if err != nil {
			return nil, fmt.Errorf("tlsconf: load client key pair: %w", err)
		}
		cfg.Certificates = []tls.Certificate{pair}
	}
	return cfg, nil
}

// FromEnv reads PREFIX_CA_FILE, PREFIX_CERT_FILE, PREFIX_KEY_FILE and
// PREFIX_SERVER_NAME. ok is false when no CA file is configured.
func FromEnv(prefix string) (o Options, ok bool) {
	o = Options{
		CAFile:     os.Getenv(prefix + "_CA_FILE"),
		CertFile:   os.Getenv(prefix + "_CERT_FILE"),
		KeyFile:    os.Getenv(prefix + "_KEY_FILE"),
		ServerName: os.Getenv(prefix + "_SERVER_NAME"),
	}
	return o, o.CAFile != ""
}

Secrets come from mounted files with private permissions and are re-read on each authentication.

go
// Package secret reads credentials that a secrets agent (Vault Agent, a
// Kubernetes secret volume, a cloud secret manager sidecar) mounts as files.
// Reading on every authentication lets rotation work without a restart.
package secret

import (
	"errors"
	"fmt"
	"os"
	"strings"
)

// ErrTooOpen is returned when group or other users can read the file.
var ErrTooOpen = errors.New("secret: file permissions allow group/other access")

// File returns the trimmed contents of path. It refuses empty secrets and
// files readable by group or other users.
func File(path string) (string, error) {
	info, err := os.Stat(path)
	if err != nil {
		return "", fmt.Errorf("secret: %w", err)
	}
	if info.Mode().Perm()&0o077 != 0 {
		return "", fmt.Errorf("%w: %s", ErrTooOpen, path)
	}
	b, err := os.ReadFile(path)
	if err != nil {
		return "", fmt.Errorf("secret: %w", err)
	}
	v := strings.TrimSpace(string(b))
	if v == "" {
		return "", fmt.Errorf("secret: %s is empty", path)
	}
	return v, nil
}

// Redact keeps a short prefix for correlation in logs and hides the rest.
func Redact(v string) string {
	if len(v) <= 4 {
		return "****"
	}
	return v[:2] + "****"
}

Envelope encryption: fresh DEK and nonce per message, AES-256-GCM with AAD that binds version, key id and destination, and a KeyWrapper interface for the KMS. Seven tests cover round trip, tampering, a moved message, a swapped key id, 1,000 unique nonces and ciphertexts, crypto-shredding and missing headers.

go
// Package envelope implements per-message envelope encryption for broker
// payloads: a fresh 256-bit data key (DEK) and a fresh 96-bit nonce per
// message, AES-256-GCM over the body, and the DEK wrapped by a key-encryption
// key (KEK) that never leaves the KMS. Headers carry the key id, the wrapped
// DEK and the nonce; the broker stores only ciphertext.
package envelope

import (
	"context"
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"encoding/base64"
	"encoding/binary"
	"errors"
	"fmt"
)

// Header names used on RabbitMQ headers, Kafka record headers or Redis
// stream fields.
const (
	HeaderVersion = "enc-v"
	HeaderKeyID   = "enc-kid"
	HeaderDEK     = "enc-dek"
	HeaderNonce   = "enc-nonce"
	version       = "v1"
)

// KeyWrapper is the KMS boundary (AWS KMS Encrypt/Decrypt, GCP Cloud KMS,
// Vault Transit, an HSM). Implementations must authenticate and audit calls.
type KeyWrapper interface {
	Wrap(ctx context.Context, keyID string, dek []byte) ([]byte, error)
	Unwrap(ctx context.Context, keyID string, wrapped []byte) ([]byte, error)
}

// Errors callers can branch on.
var (
	ErrMissingHeader = errors.New("envelope: missing encryption header")
	ErrDecrypt       = errors.New("envelope: authentication failed (tampered, wrong context or wrong key)")
)

// Envelope is one encrypted message.
type Envelope struct {
	KeyID      string
	WrappedDEK []byte
	Nonce      []byte
	Ciphertext []byte
}

// aad binds the ciphertext to its version, key id and caller context (for
// example destination and message id), with length prefixes so that
// ("ab","c") and ("a","bc") differ.
func aad(keyID string, context []byte) []byte {
	out := make([]byte, 0, 16+len(version)+len(keyID)+len(context))
	for _, part := range [][]byte{[]byte(version), []byte(keyID), context} {
		out = binary.BigEndian.AppendUint32(out, uint32(len(part)))
		out = append(out, part...)
	}
	return out
}

// Seal encrypts plaintext under a new data key wrapped by keyID.
func Seal(ctx context.Context, kms KeyWrapper, keyID string, plaintext, context []byte) (Envelope, error) {
	dek := make([]byte, 32)
	if _, err := rand.Read(dek); err != nil {
		return Envelope{}, err
	}
	defer clear(dek)

	gcm, err := newGCM(dek)
	if err != nil {
		return Envelope{}, err
	}
	// A random nonce is safe here because every DEK encrypts exactly one
	// message; GCM's nonce-uniqueness rule is per key.
	nonce := make([]byte, gcm.NonceSize())
	if _, err := rand.Read(nonce); err != nil {
		return Envelope{}, err
	}
	ct := gcm.Seal(nil, nonce, plaintext, aad(keyID, context))

	wrapped, err := kms.Wrap(ctx, keyID, dek)
	if err != nil {
		return Envelope{}, fmt.Errorf("envelope: wrap data key: %w", err)
	}
	return Envelope{KeyID: keyID, WrappedDEK: wrapped, Nonce: nonce, Ciphertext: ct}, nil
}

// Open unwraps the data key and authenticates and decrypts the body. The
// same context bytes used by Seal must be supplied.
func Open(ctx context.Context, kms KeyWrapper, e Envelope, context []byte) ([]byte, error) {
	dek, err := kms.Unwrap(ctx, e.KeyID, e.WrappedDEK)
	if err != nil {
		return nil, fmt.Errorf("envelope: unwrap data key: %w", err)
	}
	defer clear(dek)
	gcm, err := newGCM(dek)
	if err != nil {
		return nil, err
	}
	if len(e.Nonce) != gcm.NonceSize() {
		return nil, ErrDecrypt
	}
	pt, err := gcm.Open(nil, e.Nonce, e.Ciphertext, aad(e.KeyID, context))
	if err != nil {
		return nil, ErrDecrypt
	}
	return pt, nil
}

// Headers renders the envelope metadata as string headers. The body is
// e.Ciphertext.
func (e Envelope) Headers() map[string]string {
	b64 := base64.StdEncoding.EncodeToString
	return map[string]string{
		HeaderVersion: version,
		HeaderKeyID:   e.KeyID,
		HeaderDEK:     b64(e.WrappedDEK),
		HeaderNonce:   b64(e.Nonce),
	}
}

// FromHeaders rebuilds an envelope from received headers and body.
func FromHeaders(h map[string]string, body []byte) (Envelope, error) {
	if h[HeaderVersion] != version || h[HeaderKeyID] == "" || h[HeaderDEK] == "" || h[HeaderNonce] == "" {
		return Envelope{}, ErrMissingHeader
	}
	dek, err := base64.StdEncoding.DecodeString(h[HeaderDEK])
	if err != nil {
		return Envelope{}, fmt.Errorf("envelope: %s: %w", HeaderDEK, err)
	}
	nonce, err := base64.StdEncoding.DecodeString(h[HeaderNonce])
	if err != nil {
		return Envelope{}, fmt.Errorf("envelope: %s: %w", HeaderNonce, err)
	}
	return Envelope{KeyID: h[HeaderKeyID], WrappedDEK: dek, Nonce: nonce, Ciphertext: body}, nil
}

func newGCM(key []byte) (cipher.AEAD, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	return cipher.NewGCM(block)
}

HMAC signing with freshness and replay detection:

go
// Package signing adds HMAC-SHA256 integrity and replay protection to
// messages. The signature covers key id, timestamp, message id and body, so
// none of them can be changed independently. Verification checks the MAC in
// constant time first, then freshness, then the replay cache.
package signing

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"encoding/binary"
	"errors"
	"strconv"
	"sync"
	"time"
)

// Header names.
const (
	HeaderKeyID = "sig-kid"
	HeaderTime  = "sig-ts"
	HeaderMsgID = "sig-msg-id"
	HeaderMAC   = "sig"
)

// Verification errors.
var (
	ErrUnknownKey   = errors.New("signing: unknown key id")
	ErrBadSignature = errors.New("signing: signature mismatch")
	ErrStale        = errors.New("signing: timestamp outside the accepted window")
	ErrReplay       = errors.New("signing: message id already seen")
)

func mac(key []byte, kid, ts, msgID string, body []byte) []byte {
	m := hmac.New(sha256.New, key)
	for _, part := range [][]byte{[]byte("v1"), []byte(kid), []byte(ts), []byte(msgID), body} {
		var n [4]byte
		binary.BigEndian.PutUint32(n[:], uint32(len(part)))
		m.Write(n[:])
		m.Write(part)
	}
	return m.Sum(nil)
}

// Sign returns the headers to attach to a message.
func Sign(kid string, key []byte, msgID string, at time.Time, body []byte) map[string]string {
	ts := strconv.FormatInt(at.Unix(), 10)
	return map[string]string{
		HeaderKeyID: kid,
		HeaderTime:  ts,
		HeaderMsgID: msgID,
		HeaderMAC:   base64.StdEncoding.EncodeToString(mac(key, kid, ts, msgID, body)),
	}
}

// Verifier holds verification keys (several during rotation), a freshness
// window and a replay cache sized to that window.
type Verifier struct {
	Keys   map[string][]byte
	MaxAge time.Duration
	Now    func() time.Time

	mu   sync.Mutex
	seen map[string]time.Time
}

// Verify authenticates the message and records its id.
func (v *Verifier) Verify(h map[string]string, body []byte) error {
	key, ok := v.Keys[h[HeaderKeyID]]
	if !ok {
		return ErrUnknownKey
	}
	got, err := base64.StdEncoding.DecodeString(h[HeaderMAC])
	if err != nil || !hmac.Equal(got, mac(key, h[HeaderKeyID], h[HeaderTime], h[HeaderMsgID], body)) {
		return ErrBadSignature
	}
	sec, err := strconv.ParseInt(h[HeaderTime], 10, 64)
	if err != nil {
		return ErrBadSignature
	}
	now := v.Now()
	at := time.Unix(sec, 0)
	if now.Sub(at) > v.MaxAge || at.Sub(now) > v.MaxAge {
		return ErrStale
	}

	v.mu.Lock()
	defer v.mu.Unlock()
	if v.seen == nil {
		v.seen = map[string]time.Time{}
	}
	for id, exp := range v.seen { // bounded: entries live only for the window
		if now.After(exp) {
			delete(v.seen, id)
		}
	}
	if _, dup := v.seen[h[HeaderMsgID]]; dup {
		return ErrReplay
	}
	v.seen[h[HeaderMsgID]] = at.Add(v.MaxAge)
	return nil
}

The Go angle ​

Go's crypto/tls verifies chains and host names unless InsecureSkipVerify is set, and the three clients accept a *tls.Config: amqp091-go through Config.TLSClientConfig or DialTLS, franz-go through kgo.DialTLSConfig (which sets ServerName per broker), go-redis through Options.TLSConfig. Credentials are best supplied through callbacks (scram.Sha512(func), CredentialsProviderContext) so rotation does not need a restart. crypto/cipher.NewGCM uses a 12-byte nonce; crypto/rand is the only acceptable source for keys and nonces. The module pins franz-go v1.18.0 and go-redis v9.7.3 so it builds with go 1.24; newer releases require Go 1.26.

Laravel ​

Before ​

The job carries an email, IBAN and transaction list in clear text and logs them.

php
<?php

namespace App\Jobs;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Log;

// Before: the serialized job carries the full customer profile in clear
// text. Anyone who can read the queue (Redis MONITOR, a RabbitMQ management
// "Get messages", a Kafka console consumer, the failed_jobs table, a backup)
// can read it, and the log line copies it again.
class SendStatementEmail implements ShouldQueue
{
    use Queueable;

    public function __construct(
        public string $email,
        public string $iban,
        public string $fullName,
        public array $transactions,
    ) {}

    public function handle(): void
    {
        Log::info('sending statement', [
            'email' => $this->email,
            'iban' => $this->iban,
            'transactions' => $this->transactions,
        ]);
        // ... render and send
    }
}

After ​

The job carries an identifier, loads PII inside the worker and implements ShouldBeEncrypted. The Laravel docs say that with this interface “Laravel will automatically encrypt your job before pushing it onto a queue”.

php
<?php

namespace App\Jobs;

use App\Models\Customer;
use Illuminate\Contracts\Queue\ShouldBeEncrypted;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Log;

// After: data minimisation first (carry an identifier, load the PII inside
// the trust boundary), ShouldBeEncrypted second. Laravel encrypts the
// serialized command with APP_KEY before pushing it; uuid, displayName and
// other envelope fields stay readable, so never put PII in the class name or
// in custom payload hooks.
class SendStatementEmail implements ShouldQueue, ShouldBeEncrypted
{
    use Queueable;

    public function __construct(
        public int $customerId,
        public string $statementPeriod,
    ) {}

    public function handle(): void
    {
        $customer = Customer::query()->findOrFail($this->customerId);

        // Log identifiers and outcomes, not personal data.
        Log::info('sending statement', [
            'customer_id' => $this->customerId,
            'period' => $this->statementPeriod,
            'job_uuid' => $this->job?->uuid(),
        ]);
        // ... render and send to $customer->email
    }
}

Field-level envelope encryption reuses Laravel's Encrypter class with a fresh per-message key and aes-256-gcm, one of the four ciphers the framework source lists as supported:

php
<?php

namespace App\Security;

// The KMS boundary: AWS KMS, Google Cloud KMS, Azure Key Vault or Vault
// Transit behind one interface. The key-encryption key never leaves the KMS.
interface KeyWrapper
{
    public function wrap(string $keyId, string $dataKey): string;

    public function unwrap(string $keyId, string $wrappedKey): string;
}
php
<?php

namespace App\Security;

use Illuminate\Encryption\Encrypter;

// Field-level envelope encryption for message payloads. Every call creates a
// fresh 32-byte data key and uses Laravel's Encrypter with aes-256-gcm (an
// AEAD cipher the framework supports alongside the CBC defaults). The wrapped
// data key and the key id travel with the field, so a consumer with KMS
// permission on that key id can decrypt and nobody else can.
final class EnvelopeCipher
{
    public function __construct(private KeyWrapper $kms) {}

    /** @return array{kid: string, dek: string, ct: string} */
    public function seal(string $keyId, string $plaintext): array
    {
        $dataKey = Encrypter::generateKey('aes-256-gcm');
        $ciphertext = (new Encrypter($dataKey, 'aes-256-gcm'))->encryptString($plaintext);

        $wrapped = $this->kms->wrap($keyId, $dataKey);
        sodium_memzero($dataKey);

        return ['kid' => $keyId, 'dek' => base64_encode($wrapped), 'ct' => $ciphertext];
    }

    /** @param array{kid: string, dek: string, ct: string} $field */
    public function open(array $field): string
    {
        $dataKey = $this->kms->unwrap($field['kid'], base64_decode($field['dek'], true) ?: '');

        try {
            // Throws DecryptException when the ciphertext or tag was altered.
            return (new Encrypter($dataKey, 'aes-256-gcm'))->decryptString($field['ct']);
        } finally {
            sodium_memzero($dataKey);
        }
    }
}

The Laravel angle ​

Laravel 13 ships database, Amazon SQS, Redis and Beanstalkd queue drivers; RabbitMQ and Kafka come from packages. Reading the framework source (Illuminate\Queue\Queue::createObjectPayload) shows that ShouldBeEncrypted encrypts only the data.command field with the application encrypter; uuid, displayName, maxTries, backoff and commandName stay readable. Crypt::encryptString uses AES-256-CBC with a MAC and throws DecryptException on tampering; rotating APP_KEY without APP_PREVIOUS_KEYS makes queued encrypted jobs undecryptable. Keep env() calls inside config/*.php, cache configuration in production, and use php artisan env:encrypt only for files that must be committed. Failed encrypted jobs remain encrypted in failed_jobs; prune them with queue:prune-failed.

Laravel featureSecurity roleCaveat
ShouldBeEncryptedEncrypts serialized job commandEnvelope fields stay clear; APP_KEY decrypts everything
Crypt::encryptString / decryptStringAuthenticated encryption of valuesOne app-wide key
Encrypter with aes-256-gcmPer-message data keysYou manage the KEK through a KMS
APP_PREVIOUS_KEYSGraceful key rotationOld keys stay usable until removed
env:encrypt / env:decryptEncrypted .env in the repositoryThe decryption key becomes the secret
config/database.php redis scheme => tls, usernameTLS and ACL userCA trust is a PHP/OpenSSL setting
queue:prune-failedLimit retention of failed payloadsRun it on a schedule

Broker differences ​

RabbitMQ ​

RabbitMQ terminates TLS on 5671 (listeners.ssl.default, ssl_options.cacertfile/certfile/keyfile, verify_peer, fail_if_no_peer_cert) and limits versions with ssl_options.versions. Authentication is pluggable through auth_backends (internal, LDAP, HTTP, OAuth 2.0, cache) and auth_mechanisms (PLAIN, AMQPLAIN, ANONYMOUS by default; EXTERNAL via rabbitmq_auth_mechanism_ssl). The OAuth 2.0 plugin validates JWTs from auth_oauth2.issuer (or jwks_uri) for auth_oauth2.resource_server_id, and maps scopes like rabbitmq.read:orders/* and rabbitmq.tag:administrator to permissions. Authorization is per vhost (configure/write/read regexes) plus optional topic permissions; user tags govern the management UI only. RabbitMQ does not encrypt messages at rest; quorum queue and stream data on disk are plain bytes unless the volume is encrypted.

go
// RabbitMQ: AMQPS on 5671 with chain + hostname verification, the identity
// taken from the client certificate (SASL EXTERNAL via the
// rabbitmq_auth_mechanism_ssl plugin), a dedicated vhost, and no secret in
// the URL. PLAIN over TLS is the fallback when certificates are not issued
// per service.
package main

import (
	"context"
	"log"
	"os"
	"time"

	amqp "github.com/rabbitmq/amqp091-go"

	"academy/messaging-security/secret"
	"academy/messaging-security/tlsconf"
)

func config() (amqp.Config, error) {
	opts, _ := tlsconf.FromEnv("AMQP")
	tlsCfg, err := tlsconf.Client(opts)
	if err != nil {
		return amqp.Config{}, err
	}
	props := amqp.NewConnectionProperties()
	props.SetClientConnectionName("billing-consumer") // visible in the management UI and audit logs

	cfg := amqp.Config{
		Vhost:           "orders",
		TLSClientConfig: tlsCfg,
		Properties:      props,
		Heartbeat:       10 * time.Second,
		// mTLS: the broker maps the certificate subject to a RabbitMQ user.
		SASL: []amqp.Authentication{&amqp.ExternalAuth{}},
	}
	if user := os.Getenv("AMQP_USER"); user != "" {
		pw, err := secret.File(os.Getenv("AMQP_PASSWORD_FILE"))
		if err != nil {
			return amqp.Config{}, err
		}
		// PLAIN sends the password inside the TLS tunnel; never over 5672.
		cfg.SASL = []amqp.Authentication{&amqp.PlainAuth{Username: user, Password: pw}}
	}
	return cfg, nil
}

// refreshToken keeps an OAuth 2.0 connection alive: AMQP 0-9-1 update-secret
// replaces the JWT on the open connection before it expires.
func refreshToken(ctx context.Context, conn *amqp.Connection, tokenFile string, every time.Duration) {
	t := time.NewTicker(every)
	defer t.Stop()
	for {
		select {
		case <-ctx.Done():
			return
		case <-t.C:
			tok, err := secret.File(tokenFile)
			if err != nil {
				log.Printf("token read failed: %v", err)
				continue
			}
			if err := conn.UpdateSecret(tok, "scheduled refresh"); err != nil {
				log.Printf("update-secret failed: %v", err) // reconnect with a fresh token
				return
			}
		}
	}
}

func main() {
	url := os.Getenv("AMQPS_URL") // amqps://broker.internal:5671 (no userinfo)
	if url == "" {
		log.Println("AMQPS_URL not set; nothing to do")
		return
	}
	cfg, err := config()
	if err != nil {
		log.Fatalf("tls/auth config: %v", err)
	}
	conn, err := amqp.DialConfig(url, cfg)
	if err != nil {
		log.Fatalf("dial broker: %v", err) // error text, never the URL with secrets
	}
	defer conn.Close()

	if tokenFile := os.Getenv("AMQP_OAUTH_TOKEN_FILE"); tokenFile != "" {
		ctx, cancel := context.WithCancel(context.Background())
		defer cancel()
		go refreshToken(ctx, conn, tokenFile, 4*time.Minute)
	}
	log.Printf("connected to vhost %q as %s", cfg.Vhost, cfg.SASL[0].Mechanism())
}

The Laravel package vladimir-yuldashev/laravel-queue-rabbitmq documents secure and ssl_options (cafile, local_cert, local_key, verify_peer, passphrase):

php
<?php

// config/queue.php fragment for vladimir-yuldashev/laravel-queue-rabbitmq.
// Option names follow the package README ("SSL Secure"). Port 5671 is AMQPS;
// credentials and certificate paths come from the environment, which a
// secrets manager populates at deploy time. Check the installed package
// version supports your Laravel 13 release before relying on it.

return [
    'connections' => [
        'rabbitmq' => [
            'driver' => 'rabbitmq',
            'hosts' => [
                [
                    'host' => env('RABBITMQ_HOST', 'broker.internal'),
                    'port' => env('RABBITMQ_PORT', 5671),
                    'user' => env('RABBITMQ_USER'),          // per-service user, never guest
                    'password' => env('RABBITMQ_PASSWORD'),
                    'vhost' => env('RABBITMQ_VHOST', 'orders'),
                ],
            ],
            'secure' => true,
            'options' => [
                'ssl_options' => [
                    'cafile' => env('RABBITMQ_SSL_CAFILE'),        // private CA bundle
                    'local_cert' => env('RABBITMQ_SSL_LOCALCERT'), // mTLS client certificate
                    'local_key' => env('RABBITMQ_SSL_LOCALKEY'),
                    'verify_peer' => env('RABBITMQ_SSL_VERIFY_PEER', true),
                    'passphrase' => env('RABBITMQ_SSL_PASSPHRASE'),
                ],
            ],
        ],
    ],
];

What breaks: leaving loopback_users = none to “fix” guest login, granting .* on all three permissions, forgetting that permission changes may apply only after reconnect, and exposing 15672 for convenience.

Kafka ​

Kafka secures each listener independently through listener.security.protocol.map. Clients choose security.protocol (PLAINTEXT, SSL, SASL_PLAINTEXT, SASL_SSL) and a sasl.mechanism (GSSAPI, PLAIN, SCRAM-SHA-256, SCRAM-SHA-512, OAUTHBEARER). SCRAM credentials live in the KRaft metadata log; delegation tokens (kafka-delegation-tokens.sh, delegation.token.secret.key, renew by default every 24 hours up to 7 days) piggyback on SCRAM. Authorization uses StandardAuthorizer; without an authorizer every authenticated principal has full access, with one and no matching ACL access is denied except for super.users. allow.everyone.if.no.acl.found=true is a migration aid, not a steady state. Kafka “does not encrypt data at rest”: use volume encryption, or producer-side message encryption when operators must not read records.

go
// Kafka: security.protocol=SASL_SSL expressed with franz-go. TLS verifies
// the broker chain and hostname (DialTLSConfig sets ServerName per broker);
// SCRAM-SHA-512 proves the identity without sending the password. The
// credential callback runs for every new connection, so a rotated secret
// file is picked up without a restart.
package main

import (
	"context"
	"log"
	"os"
	"strings"

	"github.com/twmb/franz-go/pkg/kgo"
	"github.com/twmb/franz-go/pkg/sasl/scram"

	"academy/messaging-security/secret"
	"academy/messaging-security/tlsconf"
)

func options(brokers []string) ([]kgo.Opt, error) {
	opts, _ := tlsconf.FromEnv("KAFKA")
	tlsCfg, err := tlsconf.Client(opts)
	if err != nil {
		return nil, err
	}
	user := os.Getenv("KAFKA_USER")
	passFile := os.Getenv("KAFKA_PASSWORD_FILE")
	creds := func(context.Context) (scram.Auth, error) {
		pw, err := secret.File(passFile)
		if err != nil {
			return scram.Auth{}, err
		}
		// Set IsToken: true when User/Pass are a delegation token ID/HMAC.
		return scram.Auth{User: user, Pass: pw, IsToken: os.Getenv("KAFKA_DELEGATION_TOKEN") == "1"}, nil
	}
	return []kgo.Opt{
		kgo.SeedBrokers(brokers...),
		kgo.DialTLSConfig(tlsCfg),
		kgo.SASL(scram.Sha512(creds)),
		kgo.ClientID("billing-consumer"), // shows up in quotas and request logs
		kgo.ConsumerGroup("billing"),     // needs READ on Group:billing
		kgo.ConsumeTopics("orders.events"),
	}, nil
}

func main() {
	brokers := os.Getenv("KAFKA_BROKERS") // broker-1.internal:9093,broker-2.internal:9093
	if brokers == "" {
		log.Println("KAFKA_BROKERS not set; nothing to do")
		return
	}
	opts, err := options(strings.Split(brokers, ","))
	if err != nil {
		log.Fatalf("kafka security config: %v", err)
	}
	cl, err := kgo.NewClient(opts...)
	if err != nil {
		log.Fatalf("kafka client: %v", err)
	}
	defer cl.Close()

	fetches := cl.PollFetches(context.Background())
	fetches.EachError(func(topic string, p int32, err error) {
		// TOPIC_AUTHORIZATION_FAILED (29) or GROUP_AUTHORIZATION_FAILED (30)
		// means the ACLs, not the network, need attention.
		log.Printf("fetch %s/%d: %v", topic, p, err)
	})
}

mateusjunges/laravel-kafka v2.13 exposes withSasl(username, password, mechanisms, securityProtocol), which defaults to SASL_PLAINTEXT, and librdkafka options through withOptions/withConfigOptions. Its TLS example sets ssl.endpoint.identification.algorithm to none; the snippet keeps librdkafka's default https.

php
<?php

namespace App\Messaging;

use Junges\Kafka\Contracts\MessageConsumer;
use Junges\Kafka\Facades\Kafka;

// mateusjunges/laravel-kafka v2.13. withSasl() defaults the security protocol
// to SASL_PLAINTEXT, so SASL_SSL is passed explicitly. The package's TLS
// example sets ssl.endpoint.identification.algorithm to none; this keeps the
// librdkafka default (https) so the broker hostname is verified.
final class SecureKafka
{
    /** @return array<string, string> librdkafka TLS options */
    private function tls(): array
    {
        return [
            'ssl.ca.location' => (string) config('kafka.tls.ca'),
            'ssl.endpoint.identification.algorithm' => 'https',
            'enable.ssl.certificate.verification' => 'true',
        ];
    }

    public function consumer(callable $handler): MessageConsumer
    {
        return Kafka::consumer(['orders.events'], 'billing')
            ->withSasl(
                password: (string) config('kafka.sasl.password'),
                username: (string) config('kafka.sasl.username'),
                mechanisms: 'SCRAM-SHA-512',
                securityProtocol: 'SASL_SSL',
            )
            ->withOptions($this->tls())
            ->withHandler($handler)
            ->build();
    }

    public function publish(string $key, array $body): void
    {
        Kafka::publish((string) config('kafka.brokers'))
            ->onTopic('orders.events')
            ->withConfigOptions($this->tls() + [
                'security.protocol' => 'SASL_SSL',
                'sasl.mechanisms' => 'SCRAM-SHA-512',
                'sasl.username' => (string) config('kafka.sasl.username'),
                'sasl.password' => (string) config('kafka.sasl.password'),
            ])
            ->withKafkaKey($key)
            ->withBodyKey('order', $body)
            ->send();
    }
}
bash
# expected, not run: least-privilege ACLs for one consumer and one producer
kafka-acls.sh --bootstrap-server broker-1.internal:9093 --command-config admin.properties \
  --add --allow-principal User:billing --consumer --topic orders.events --group billing
kafka-acls.sh --bootstrap-server broker-1.internal:9093 --command-config admin.properties \
  --add --allow-principal User:orders-producer --producer --topic orders. --resource-pattern-type prefixed
kafka-acls.sh --bootstrap-server broker-1.internal:9093 --command-config admin.properties \
  --list --topic orders.events --resource-pattern-type match

Redis Streams ​

Redis Streams inherit Redis security: ACL users and rules, optional TLS (compile with BUILD_TLS=yes, tls-port, tls-cert-file, tls-key-file, tls-ca-cert-file, tls-auth-clients, tls-replication, tls-cluster), protected mode and the legacy requirepass. There is no per-entry encryption, no per-stream permission beyond key patterns, and AUTH without TLS is sent in clear text. Persistence files (RDB/AOF) store entries as written. Consumer-group commands (XREADGROUP, XACK) modify group state, so consumers need write permission on the stream key.

go
// Redis Streams: rediss:// (TLS-only port), a named ACL user per role, and
// credentials supplied per connection from a mounted secret file.
package main

import (
	"context"
	"log"
	"os"
	"strings"

	"github.com/redis/go-redis/v9"

	"academy/messaging-security/secret"
	"academy/messaging-security/tlsconf"
)

// ACL rules applied by the platform team (ACL SETUSER or an aclfile).
// Each role names its commands and its key pattern; nothing else is allowed.
var aclRules = map[string]string{
	"orders-producer": "on #<sha256-of-password> resetkeys ~stream:orders:* resetchannels -@all +xadd +ping +hello",
	"orders-consumer": "on #<sha256-of-password> resetkeys ~stream:orders:* resetchannels -@all +xreadgroup +xack +xautoclaim +xpending +ping +hello",
	"orders-admin":    "on #<sha256-of-password> resetkeys ~stream:orders:* resetchannels -@all +@stream +ping +hello",
}

func client(addr, user, passFile string) (*redis.Client, error) {
	opts, _ := tlsconf.FromEnv("REDIS")
	tlsCfg, err := tlsconf.Client(opts)
	if err != nil {
		return nil, err
	}
	return redis.NewClient(&redis.Options{
		Addr:      addr, // server runs "port 0" + "tls-port 6379"
		TLSConfig: tlsCfg,
		CredentialsProviderContext: func(context.Context) (string, string, error) {
			pw, err := secret.File(passFile)
			return user, pw, err // AUTH <username> <password>, never the default user
		},
	}), nil
}

func main() {
	addr := os.Getenv("REDIS_ADDR") // redis.internal:6379
	if addr == "" {
		log.Println("REDIS_ADDR not set; nothing to do")
		for user, rule := range aclRules {
			log.Printf("ACL SETUSER %s %s", user, rule)
		}
		return
	}
	rdb, err := client(addr, "orders-producer", os.Getenv("REDIS_PASSWORD_FILE"))
	if err != nil {
		log.Fatalf("redis config: %v", err)
	}
	defer rdb.Close()

	ctx := context.Background()
	id, err := rdb.XAdd(ctx, &redis.XAddArgs{
		Stream: "stream:orders:events",
		Values: map[string]any{"type": "OrderPlaced", "order_id": "o-1042"},
	}).Result()
	if err != nil && strings.HasPrefix(err.Error(), "NOPERM") {
		log.Fatalf("ACL denied: %v", err) // check ACL LOG on the server
	}
	if err != nil {
		log.Fatalf("xadd: %v", err)
	}
	log.Printf("appended %s", id)
}

Laravel configures TLS with scheme => tls and an ACL user with username:

php
<?php

// config/database.php 'redis' fragment. scheme=tls is the documented Laravel
// switch for TLS; username selects a Redis 6+ ACL user instead of the legacy
// requirepass "default" user. PHP's OpenSSL streams verify the server
// certificate; install the private CA where your PHP build looks for it
// (openssl.cafile) rather than disabling verification.

return [
    'redis' => [
        'client' => env('REDIS_CLIENT', 'phpredis'),

        'streams' => [
            'scheme' => 'tls',
            'host' => env('REDIS_STREAMS_HOST', 'redis.internal'),
            'port' => env('REDIS_STREAMS_PORT', 6379),          // tls-port 6379, port 0
            'username' => env('REDIS_STREAMS_USERNAME', 'orders-producer'),
            'password' => env('REDIS_STREAMS_PASSWORD'),
            'database' => 0,
        ],
    ],
];

Sensitive fields are sealed before XADD because Redis will store whatever bytes it receives:

php
<?php

namespace App\Messaging;

use App\Security\EnvelopeCipher;
use Illuminate\Support\Facades\Redis;

// Redis Streams has no per-entry encryption, so sensitive fields are sealed
// before XADD. The ACL user behind the "streams" connection may only XADD to
// stream:orders:*; anything else returns NOPERM and appears in ACL LOG.
final class RedisStreamsPublisher
{
    public function __construct(private EnvelopeCipher $cipher) {}

    public function orderPlaced(int $orderId, int $customerId, string $shippingAddress): string
    {
        $address = $this->cipher->seal("customer-{$customerId}", $shippingAddress);

        return Redis::connection('streams')->xadd('stream:orders:events', '*', [
            'type' => 'OrderPlaced',
            'order_id' => (string) $orderId,
            'customer_id' => (string) $customerId,
            'address' => json_encode($address, JSON_THROW_ON_ERROR),
        ]);
    }
}

What breaks: relying on protected mode (it turns off as soon as a password is set or bind changes), giving workers +@all, and trimming streams with MAXLEN while assuming PII has left backups.

In production systems ​

  • Kafka's own security model page states that a fresh cluster “accepts unauthenticated PLAINTEXT connections on every listener and applies no authorization”, and that super.users should be treated like a root password.
  • RabbitMQ documents that guest can only connect from localhost by default and that ANONYMOUS acts as anonymous_login_user; its deployment guidance says to remove ANONYMOUS in production.
  • Redis documents protected mode since 3.2.0, ACLs since 6, and the risk that CONFIG lets a client write RDB files to arbitrary paths; hardening means denying @admin and @dangerous to application users.
  • Laravel's queue source shows ShouldBeEncrypted covers the job command only; payload metadata such as displayName is visible to anyone who can read the queue.

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

A Laravel monolith with a Redis queue on the same host still benefits from an ACL user (so a bug in a cache call cannot FLUSHALL the queue) and ShouldBeEncrypted for jobs that carry personal data. The simplest correct setup: Redis bound to a private interface with TLS, REDIS_USERNAME per role, jobs passing ids.

Modular monolith: explicit owners ​

Modules share one RabbitMQ but get their own vhost or queue prefix and their own user. Billing's user can read billing.* and publish to events; shipping cannot read billing's queues. When a module is extracted later, its credentials and permissions move with it instead of being untangled from one shared account.

Microservices: identities per service ​

Orders publishes OrderPlaced to Kafka with principal User:orders (WRITE on orders.events). Billing and Shipping consume with their own principals and groups. The address field is envelope-encrypted under kid=customer-42; only Shipping has KMS decrypt permission for address keys, so Billing never sees it even though it reads the same record. Commands such as IssueRefund carry an HMAC or JWS and a message id, and the consumer's inbox rejects duplicates. Reliable publication still uses the outbox; the outbox table holds the encrypted field, not plaintext.

Distributed data: replicas, mirrors, regions ​

Every copy needs the same controls: Kafka MirrorMaker 2 and Connect use the same ssl.*/sasl.* client configuration and need their own principals; RabbitMQ federation and shovel links carry credentials in their URIs; Redis replicas need tls-replication yes. Multi-region KMS keys (or one key per region) must be reachable by consumers in each region, and crypto-shredding must destroy every replica of the key. Backups of broker volumes inherit the retention and erasure obligations of the topics they contain.

Scaling path ​

LoadSecurity designExample
1×TLS, per-service users, hand-written permissions, ShouldBeEncryptedOne Laravel app and two Go workers
10×Permissions as code, secrets manager, credential callbacks, quotas, audit shippingTen teams on one Kafka cluster with prefixed ACLs
100×Workload PKI (mTLS), OAuth with scopes, per-tenant KEKs, data-key caching, automated access reviewsSaaS platform with thousands of tenants and regional clusters

Lab ​

All broker and Laravel experiments are expected, not run. Use a disposable environment you already have; this chapter does not start Docker or clusters. The Go tests run without a broker.

1. Run the Go security tests ​

bash
cd docs/snippets/messaging/messaging-security/go
go test ./...
# expected: ok for envelope, secret, signing, tlsconf (18 tests)
go test -run 'TestRejectsWrongHostname|TestMutualTLS' -v ./tlsconf
# expected: PASS; a broker.internal certificate fails for attacker.example; no client cert -> server handshake error

2. RabbitMQ: guest, permissions and refusals ​

bash
# expected, not run
rabbitmqctl add_vhost orders
rabbitmqctl add_user billing 'use-a-generated-secret'
rabbitmqctl set_permissions -p orders billing '^$' '^$' '^orders\.billing$'
rabbitmqctl list_user_permissions billing
# expected: orders  ^$  ^$  ^orders\.billing$
# From a remote host, connect as guest/guest:
# expected log: PLAIN login refused: user 'guest' can only connect via localhost
# Declare a queue as billing:
# expected: 403 ACCESS_REFUSED (configure regex ^$)

3. Kafka: authorizer default-deny ​

text
1 Broker: authorizer.class.name=...StandardAuthorizer, no ACLs, billing is not a super user
2 billing -> consume orders.events      -> TOPIC_AUTHORIZATION_FAILED (29)
3 admin  -> kafka-acls --add --consumer --topic orders.events --group billing
4 billing -> consume again              -> records delivered
5 admin  -> kafka-acls --list --topic orders.events --resource-pattern-type match

Expected, not run. Set log4j.logger.kafka.authorizer.logger=INFO and observe one denial line for step 2.

4. Redis: ACL rules and ACL LOG ​

bash
# expected, not run (TLS-enabled Redis 7+)
redis-cli --tls --cacert ca.pem ACL SETUSER orders-producer on '>use-a-generated-secret' resetkeys '~stream:orders:*' resetchannels -@all +xadd +ping +hello
redis-cli --tls --cacert ca.pem --user orders-producer --pass use-a-generated-secret XADD stream:orders:events '*' type OrderPlaced
# expected: an entry id such as 1764115200000-0
redis-cli --tls --cacert ca.pem --user orders-producer --pass use-a-generated-secret XRANGE stream:orders:events - +
# expected: (error) NOPERM ... 'xrange' command
redis-cli --tls --cacert ca.pem ACL LOG 1
# expected: reason "command", username "orders-producer", object "xrange"

5. Crypto-shredding with the envelope package ​

bash
go test -run TestCryptoShredding -v ./envelope
# expected: PASS; Open returns ErrUnknownKey after the subject key is destroyed

Extend the test: seal 100 messages for two subjects, destroy one key, and count which messages still decrypt. Expected: exactly the other subject's 50.

6. Laravel: inspect what is encrypted ​

bash
# expected, not run: QUEUE_CONNECTION=redis, a job implementing ShouldBeEncrypted
php artisan tinker --execute="dispatch(new App\Jobs\SendStatementEmail(42, '2026-10'));"
redis-cli --tls --cacert ca.pem --user laravel-queue --pass '...' LRANGE queues:default 0 0
# expected: JSON with readable uuid and displayName "App\\Jobs\\SendStatementEmail"; data.command is an encrypted string

Common misconceptions ​

BeliefReality
TLS hides messages from the brokerTLS ends at the broker; operators and disks see plaintext
InsecureSkipVerify is fine inside the VPCIt accepts any certificate, including an attacker's
SASL means encryptedSASL_PLAINTEXT and AMQP 5672 send credentials without TLS
Kafka with SASL is access-controlledWithout an authorizer every authenticated principal has full access
allow.everyone.if.no.acl.found=true is harmlessEvery resource without ACLs is open to all principals
ssl.client.auth=requested enforces mTLSClients without certificates still connect
RabbitMQ guest is a security holeIt is loopback-only by default; loopback_users = none makes it one
Redis key patterns limit everythingFLUSHALL, FLUSHDB, SWAPDB ignore key patterns
requirepass creates a userIt sets the password of the default user
vhosts isolate resourcesThey isolate names and permissions, not memory, disk or CPU
Disk encryption protects payloads from operatorsOnly message-level encryption does
A random nonce with one long-lived AES-GCM key is always safeNonce collisions become a risk at high volume; use fresh data keys
HMAC gives non-repudiationEvery verifier holds the key and can forge
Retention deletes personal dataCopies in DLQs, mirrors, lakes and backups remain
ShouldBeEncrypted encrypts the whole payloadOnly the serialized command; metadata stays readable

Cheat sheet ​

TopicRemember
Threat modelActors, assets, boundaries; eavesdrop, impersonate, over-privilege, replay, leak
TLS portsAMQPS 5671, management 15671, Kafka SSL/SASL_SSL listener, Redis tls-port + rediss://
VerificationChain to CA + hostname/SAN; never skip
mTLSfail_if_no_peer_cert = true, ssl.client.auth=required, Redis tls-auth-clients yes
Kafka authSCRAM-SHA-512 or mTLS; PLAIN only with SASL_SSL; OAUTHBEARER needs a real validator
RabbitMQ authPer-service users or EXTERNAL; remove ANONYMOUS and guest
Redis authACL users, AUTH username password; requirepass is legacy
RabbitMQ authzvhost + configure/write/read regex + topic permissions
Kafka authzStandardAuthorizer, literal/prefixed ACLs, super.users, default deny
Redis authz-@all then add commands; ~ key patterns; resetchannels
SecretsMounted files, callbacks, redaction, overlap rotation
PayloadMinimise, envelope-encrypt with KMS, AES-GCM, fresh DEK and nonce
IntegrityHMAC/JWS over id + time + body; replay window
ErasureTombstones for keyed topics, crypto-shredding for the rest
AuditAuthorizer logs, ACL LOG, RabbitMQ refusals, shipped off-broker

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why does TLS alone not satisfy a requirement that broker operators must not read card-holder names? Must-know ​

Answer

Answer: TLS protects the connection and ends at the broker. Messages are stored and served in plaintext to anyone with broker or disk access. Only producer-side payload encryption with keys the operators cannot use protects them.

2 — A Kafka cluster has SCRAM authentication but no authorizer.class.name. What can a consumer credential do? Important ​

Answer

Answer: Everything: Kafka's security model states that without an authorizer all authenticated principals have full access, including writing and deleting topics.

3 — What do ssl_options.verify = verify_peer and fail_if_no_peer_cert = true each contribute in RabbitMQ? Important ​

Answer

Answer: verify_peer makes the node verify a certificate the client presents; fail_if_no_peer_cert rejects clients that present none. Without the second, clients without certificates are still accepted.

4 — Why is SCRAM preferable to SASL/PLAIN even over TLS? Important ​

Answer

Answer: SCRAM never sends the password; the server stores salted, iterated keys and both sides prove knowledge. A compromised TLS termination point or a broker log cannot capture a reusable password.

5 — Write the RabbitMQ permissions for a consumer that may only consume from orders.billing. Good to know ​

Answer

Answer: configure '^$', write '^$', read '^orders.billing$' in the correct vhost.

6 — Why can a Redis user with ~tenant1:* +@all still destroy another tenant's data? Important ​

Answer

Answer: Whole-keyspace commands such as FLUSHALL, FLUSHDB and SWAPDB take no key arguments, so key patterns do not restrict them. Remove them explicitly or start from -@all.

7 — Why does the envelope helper generate a new data key for every message? Good to know ​

Answer

Answer: GCM forbids nonce reuse under one key. With a fresh key per message, a random 96-bit nonce never meets the same key twice, and compromising one data key exposes one message.

8 — Why must a verifier check the HMAC before recording the message id in its replay cache? Important ​

Answer

Answer: Otherwise an attacker can send unsigned messages with future ids and block the genuine messages as replays.

9 — How do you honour an erasure request for data in a non-compacted Kafka topic with 90-day retention? Good to know ​

Answer

Answer: You cannot delete individual records there. If the data was encrypted under a per-subject key, destroy that key (crypto-shredding); otherwise wait for retention or rewrite the topic, and also handle DLQs, mirrors and backups.

10 — What does Laravel's ShouldBeEncrypted leave readable? Important ​

Answer

Answer: The job envelope: uuid, displayName, commandName, maxTries, backoff, timeout and similar fields. Only data.command, the serialized job, is encrypted with APP_KEY.

11 — What is wrong with kafka-acls --allow-principal User:'*' --operation All --topic '*' as a quick fix? Must-know ​

Answer

Answer: It grants every authenticated principal every operation on every topic, defeating least privilege and auditability; it is equivalent to having no authorization for topics.

Glossary ​

TermMeaning
Threat modelList of actors, assets, trust boundaries and threats with controls
Trust boundaryPoint where data or control passes between parties with different privileges
Replay attackResending a captured valid message to repeat its effect
Poison messageInput crafted or malformed so that consumers fail repeatedly
TLSTransport Layer Security; encryption and server authentication in transit (RFC 8446 for 1.3)
mTLSMutual TLS; the client also authenticates with a certificate
SNIServer Name Indication; host name sent in the TLS handshake
Certificate verificationChecking the chain to a trusted CA and the host name against the SAN
AMQPSAMQP over TLS, port 5671 for RabbitMQ
security.protocolKafka client setting: PLAINTEXT, SSL, SASL_PLAINTEXT, SASL_SSL
SASL_SSLKafka listener/protocol with SASL authentication inside TLS
ssl.endpoint.identification.algorithmKafka/librdkafka host name verification; https by default
ssl.client.authKafka broker setting for client certificates: none, requested, required
redissURL scheme for Redis over TLS
SASLSimple Authentication and Security Layer; framework of mechanisms
SASL/PLAINUsername and password sent in clear inside the channel
SCRAM-SHA-256 / SCRAM-SHA-512Salted challenge-response authentication (RFC 5802, RFC 7677)
GSSAPISASL mechanism for Kerberos
OAUTHBEARERSASL mechanism carrying an OAuth 2.0 bearer token
Delegation tokenKafka-issued short-lived credential used through SCRAM
EXTERNALRabbitMQ mechanism taking identity from the TLS certificate
ANONYMOUSRabbitMQ mechanism that logs in as anonymous_login_user
OAuth 2.0 pluginRabbitMQ plugin validating JWTs and mapping scopes to permissions
update-secretAMQP 0-9-1 method to replace an expiring token on an open connection
JWKSJSON Web Key Set; identity provider's public signing keys
AUTHRedis command to authenticate a connection
requirepassLegacy Redis password for the default user
ACLAccess control list; Redis users/rules or Kafka authorization entries
ACL LOGRedis command listing recent authentication and permission denials
aclfileRedis file holding ACL users; persisted with ACL SAVE
Protected modeRedis mode answering only loopback when no password and all interfaces bound
vhostRabbitMQ virtual host; namespace for resources and permissions
configure/write/read permissionsRabbitMQ's three per-vhost regexes
Topic permissionsRabbitMQ routing-key regex for topic exchanges
loopback_users / guest loopbackRabbitMQ list of users allowed only from localhost; contains guest
Management pluginRabbitMQ UI and HTTP API on 15672/15671
User tagsRabbitMQ management roles: management, policymaker, monitoring, administrator
kafka-aclsKafka CLI for adding, removing and listing ACLs
Resource patternKafka ACL target: type, name and LITERAL or PREFIXED match
Prefixed ACLKafka ACL applying to every resource whose name starts with a prefix
allow.everyone.if.no.acl.foundKafka setting opening resources that have no ACLs
super.usersKafka principals that bypass ACL checks
StandardAuthorizerKafka's built-in KRaft authorizer
Least privilegeGranting only the operations and resources a role needs
Secrets managementStoring, delivering, rotating and auditing credentials
Envelope encryptionEncrypting data with a data key that is itself encrypted by a KEK
KMSKey management service holding KEKs and auditing their use
Data key (DEK)Random symmetric key that encrypts one payload
KEKKey-encryption key that wraps data keys
AES-GCMAES in Galois/Counter Mode; authenticated encryption (NIST SP 800-38D)
NonceNumber used once; must never repeat under the same GCM key
AADAdditional authenticated data; bound to the ciphertext but not encrypted
HMACKeyed hash for message authentication (RFC 2104)
JWSJSON Web Signature; MAC- or signature-protected content (RFC 7515)
ShouldBeEncryptedLaravel interface that encrypts a queued job's command
CryptLaravel facade for AES-256-CBC + MAC encryption with APP_KEY
APP_PREVIOUS_KEYSLaravel list of old keys accepted for decryption during rotation
PIIPersonally identifiable information
RetentionHow long the broker keeps messages
Right to erasureLegal obligation to delete personal data on request (GDPR Art. 17)
Crypto-shreddingMaking data unreadable by destroying its encryption key
TombstoneKafka record with a key and null value that marks the key for deletion
CompactionKafka cleanup keeping only the latest value per key
Audit logDurable record of authentication, authorization and admin events
Multi-tenancySeveral tenants sharing one broker with isolation
QuotasLimits on bandwidth, request rate, connections or queues per principal or vhost

References ​

Built by Morteza Negahi