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 for | Go to |
|---|---|
| What can go wrong around a broker | Threat model |
TLS ports, security.protocol, rediss://, hostname checks | Transport security |
| Client certificates as identity | Mutual TLS |
| PLAIN, SCRAM, GSSAPI, OAUTHBEARER, delegation tokens, Redis AUTH | Authentication |
vhosts and regex permissions, kafka-acls, Redis ACL rules | Authorization |
Passwords in URLs, logs, .env and vaults | Secrets management |
KMS, data keys, AES-GCM, ShouldBeEncrypted | Payload encryption |
| HMAC, JWS, replay windows | Integrity and replay |
| GDPR erasure in a Kafka log | PII, retention and erasure |
| Tenants sharing one cluster | Multi-tenant isolation |
| Management UI exposure, audit trails | Audit and management plane |
| A hardening checklist per broker | Solutions |
| Go and Laravel code | Go, Laravel, Broker differences |
Everything in one minute
| Threat | Plain words | Control | RabbitMQ | Kafka | Redis Streams |
|---|---|---|---|---|---|
| Eavesdropping | Someone on the network reads messages | TLS with chain and hostname verification | AMQPS on 5671 | security.protocol=SSL or SASL_SSL | tls-port, rediss:// |
| Impersonation | A client pretends to be a service | Authentication | PLAIN over TLS, EXTERNAL (x509), OAuth 2.0 plugin | SCRAM-SHA-512, mTLS, OAUTHBEARER, GSSAPI | ACL users with AUTH username password, client certificates |
| Over-privilege | A valid identity does too much | Least-privilege authorization | vhost + configure/write/read regex, topic permissions | ACLs on Topic/Group/Cluster/TransactionalId | ACL rules on commands, keys, channels |
| Payload leakage | Broker disk, backup, DLQ or log reveals data | Data minimisation, envelope encryption | Not encrypted at rest by the broker | “does not encrypt data at rest” | No per-entry encryption |
| Tampering and replay | A message is altered or sent twice on purpose | HMAC/JWS signature, message id, freshness window | Application headers | Record headers | Stream fields |
| Erasure obligation | Personal data must be deletable | Retention limits, tombstones, crypto-shredding | TTL, queue deletion | retention.ms, compaction tombstones | XTRIM, XDEL, key deletion |
| Exposed admin plane | Anyone can reach the UI or Admin API | Private network, TLS, admin identities, audit | Management on 15672/15671, user tags | Admin API ACLs on Cluster, JMX locked down | -@admin -@dangerous for apps |
| Default out of the box | RabbitMQ | Kafka | Redis |
|---|---|---|---|
| Transport | Plain AMQP on 5672; TLS listener only when configured | PLAINTEXT on every listener | Plain TCP on 6379; TLS only if built with BUILD_TLS=yes and configured |
| Identity | guest/guest, limited to loopback by loopback_users; ANONYMOUS mechanism enabled | None | default user with nopass |
| Authorization | Per-vhost permissions; new users have none | No authorizer: every principal may do everything | default user has ~* &* +@all |
| Safety net | Remote guest login refused | None | Protected 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 posture | Stronger posture |
|---|---|
| Plain TCP inside “trusted” networks | TLS everywhere, including inter-broker and replication links |
| One shared admin account | One identity per service and per human, least privilege |
| Credentials in URLs, YAML and logs | Secrets mounted at runtime, redacted logs, rotation |
| Payload in clear text, protected only by the broker | Minimised payload, envelope encryption for sensitive fields |
| “Kafka keeps everything forever” | Retention per topic, tombstones, crypto-shredding plan |
| Faster to set up, fewer moving parts | More 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.
| STRIDE category | Messaging example | Primary control |
|---|---|---|
| Spoofing | Fake producer publishes RefundIssued | Authentication, mTLS |
| Tampering | Proxy changes amount in flight or a DLQ operator edits a body | TLS in transit, HMAC/JWS end to end |
| Repudiation | Nobody can tell who published a destructive command | Per-service identities, audit log |
| Information disclosure | Backup of Kafka log segments sold online | Encryption at rest, payload encryption, minimisation |
| Denial of service | Tenant floods the cluster or creates 10,000 queues | Quotas, vhost limits, connection limits |
| Elevation of privilege | Consumer credential can also delete topics | Least-privilege ACLs, separate admin identity |
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.
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 itReal 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).
| Asset | Who legitimately needs it | Typical leak path |
|---|---|---|
| Message bodies | Producer, owning consumers | Wildcard read ACL, DLQ copies, logs, backups |
| Credentials | One service each | URL in logs, Git, CI variables printed in jobs |
| Topology (queues, topics, ACLs) | Platform team | Management UI, Admin API, Terraform state |
| Offsets / consumer groups | Consumer | A foreign group id resets or steals offsets |
| Metrics and traces | Operators | Payload 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.
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 channelReal 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.
| Item | RabbitMQ | Kafka | Redis |
|---|---|---|---|
| TLS client port | 5671 (AMQP), 5551 (streams), 15671 (HTTPS management) | Listener named SSL:// or SASL_SSL://, often 9093 | tls-port 6379 with port 0 |
| Client switch | amqps:// URL | security.protocol=SSL or SASL_SSL | rediss:// URL or TLSConfig |
| Hostname verification | Client 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 floor | ssl_options.versions.1 = tlsv1.3 (and .2 = tlsv1.2 if needed) | ssl.enabled.protocols default TLSv1.2,TLSv1.3 | tls-protocols in redis.conf |
| Internal links | Inter-node Erlang distribution on 25672 needs separate TLS setup | security.inter.broker.protocol, controller listener | tls-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.
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 exchangedReal 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.
| Concern | RabbitMQ | Kafka | Redis |
|---|---|---|---|
| Require certificate | fail_if_no_peer_cert = true | ssl.client.auth=required | Default when TLS on; tls-auth-clients yes |
| Certificate becomes user | ssl_cert_login_from (DN, CN, SAN) + EXTERNAL | ssl.principal.mapping.rules or custom KafkaPrincipalBuilder | Certificate proves possession; the connection still uses an ACL user (default unless AUTH) |
| Chain depth | ssl_options.depth (default 1) | JVM truststore | OpenSSL 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).
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 tooReal 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.
| Mechanism | Where | Secret on the wire | Good for | Watch out |
|---|---|---|---|---|
| SASL/PLAIN | RabbitMQ default, Kafka | Password (inside TLS) | Simple setups, external password backends | Never over SASL_PLAINTEXT or AMQP 5672 |
| SCRAM-SHA-256/512 | Kafka (credentials in KRaft metadata) | Proof only | Most self-managed Kafka | Default 4096 iterations; still use TLS |
| GSSAPI | Kafka | Kerberos ticket | Existing Kerberos estates | KDC availability, clock skew |
| OAUTHBEARER | Kafka; RabbitMQ OAuth 2.0 plugin | Short-lived JWT | Central identity provider, scopes | Kafka's default unsecured JWT is for testing only |
| Delegation token | Kafka | Token HMAC via SCRAM | Distributed frameworks | Default renew every 24 h, max 7 days |
| EXTERNAL | RabbitMQ with rabbitmq_auth_mechanism_ssl | None (certificate) | Per-workload PKI | Map subjects carefully |
| ANONYMOUS | RabbitMQ (enabled by default) | None | Development only | Acts as anonymous_login_user (guest); remove in production |
| AUTH / ACL users | Redis 6+ | Password (needs TLS) | Named users per role | requirepass 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 (&).
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).
| Role | RabbitMQ (configure / write / read) | Kafka ACLs | Redis 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 monitoring | DESCRIBE, DESCRIBE_CONFIGS | +info +ping without key access |
| Admin (human, break-glass) | administrator tag on a separate user | super.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.
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 rotatedReal 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).
| Practice | Do | Avoid |
|---|---|---|
| Storage | Vault, AWS Secrets Manager, GCP Secret Manager, Kubernetes secrets with encryption | Git, images, wiki pages |
| Delivery | File mounted per pod, read at connect time | URL with userinfo, command-line flags (ps shows them) |
| Logging | Redacted values, connection names, user names | Full URLs, configuration dumps |
| Rotation | Overlap two credentials; per-connection credential callbacks | Restart-the-world rotations |
| Laravel | env() only in config files, config:cache, env:encrypt for checked-in files | env() 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.
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 failsReal 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.
| Option | Protects against | Does not protect against | Example |
|---|---|---|---|
| TLS only | Network eavesdropping | Broker operators, disk theft, backups, DLQ readers | AMQPS, SASL_SSL |
| Disk/volume encryption | Stolen disks, misdirected snapshots | Anyone with broker login | LUKS, EBS encryption |
| Whole-payload envelope encryption | Broker operators, backups, wrong consumers | Metadata in headers, traffic analysis | Go envelope package |
| Field-level encryption | Same, for chosen fields; routing still works | Fields left in clear | Laravel EnvelopeCipher on address |
Laravel ShouldBeEncrypted | Readers of the queue store | Anyone holding APP_KEY; envelope fields | Encrypted 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.
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 5Real 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.
| Need | Choose | Note |
|---|---|---|
| One producer, few trusted consumers | HMAC-SHA256 with key id | Every verifier can forge |
| Many consumers, non-repudiation | JWS with ES256/EdDSA | Producer keeps private key |
| Confidentiality and integrity | AES-GCM envelope (AEAD) | Integrity for holders of the data key |
| Replay protection | Message id + timestamp + replay cache | Same 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.
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 everywhereReal 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.
| Technique | How | Advantage | Limitation |
|---|---|---|---|
| Data minimisation | Send ids, load PII at the consumer | Nothing to erase in the broker | Consumer needs a lookup |
| Short retention | retention.ms, queue TTL, XTRIM MINID | Simple, automatic | Replays lose history too |
| Compaction + tombstone | Null value for the subject's key | Native Kafka erasure for keyed topics | Only for topics keyed by subject; timing depends on the log cleaner |
| Crypto-shredding | Per-subject key in KMS, delete on request | Covers every copy, including backups | Key management cost; metadata stays |
| Pseudonymisation | Replace identity with a token, mapping elsewhere | Analytics stay useful | Mapping 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).
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| Isolation | RabbitMQ | Kafka | Redis |
|---|---|---|---|
| Namespace | vhost per tenant or environment | Prefix (acme.) + prefixed ACLs | Key prefix + ~acme:* |
| Limits | rabbitmqctl set_vhost_limits (max-connections, max-queues) | Client quotas, connection limits | Separate instance or maxmemory |
| Hard isolation | Separate cluster | Separate cluster | Separate 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).
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| Exposure | RabbitMQ | Kafka | Redis |
|---|---|---|---|
| Admin endpoint | 15672/15671, rabbitmqadmin, CLI on 25672/35672-35682 | Admin API on broker listeners, controller listener, JMX | Same port as data; @admin commands |
| Bind privately | management.tcp.ip, firewall | Separate internal listener; never expose controller listener | bind, protected mode, firewall |
| Audit | Logs, event exchange | kafka.authorizer.logger, kafka.request.logger | ACL 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
| Port | Broker | Purpose | Expose to |
|---|---|---|---|
| 5672 / 5671 | RabbitMQ | AMQP 0-9-1 and 1.0 without / with TLS | 5671 only, to application subnets |
| 5552 / 5551 | RabbitMQ | Stream protocol without / with TLS | 5551 only |
| 15672 / 15671 | RabbitMQ | Management UI and HTTP API without / with TLS | Operator network, via VPN or bastion |
| 25672, 4369, 35672-35682 | RabbitMQ | Inter-node (Erlang distribution), epmd, CLI tools | Cluster nodes only |
| 9092 / 9093 (convention) | Kafka | Client listeners (PLAINTEXT / SSL or SASL_SSL) | TLS listener only |
| Controller listener | Kafka | KRaft controller quorum | Never client networks |
| 6379 | Redis | Data port (port or tls-port) | Application subnets; port 0 when TLS-only |
| 16379 (port + 10000) | Redis Cluster | Cluster bus (tls-cluster yes) | Cluster nodes only |
Kafka listener protocols and client properties Must-know
security.protocol | Authentication | Encryption | Use |
|---|---|---|---|
| PLAINTEXT | None | None | Closed test environments only |
| SSL | Optional mTLS | TLS | Certificate-based identity |
| SASL_PLAINTEXT | SASL | None | Never with PLAIN; avoid in production |
| SASL_SSL | SASL (+ optional mTLS) | TLS | Default choice for services |
# 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
| Operation | configure | write | read |
|---|---|---|---|
queue.declare (non-passive) | queue | ||
queue.bind | queue | exchange | |
basic.publish | exchange | ||
basic.consume, basic.get, queue.purge | queue | ||
exchange.declare with alternate exchange | exchange | exchange (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.
# 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 guestRedis 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).
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-consumerError messages you will meet Must-know
| Signal | Meaning | First check |
|---|---|---|
PLAIN login refused: user 'guest' can only connect via localhost | RabbitMQ loopback_users default | Create a real user; do not set loopback_users = none |
access to vhost '/' refused for user 'user2' | No permissions in that vhost | rabbitmqctl set_permissions -p |
AMQP 403 ACCESS_REFUSED | Permission regex did not match | Which of configure/write/read the operation needs |
amqp091 ErrSASL / ErrCredentials | No shared mechanism / bad credentials | EXTERNAL plugin enabled? correct user? |
Kafka TOPIC_AUTHORIZATION_FAILED (29) | No ACL for the topic operation | kafka-acls --list --topic t --resource-pattern-type match |
Kafka GROUP_AUTHORIZATION_FAILED (30) | Consumer lacks READ on its group | ACL on --group |
Kafka CLUSTER_AUTHORIZATION_FAILED (31) | Admin or idempotent-write operation denied | Cluster-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' command | ACL command rule | ACL GETUSER, ACL LOG |
Redis WRONGPASS | Bad user/password or user disabled | Secret rotation, user on |
Go tls: failed to verify certificate: x509: certificate is valid for broker.internal, not attacker.example | Hostname verification worked | DNS, SAN list, ServerName |
Go x509: certificate signed by unknown authority (Linux; macOS reports “certificate is not trusted”) | CA bundle missing | RootCAs, mounted CA file |
Solving the classic problems
Hardening a fresh broker
| Step | RabbitMQ | Kafka | Redis |
|---|---|---|---|
| Remove defaults | Delete guest, remove ANONYMOUS from auth_mechanisms | Configure an authorizer; keep allow.everyone.if.no.acl.found=false | Disable default user or give it no permissions |
| Encrypt | TLS listener 5671 only, management on 15671 | SASL_SSL listeners, TLS inter-broker | port 0, tls-port 6379, tls-replication yes |
| Identities | One user (or certificate) per service | SCRAM user or certificate per service | ACL user per role |
| Permissions | Per-vhost regexes, topic permissions | Literal or prefixed ACLs | Command + key + channel rules |
| Limits | vhost limits | Quotas | maxmemory, separate instances |
| Admin plane | Bind management privately, TLS | Private controller listener, JMX auth or localhost | -@admin -@dangerous for apps |
| Audit | Ship logs; alert on refusals | kafka.authorizer.logger at INFO | ACL LOG scraping |
Rotating credentials without downtime
| Problem | Solution | Advantage | Limitation |
|---|---|---|---|
| SCRAM password rotation | Add new credential, update secret file, clients reconnect via callback, remove old | No restart | Old credential valid during overlap |
| RabbitMQ password rotation | rabbitmqctl change_password, reconnect clients | Simple | Open connections keep working until reconnect |
| OAuth token expiry | update-secret on AMQP 0-9-1; Kafka OAUTHBEARER refresh | Short-lived credentials | Needs IdP availability |
| Certificate rotation | Overlapping validity, reload (Kafka dynamic broker config) | No shared secret | PKI automation required |
| Redis ACL rotation | Add second password with >new, rotate, remove with <old | Two passwords per user supported | Persist 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.
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
| Problem | Solution | Advantage | Limitation |
|---|---|---|---|
| Payload logged on failure | Log ids, reason codes, sizes | Logs need no special retention | Debugging needs a secured lookup |
| Span attributes contain bodies | Allow-list attributes in OTel | Traces safe to share | Less detail |
| DLQ keeps PII for months | Encrypt payloads; DLQ retention aligned with policy | Recovery still possible | Replay needs KMS access |
failed_jobs stores serialized job | ShouldBeEncrypted, queue:prune-failed | Laravel-native | APP_KEY holders can read |
Choosing a protection level
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Internal events, no personal data | TLS + per-service identity + least privilege | Prefixed ACLs | Baseline for any production broker |
| Payment or health data in events | Baseline + envelope encryption of sensitive fields | Per-tenant KEK, short retention | Broker operators and backups must not read it |
| Commands that move money | Baseline + signature + replay window | Idempotency key in the inbox | A replay must not repeat the effect |
| Event-sourced aggregates with personal data | Crypto-shredding by subject | Keep PII in a separate, deletable store | Immutable history plus erasure |
| Multi-tenant SaaS on one cluster | vhost/prefix per tenant + quotas | Per-tenant KEK | Isolation of data and capacity |
| Kafka Connect / stream processors | Dedicated principals, delegation tokens | ACLs per connector | Framework processes fan out widely |
| Laravel app on Redis queue | ACL user, TLS, ShouldBeEncrypted | Pass ids, not models with PII | Queue store holds serialized jobs |
| Development laptop | Local-only binding | Still no wildcard admin in shared dev clusters | Habits 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.
// 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.
// 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.
// 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.
// 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:
// 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
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
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
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
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 feature | Security role | Caveat |
|---|---|---|
ShouldBeEncrypted | Encrypts serialized job command | Envelope fields stay clear; APP_KEY decrypts everything |
Crypt::encryptString / decryptString | Authenticated encryption of values | One app-wide key |
Encrypter with aes-256-gcm | Per-message data keys | You manage the KEK through a KMS |
APP_PREVIOUS_KEYS | Graceful key rotation | Old keys stay usable until removed |
env:encrypt / env:decrypt | Encrypted .env in the repository | The decryption key becomes the secret |
config/database.php redis scheme => tls, username | TLS and ACL user | CA trust is a PHP/OpenSSL setting |
queue:prune-failed | Limit retention of failed payloads | Run 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.
// 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
// 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.
// 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
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();
}
}# 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 matchRedis 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.
// 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
// 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
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.usersshould be treated like a root password. - RabbitMQ documents that
guestcan only connect from localhost by default and that ANONYMOUS acts asanonymous_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
CONFIGlets a client write RDB files to arbitrary paths; hardening means denying@adminand@dangerousto application users. - Laravel's queue source shows
ShouldBeEncryptedcovers the job command only; payload metadata such asdisplayNameis 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
| Load | Security design | Example |
|---|---|---|
| 1× | TLS, per-service users, hand-written permissions, ShouldBeEncrypted | One Laravel app and two Go workers |
| 10× | Permissions as code, secrets manager, credential callbacks, quotas, audit shipping | Ten teams on one Kafka cluster with prefixed ACLs |
| 100× | Workload PKI (mTLS), OAuth with scopes, per-tenant KEKs, data-key caching, automated access reviews | SaaS 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
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 error2. RabbitMQ: guest, permissions and refusals
# 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
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 matchExpected, not run. Set log4j.logger.kafka.authorizer.logger=INFO and observe one denial line for step 2.
4. Redis: ACL rules and ACL LOG
# 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
go test -run TestCryptoShredding -v ./envelope
# expected: PASS; Open returns ErrUnknownKey after the subject key is destroyedExtend 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
# 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 stringCommon misconceptions
| Belief | Reality |
|---|---|
| TLS hides messages from the broker | TLS ends at the broker; operators and disks see plaintext |
InsecureSkipVerify is fine inside the VPC | It accepts any certificate, including an attacker's |
| SASL means encrypted | SASL_PLAINTEXT and AMQP 5672 send credentials without TLS |
| Kafka with SASL is access-controlled | Without an authorizer every authenticated principal has full access |
allow.everyone.if.no.acl.found=true is harmless | Every resource without ACLs is open to all principals |
ssl.client.auth=requested enforces mTLS | Clients without certificates still connect |
RabbitMQ guest is a security hole | It is loopback-only by default; loopback_users = none makes it one |
| Redis key patterns limit everything | FLUSHALL, FLUSHDB, SWAPDB ignore key patterns |
requirepass creates a user | It sets the password of the default user |
| vhosts isolate resources | They isolate names and permissions, not memory, disk or CPU |
| Disk encryption protects payloads from operators | Only message-level encryption does |
| A random nonce with one long-lived AES-GCM key is always safe | Nonce collisions become a risk at high volume; use fresh data keys |
| HMAC gives non-repudiation | Every verifier holds the key and can forge |
| Retention deletes personal data | Copies in DLQs, mirrors, lakes and backups remain |
ShouldBeEncrypted encrypts the whole payload | Only the serialized command; metadata stays readable |
Cheat sheet
| Topic | Remember |
|---|---|
| Threat model | Actors, assets, boundaries; eavesdrop, impersonate, over-privilege, replay, leak |
| TLS ports | AMQPS 5671, management 15671, Kafka SSL/SASL_SSL listener, Redis tls-port + rediss:// |
| Verification | Chain to CA + hostname/SAN; never skip |
| mTLS | fail_if_no_peer_cert = true, ssl.client.auth=required, Redis tls-auth-clients yes |
| Kafka auth | SCRAM-SHA-512 or mTLS; PLAIN only with SASL_SSL; OAUTHBEARER needs a real validator |
| RabbitMQ auth | Per-service users or EXTERNAL; remove ANONYMOUS and guest |
| Redis auth | ACL users, AUTH username password; requirepass is legacy |
| RabbitMQ authz | vhost + configure/write/read regex + topic permissions |
| Kafka authz | StandardAuthorizer, literal/prefixed ACLs, super.users, default deny |
| Redis authz | -@all then add commands; ~ key patterns; resetchannels |
| Secrets | Mounted files, callbacks, redaction, overlap rotation |
| Payload | Minimise, envelope-encrypt with KMS, AES-GCM, fresh DEK and nonce |
| Integrity | HMAC/JWS over id + time + body; replay window |
| Erasure | Tombstones for keyed topics, crypto-shredding for the rest |
| Audit | Authorizer logs, ACL LOG, RabbitMQ refusals, shipped off-broker |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| Threat model | List of actors, assets, trust boundaries and threats with controls |
| Trust boundary | Point where data or control passes between parties with different privileges |
| Replay attack | Resending a captured valid message to repeat its effect |
| Poison message | Input crafted or malformed so that consumers fail repeatedly |
| TLS | Transport Layer Security; encryption and server authentication in transit (RFC 8446 for 1.3) |
| mTLS | Mutual TLS; the client also authenticates with a certificate |
| SNI | Server Name Indication; host name sent in the TLS handshake |
| Certificate verification | Checking the chain to a trusted CA and the host name against the SAN |
| AMQPS | AMQP over TLS, port 5671 for RabbitMQ |
security.protocol | Kafka client setting: PLAINTEXT, SSL, SASL_PLAINTEXT, SASL_SSL |
| SASL_SSL | Kafka listener/protocol with SASL authentication inside TLS |
ssl.endpoint.identification.algorithm | Kafka/librdkafka host name verification; https by default |
ssl.client.auth | Kafka broker setting for client certificates: none, requested, required |
rediss | URL scheme for Redis over TLS |
| SASL | Simple Authentication and Security Layer; framework of mechanisms |
| SASL/PLAIN | Username and password sent in clear inside the channel |
| SCRAM-SHA-256 / SCRAM-SHA-512 | Salted challenge-response authentication (RFC 5802, RFC 7677) |
| GSSAPI | SASL mechanism for Kerberos |
| OAUTHBEARER | SASL mechanism carrying an OAuth 2.0 bearer token |
| Delegation token | Kafka-issued short-lived credential used through SCRAM |
| EXTERNAL | RabbitMQ mechanism taking identity from the TLS certificate |
| ANONYMOUS | RabbitMQ mechanism that logs in as anonymous_login_user |
| OAuth 2.0 plugin | RabbitMQ plugin validating JWTs and mapping scopes to permissions |
update-secret | AMQP 0-9-1 method to replace an expiring token on an open connection |
| JWKS | JSON Web Key Set; identity provider's public signing keys |
| AUTH | Redis command to authenticate a connection |
requirepass | Legacy Redis password for the default user |
| ACL | Access control list; Redis users/rules or Kafka authorization entries |
| ACL LOG | Redis command listing recent authentication and permission denials |
aclfile | Redis file holding ACL users; persisted with ACL SAVE |
| Protected mode | Redis mode answering only loopback when no password and all interfaces bound |
| vhost | RabbitMQ virtual host; namespace for resources and permissions |
| configure/write/read permissions | RabbitMQ's three per-vhost regexes |
| Topic permissions | RabbitMQ routing-key regex for topic exchanges |
loopback_users / guest loopback | RabbitMQ list of users allowed only from localhost; contains guest |
| Management plugin | RabbitMQ UI and HTTP API on 15672/15671 |
| User tags | RabbitMQ management roles: management, policymaker, monitoring, administrator |
kafka-acls | Kafka CLI for adding, removing and listing ACLs |
| Resource pattern | Kafka ACL target: type, name and LITERAL or PREFIXED match |
| Prefixed ACL | Kafka ACL applying to every resource whose name starts with a prefix |
allow.everyone.if.no.acl.found | Kafka setting opening resources that have no ACLs |
super.users | Kafka principals that bypass ACL checks |
| StandardAuthorizer | Kafka's built-in KRaft authorizer |
| Least privilege | Granting only the operations and resources a role needs |
| Secrets management | Storing, delivering, rotating and auditing credentials |
| Envelope encryption | Encrypting data with a data key that is itself encrypted by a KEK |
| KMS | Key management service holding KEKs and auditing their use |
| Data key (DEK) | Random symmetric key that encrypts one payload |
| KEK | Key-encryption key that wraps data keys |
| AES-GCM | AES in Galois/Counter Mode; authenticated encryption (NIST SP 800-38D) |
| Nonce | Number used once; must never repeat under the same GCM key |
| AAD | Additional authenticated data; bound to the ciphertext but not encrypted |
| HMAC | Keyed hash for message authentication (RFC 2104) |
| JWS | JSON Web Signature; MAC- or signature-protected content (RFC 7515) |
| ShouldBeEncrypted | Laravel interface that encrypts a queued job's command |
| Crypt | Laravel facade for AES-256-CBC + MAC encryption with APP_KEY |
APP_PREVIOUS_KEYS | Laravel list of old keys accepted for decryption during rotation |
| PII | Personally identifiable information |
| Retention | How long the broker keeps messages |
| Right to erasure | Legal obligation to delete personal data on request (GDPR Art. 17) |
| Crypto-shredding | Making data unreadable by destroying its encryption key |
| Tombstone | Kafka record with a key and null value that marks the key for deletion |
| Compaction | Kafka cleanup keeping only the latest value per key |
| Audit log | Durable record of authentication, authorization and admin events |
| Multi-tenancy | Several tenants sharing one broker with isolation |
| Quotas | Limits on bandwidth, request rate, connections or queues per principal or vhost |
References
- Redis: Security, ACL, TLS, ACL LOG.
- RabbitMQ: TLS support, Access control, Virtual hosts, OAuth 2.0, Management plugin, Networking and ports.
- Apache Kafka 4.4: Security overview, Security model, SSL, SASL, Authorization and ACLs, Multi-tenancy, Producer configs.
- librdkafka: Configuration properties.
- Laravel 13: Queues (encrypted jobs), Encryption, Redis, Configuration (env encryption); framework source Queue.php, Encrypter.php.
- Packages: laravel-queue-rabbitmq README, Laravel Kafka SASL, Laravel Kafka producers.
- Go clients: amqp091-go, franz-go kgo, franz-go SCRAM, go-redis.
- Standards: NIST SP 800-38D (GCM), RFC 5802 (SCRAM), RFC 7677 (SCRAM-SHA-256), RFC 8446 (TLS 1.3), RFC 2104 (HMAC), RFC 7515 (JWS).
- OWASP: Secrets Management, Transport Layer Security, Cryptographic Storage.
- AWS: KMS cryptography essentials (envelope encryption).