From 494a194b3346bf6d9021439bb2c287c8af66c3e5 Mon Sep 17 00:00:00 2001 From: "bojan.malinic" Date: Mon, 23 Nov 2026 12:51:55 +0100 Subject: [PATCH 1/2] Support SSL, mTLS and SASL for Kafka status events The Kafka status-event producer always connected with PLAINTEXT and exposed no way to change it. Producer settings can now be passed through under conductor.message-publisher.kafka.producer.*, which enables SSL, mTLS, SASL_SSL and SASL_PLAINTEXT with PKCS12 or PEM files. - Settings are validated at startup: invalid values, unreadable keystore/truststore files and inline PEM certificates fail startup; unknown keys are logged as a warning. Serializers can't be overridden. - The producer is per service instance and closed on shutdown. - kafka-clients stays at 3.9.1. - Container tests run each mode end to end against apache/kafka:3.9.1 with per-run keytool certificates, plus rejection cases. - Documents the modes in kafka/README.md and records the decision in adr/0001-kafka-status-producer-security.md. Co-Authored-By: Claude Opus 5.5 --- adr/0001-kafka-status-producer-security.md | 179 ++++++++++ adr/README.md | 23 ++ kafka/README.md | 119 ++++++- kafka/build.gradle | 2 + .../status/events/config/KafkaProperties.java | 15 + .../services/KafkaEventServiceImpl.java | 161 +++++++-- .../services/KafkaEventServiceImplTest.java | 328 ++++++++++++++++++ .../services/KafkaSecurityContainerTest.java | 265 ++++++++++++++ .../events/services/SecureKafkaContainer.java | 160 +++++++++ .../events/services/TestCertificates.java | 270 ++++++++++++++ 10 files changed, 1494 insertions(+), 28 deletions(-) create mode 100644 adr/0001-kafka-status-producer-security.md create mode 100644 adr/README.md create mode 100644 kafka/src/test/java/com/netflix/conductor/kafka/status/events/services/KafkaEventServiceImplTest.java create mode 100644 kafka/src/test/java/com/netflix/conductor/kafka/status/events/services/KafkaSecurityContainerTest.java create mode 100644 kafka/src/test/java/com/netflix/conductor/kafka/status/events/services/SecureKafkaContainer.java create mode 100644 kafka/src/test/java/com/netflix/conductor/kafka/status/events/services/TestCertificates.java diff --git a/adr/0001-kafka-status-producer-security.md b/adr/0001-kafka-status-producer-security.md new file mode 100644 index 0000000000..d478779ddb --- /dev/null +++ b/adr/0001-kafka-status-producer-security.md @@ -0,0 +1,179 @@ +# ADR-0001: Secure connections for the Kafka status-event producer + +- **Status:** Accepted +- **Date:** 2026-11-23 +- **Module:** `kafka` (`com.netflix.conductor.kafka.status.events`) + +## Context + +Conductor can publish task and workflow status changes to Kafka +(`conductor.message-publisher.type=kafka`). The events contain task and workflow input and +output, which can include sensitive data. + +The producer was built in `KafkaEventServiceImpl` from a fixed set of settings: +`bootstrap.servers`, `acks`, `client.id` and the serializers. `KafkaProperties` exposed only +those and the topic settings, and nothing else was passed to the Kafka client. As a result +the producer always used Kafka's default `security.protocol=PLAINTEXT`: + +- events crossed the network unencrypted; +- the broker could not authenticate Conductor; +- there was no configuration option to change either. + +Deployments need to connect to brokers that require one of: + +| Mode | Encryption | Broker authenticated | Conductor authenticated by | +|---|---|---|---| +| SSL | Yes | Yes | Nothing | +| mTLS (SSL with client certificate) | Yes | Yes | Client certificate | +| SASL_SSL | Yes | Yes | SASL (PLAIN, SCRAM, OAUTHBEARER, GSSAPI) | +| SASL_PLAINTEXT | No | No | SASL | + +Certificates come either as PKCS12 keystores (common in Java setups) or as PEM files (common +with Kubernetes secrets and cert-manager). + +The project uses `kafka-clients` 3.9.1, which already supports all four modes and PEM +keystores and truststores (KIP-651). The gap is in Conductor, not in the library. + +## Decision + +### 1. Pass Kafka producer settings through from configuration + +`KafkaProperties` gains a `producer` map bound from +`conductor.message-publisher.kafka.producer.*`. Keys are Kafka producer setting names and +are passed to the Kafka client as they are. This is the same approach the +`kafka-event-queue` module uses (`conductor.event-queues.kafka.producer.*`). + +The map is `Map` rather than `Map`. Spring Boot keeps a +dotted key such as `security.protocol` as a single key for scalar-valued maps, but splits it +into nested maps for `Object` values, which would make the setting invisible to Kafka. + +The producer settings are built in one place, `KafkaEventServiceImpl.buildProducerConfig`, in +this order: + +1. Defaults: `acks=all`, `client.id` = local host name (falling back to + `conductor-status-producer` if it cannot be resolved). +2. The user's `producer.*` settings, which may override the defaults. +3. `bootstrap.servers` from the existing `bootstrapServers` setting, when not blank. +4. The key and value serializers, which cannot be overridden because the event format + depends on `KafkaJsonSerializer`. Attempts to set them are ignored with a warning. + +With no `producer.*` settings the resulting configuration is the same as before, so existing +deployments are unaffected. + +### 2. Certificates and keys only as files + +Keystores and truststores, in PKCS12 or PEM format, are given by file path +(`ssl.keystore.location`, `ssl.truststore.location`). The inline PEM settings +`ssl.keystore.key`, `ssl.keystore.certificate.chain` and `ssl.truststore.certificates` are +refused, and Conductor fails to start with a message pointing to the `*.location` settings. +The message names the setting but never includes its value. + +### 3. Validate at startup, connect on first use + +`KafkaEventServiceImpl`'s constructor builds and validates the settings, so a bad +configuration fails Conductor's startup rather than every status event: + +- inline certificate settings are refused; +- each keystore and truststore location must exist and be readable; +- Kafka's own `ProducerConfig.configDef().parse(...)` checks types and allowed values + (for example `security.protocol`) without connecting or logging values; +- settings that are not Kafka producer settings are logged as a warning by key name only. + They are still passed through, as Kafka itself ignores unknown settings. + +The `KafkaProducer` is still created on the first event, as before. Creating it at startup +would require the bootstrap address to resolve at startup. + +### 4. One producer per service instance, closed on shutdown + +The producer moves from a `static` field to an instance field, so service instances with +different settings no longer share whichever producer was created first. Conductor creates +one service bean, so runtime behaviour is unchanged. The service implements `AutoCloseable`; +Spring calls `close()` on shutdown, which flushes and closes the producer. + +### 5. Keep kafka-clients at 3.9.1 + +No library change is needed, so the version stays as it is. + +### 6. Test against a real broker + +Besides unit tests of the settings builder, `KafkaSecurityContainerTest` runs a single-node +`apache/kafka:3.9.1` broker (matching the client version) with one listener per mode, and +checks each mode end to end through `KafkaEventServiceImpl` and `TaskStatusKafkaProducer`: + +- delivery over SSL (PKCS12 and PEM truststores), mTLS (PKCS12 and PEM keystores), SASL_SSL + (PLAIN and SCRAM-SHA-512) and SASL_PLAINTEXT; +- rejection of a client without a certificate on the mTLS listener, a wrong SASL password, + and a broker certificate the client does not trust. These show the broker really enforces + each mode, so the delivery tests cannot pass by accident. + +Certificates are generated per run with the JDK's `keytool`, so no private keys are stored in +the repository and no extra library is needed. The tests are skipped when Docker is not +available. + +## Alternatives considered + +**Dedicated, typed settings** (for example `kafka.security.mode=MTLS`, +`kafka.security.keystore-path`). Easier to discover, but each new Kafka option (another SASL +mechanism, OAuth settings, TLS protocol versions) would need code changes, and the names +would differ from Kafka's documentation. Passing settings through covers every mode with no +further code and matches `kafka-event-queue`. + +**Allowing inline PEM settings.** Kafka supports them, but they put private keys into +configuration, which is more often copied, logged or committed than a mounted secret file. +In `.properties` files every line break must also be escaped. Files work in every target +environment, so inline settings were excluded deliberately. + +**Creating the producer at startup.** This would also catch unreadable keystores, but the +Kafka client resolves the bootstrap addresses when it is created, so Conductor could not +start before Kafka's DNS name resolves (for example during a Kubernetes rollout). Checking +that store files are readable covers the most common error without that dependency. + +**Failing on unknown settings.** Stricter, but would stop Conductor from starting on a +setting from a newer Kafka version or a harmless extra key. A warning naming the key makes +typos visible without that risk. + +**Encrypting at the network level instead** (service mesh mTLS, private network). Useful in +addition, but does not help when the broker itself requires TLS or SASL, as managed Kafka +services usually do, and does not give the broker an identity for ACLs. + +**Upgrading kafka-clients.** Not needed for any of the modes, and would affect other modules +that share the version. + +## Consequences + +**Positive** + +- Status events can be encrypted, and Conductor can authenticate to the broker by + certificate or SASL credentials, so broker ACLs can apply to it. +- Any Kafka producer setting can be tuned without code changes. +- Misconfiguration (invalid values, missing files, inline certificates) is reported once at + startup with a clear message. +- Existing deployments without `producer.*` settings behave exactly as before. + +**Negative / to be aware of** + +- Certificates and credentials are read once, when the producer is created. A renewed + certificate or changed password takes effect only after Conductor restarts, which matters + with short-lived certificates. +- Passwords and `sasl.jaas.config` credentials live in configuration. They should be + supplied with `${...}` placeholders from environment variables or a secret store. +- A misspelt setting only produces a warning. +- SASL_PLAINTEXT is supported but sends events, and with PLAIN the password, unencrypted. + The README warns about this. +- The container tests need Docker and add roughly 30 seconds to the module's tests. + +**Not covered** + +- The `KAFKA_PUBLISH` system task (`KafkaProducerManager`) and the `kafka-event-queue` + module build their own Kafka clients and are unaffected by this decision. +- Encrypted PEM private keys work through `ssl.key.password`, but the container tests only + use unencrypted keys. + +## References + +- User documentation: [`kafka/README.md`](../kafka/README.md), section "Kafka Status Events". +- Implementation: `kafka/src/main/java/com/netflix/conductor/kafka/status/events/`. +- Tests: `kafka/src/test/java/com/netflix/conductor/kafka/status/events/services/`. +- Kafka producer settings: +- KIP-651, PEM support for keystores and truststores: + diff --git a/adr/README.md b/adr/README.md new file mode 100644 index 0000000000..551c3fe20f --- /dev/null +++ b/adr/README.md @@ -0,0 +1,23 @@ +# Architecture Decision Records + +This directory records significant design decisions made in this fork of Conductor, one +decision per file, using the format from Michael Nygard's +[Documenting Architecture Decisions](https://cognitect.com/blog/2011/11/15/documenting-architecture-decisions). + +Files are named `NNNN-short-title.md` with a sequential number. A record is not rewritten +once accepted; if a decision changes, add a new record that supersedes it and update the old +record's status. + +Each record has these sections: + +- **Status**: Proposed, Accepted, Deprecated, or Superseded by ADR-NNNN. +- **Context**: the problem and the forces at play. +- **Decision**: what was decided. +- **Alternatives considered**: options rejected, and why. +- **Consequences**: what becomes easier or harder as a result. + +## Index + +| ADR | Title | Status | +|---|---|---| +| [0001](0001-kafka-status-producer-security.md) | Secure connections for the Kafka status-event producer | Accepted | diff --git a/kafka/README.md b/kafka/README.md index 5195a41086..b2561b1911 100644 --- a/kafka/README.md +++ b/kafka/README.md @@ -180,4 +180,121 @@ kafka.publish.producer.cache.time.ms respectively. Task status transitions to `COMPLETED`. The task is marked as `FAILED` if the message could not be published to -the Kafka queue. \ No newline at end of file +the Kafka queue. +## Kafka Status Events + +Conductor can publish task and workflow status changes to Kafka topics. + +```properties +conductor.message-publisher.type=kafka +conductor.task-status-listener.type=kafka +conductor.workflow-status-listener.type=kafka +conductor.message-publisher.kafka.bootstrapServers=kafka:9092 +conductor.message-publisher.kafka.taskStatusTopic=conductor-task-status +conductor.message-publisher.kafka.workflowStatusTopic=conductor-workflow-status +conductor.message-publisher.kafka.allowedTaskStatuses=COMPLETED,FAILED +``` + +### Security + +By default the producer connects without encryption or authentication (`PLAINTEXT`). +Any [Kafka producer setting](https://kafka.apache.org/39/documentation/#producerconfigs) +can be set under `conductor.message-publisher.kafka.producer.*`, which is how SSL, mTLS, +SASL_SSL and SASL_PLAINTEXT are enabled. Examples below omit the +`conductor.message-publisher.kafka.producer.` prefix for brevity; every line needs it. + +Conductor checks these settings at startup and fails to start if a value is invalid or a +keystore or truststore file is missing or unreadable. Unknown settings are logged as a warning. +`key.serializer` and `value.serializer` cannot be changed. + +#### SSL (encryption, broker authenticated) + +```properties +security.protocol=SSL +ssl.truststore.type=PKCS12 +ssl.truststore.location=/etc/conductor/kafka/truststore.p12 +ssl.truststore.password=${KAFKA_TRUSTSTORE_PASSWORD} +``` + +With a PEM file holding the CA certificate(s): + +```properties +security.protocol=SSL +ssl.truststore.type=PEM +ssl.truststore.location=/etc/conductor/kafka/ca.crt +``` + +The truststore can be omitted if the broker's certificate is signed by a CA the JVM already +trusts. + +#### mTLS (SSL with a client certificate) + +The broker listener must have `ssl.client.auth=required`. Add a keystore to the SSL settings: + +```properties +ssl.keystore.type=PKCS12 +ssl.keystore.location=/etc/conductor/kafka/client.p12 +ssl.keystore.password=${KAFKA_KEYSTORE_PASSWORD} +``` + +or, in PEM format: + +```properties +ssl.keystore.type=PEM +ssl.keystore.location=/etc/conductor/kafka/client.pem +# Only when the private key is encrypted: +# ssl.key.password=${KAFKA_KEY_PASSWORD} +``` + +A PEM keystore file contains the private key in PKCS#8 format (`BEGIN PRIVATE KEY` or +`BEGIN ENCRYPTED PRIVATE KEY`) followed by the client certificate and any intermediate +certificates. Do not set `ssl.keystore.password` for PEM. + +#### SASL_SSL (encryption, user name and password) + +```properties +security.protocol=SASL_SSL +sasl.mechanism=SCRAM-SHA-512 +sasl.jaas.config=org.apache.kafka.common.security.scram.ScramLoginModule required username="conductor" password="${KAFKA_PASSWORD}"; +ssl.truststore.type=PEM +ssl.truststore.location=/etc/conductor/kafka/ca.crt +``` + +For `PLAIN`, use `sasl.mechanism=PLAIN` and +`org.apache.kafka.common.security.plain.PlainLoginModule`. `SCRAM-SHA-256` works the same way +as `SCRAM-SHA-512`. + +#### SASL_PLAINTEXT (user name and password, no encryption) + +```properties +security.protocol=SASL_PLAINTEXT +sasl.mechanism=SCRAM-SHA-512 +sasl.jaas.config=org.apache.kafka.common.security.scram.ScramLoginModule required username="conductor" password="${KAFKA_PASSWORD}"; +``` + +Status events, and with `PLAIN` the password, cross the network unencrypted. Use it only on a +trusted network. + +#### Certificates and keys + +- Certificates and keys must be files. Inline PEM settings (`ssl.keystore.key`, + `ssl.keystore.certificate.chain`, `ssl.truststore.certificates`) are not supported and + stop Conductor from starting. +- Supply passwords and `sasl.jaas.config` credentials through environment variables or a + secret store using `${...}` placeholders rather than writing them into the properties file. +- The producer reads certificates and credentials once. After renewing a certificate or + changing a password, restart Conductor. + +Converting between formats with `openssl`: + +```shell +# PEM key and certificate to a PKCS12 keystore +openssl pkcs12 -export -inkey client.key -in client.crt -certfile ca.crt -out client.p12 + +# PKCS12 keystore to a PEM keystore file (unencrypted PKCS#8 key followed by certificates) +openssl pkcs12 -in client.p12 -nocerts -nodes | openssl pkcs8 -topk8 -nocrypt > client.pem +openssl pkcs12 -in client.p12 -nokeys >> client.pem + +# Older "BEGIN RSA PRIVATE KEY" files to PKCS#8 +openssl pkcs8 -topk8 -nocrypt -in client.key -out client-pkcs8.key +``` diff --git a/kafka/build.gradle b/kafka/build.gradle index f34841dbb0..779186729c 100644 --- a/kafka/build.gradle +++ b/kafka/build.gradle @@ -27,4 +27,6 @@ dependencies { testImplementation project(':conductor-test-util') testImplementation project(':conductor-test-util').sourceSets.test.output testImplementation "redis.clients:jedis:${revJedis}" + testImplementation "org.testcontainers:testcontainers:${revTestContainer}" + testImplementation "org.testcontainers:junit-jupiter:${revTestContainer}" } diff --git a/kafka/src/main/java/com/netflix/conductor/kafka/status/events/config/KafkaProperties.java b/kafka/src/main/java/com/netflix/conductor/kafka/status/events/config/KafkaProperties.java index b4f3bf07bc..e0e2363898 100644 --- a/kafka/src/main/java/com/netflix/conductor/kafka/status/events/config/KafkaProperties.java +++ b/kafka/src/main/java/com/netflix/conductor/kafka/status/events/config/KafkaProperties.java @@ -13,7 +13,9 @@ package com.netflix.conductor.kafka.status.events.config; import java.util.Arrays; +import java.util.HashMap; import java.util.List; +import java.util.Map; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -51,6 +53,18 @@ public void setAllowedTaskStatuses(String allowedTaskStatuses) { this.allowedTaskStatuses = allowedTaskStatuses; } + /** + * Additional Kafka producer settings, e.g. {@code security.protocol}, {@code ssl.*} and {@code + * sasl.*}. Keys are Kafka producer config names. + */ + public Map getProducer() { + return producer; + } + + public void setProducer(Map producer) { + this.producer = producer; + } + public boolean isAlwaysPublishWorkflowStatusEnabled() { return alwaysPublishWorkflowStatusEnabled; } @@ -64,4 +78,5 @@ public void setAlwaysPublishWorkflowStatusEnabled(boolean alwaysPublishWorkflowS private String bootstrapServers = ""; private String taskStatusTopic = "conductor-task-status"; private String workflowStatusTopic = "conductor-workflow-status"; + private Map producer = new HashMap<>(); } diff --git a/kafka/src/main/java/com/netflix/conductor/kafka/status/events/services/KafkaEventServiceImpl.java b/kafka/src/main/java/com/netflix/conductor/kafka/status/events/services/KafkaEventServiceImpl.java index f5f15f636b..7fb3ac2a11 100644 --- a/kafka/src/main/java/com/netflix/conductor/kafka/status/events/services/KafkaEventServiceImpl.java +++ b/kafka/src/main/java/com/netflix/conductor/kafka/status/events/services/KafkaEventServiceImpl.java @@ -13,61 +13,160 @@ package com.netflix.conductor.kafka.status.events.services; import java.net.InetAddress; +import java.net.UnknownHostException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; import java.util.Properties; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; +import org.apache.kafka.common.config.ConfigException; +import org.apache.kafka.common.config.SslConfigs; import org.apache.kafka.common.serialization.StringSerializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import com.netflix.conductor.kafka.status.events.config.KafkaProperties; -public class KafkaEventServiceImpl implements KafkaEventService { +public class KafkaEventServiceImpl implements KafkaEventService, AutoCloseable { private static final Logger LOGGER = LoggerFactory.getLogger(KafkaEventServiceImpl.class); - private static KafkaProducer kafkaProducer; - private static synchronized KafkaProducer getKafkaProducer( - KafkaProperties kafkaProperties) throws Exception { + private static final String DEFAULT_CLIENT_ID = "conductor-status-producer"; - if (kafkaProducer == null) { + /** Certificates and keys given as PEM text in config; only file locations are supported. */ + static final List INLINE_CERTIFICATE_CONFIGS = + List.of( + SslConfigs.SSL_KEYSTORE_KEY_CONFIG, + SslConfigs.SSL_KEYSTORE_CERTIFICATE_CHAIN_CONFIG, + SslConfigs.SSL_TRUSTSTORE_CERTIFICATES_CONFIG); + + private static final List STORE_LOCATION_CONFIGS = + List.of( + SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG, + SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG); + + private static final List SERIALIZER_CONFIGS = + List.of( + ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, + ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG); - Properties producerConfig = new Properties(); - producerConfig.put( - ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaProperties.getBootstrapServers()); - producerConfig.put(ProducerConfig.ACKS_CONFIG, "all"); - producerConfig.put( - ProducerConfig.CLIENT_ID_CONFIG, InetAddress.getLocalHost().getHostName()); - producerConfig.put( - ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); + private final Properties producerConfig; + private KafkaProducer kafkaProducer; - KafkaJsonSerializer jsonSerializer = new KafkaJsonSerializer<>(); + public KafkaEventServiceImpl(KafkaProperties kafkaProperties) { + // Built and validated here so that misconfiguration fails startup. The producer itself + // is created on the first event, so the broker does not need to be reachable yet. + this.producerConfig = buildProducerConfig(kafkaProperties); + } + + /** + * Builds the producer settings: defaults, then the user's {@code producer.*} settings, then + * {@code bootstrap.servers}, then the serializers this service depends on. + * + * @throws ConfigException if a setting is invalid, a certificate is given inline, or a keystore + * or truststore file is not readable + */ + static Properties buildProducerConfig(KafkaProperties kafkaProperties) { + Properties config = new Properties(); + config.put(ProducerConfig.ACKS_CONFIG, "all"); + config.put(ProducerConfig.CLIENT_ID_CONFIG, defaultClientId()); + + kafkaProperties + .getProducer() + .forEach( + (key, value) -> { + if (!ProducerConfig.configNames().contains(key)) { + LOGGER.warn( + "Unknown Kafka producer setting '{}' in" + + " conductor.message-publisher.kafka.producer", + key); + } + if (SERIALIZER_CONFIGS.contains(key)) { + LOGGER.warn( + "Ignoring Kafka producer setting '{}': status events" + + " always use their built-in serializers", + key); + return; + } + config.put(key, value); + }); + + String bootstrapServers = kafkaProperties.getBootstrapServers(); + if (bootstrapServers != null && !bootstrapServers.isBlank()) { + config.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); + } + config.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); + config.put( + ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KafkaJsonSerializer.class.getName()); + + validate(config); + return config; + } + + private static void validate(Properties config) { + for (String key : INLINE_CERTIFICATE_CONFIGS) { + if (config.containsKey(key)) { + throw new ConfigException( + "Kafka producer setting '" + + key + + "' is not supported: certificates and keys must be given as" + + " files with " + + SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG + + " / " + + SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG); + } + } + + for (String key : STORE_LOCATION_CONFIGS) { + String location = config.getProperty(key); + if (location != null && !Files.isReadable(Path.of(location))) { + throw new ConfigException( + "Kafka producer setting '" + + key + + "' points to '" + + location + + "', which does not exist or is not readable"); + } + } + + // Checks types and allowed values (e.g. security.protocol) without connecting. + ProducerConfig.configDef().parse(config); + } + + private static String defaultClientId() { + try { + return InetAddress.getLocalHost().getHostName(); + } catch (UnknownHostException e) { + LOGGER.warn( + "Could not resolve local host name, using Kafka client id '{}'", + DEFAULT_CLIENT_ID, + e); + return DEFAULT_CLIENT_ID; + } + } + + private synchronized KafkaProducer getKafkaProducer() { + if (kafkaProducer == null) { try { - KafkaProducer producer = - new KafkaProducer<>(producerConfig, new StringSerializer(), jsonSerializer); - kafkaProducer = producer; - return producer; + kafkaProducer = + new KafkaProducer<>( + producerConfig, + new StringSerializer(), + new KafkaJsonSerializer<>()); } catch (Exception e) { LOGGER.error("Failed to create producer.", e); throw e; } } - return kafkaProducer; } - @Autowired private final KafkaProperties kafkaProperties; - - public KafkaEventServiceImpl(KafkaProperties kafkaProperties) { - this.kafkaProperties = kafkaProperties; - } - @Override public void produce(String key, V message, String topic) throws Exception { - KafkaProducer producer = getKafkaProducer(kafkaProperties); + KafkaProducer producer = getKafkaProducer(); final ProducerRecord record = new ProducerRecord<>(topic, key, message); producer.send( @@ -85,4 +184,12 @@ public void produce(String key, V message, String topic) throws Exception { producer.flush(); } + + @Override + public synchronized void close() { + if (kafkaProducer != null) { + kafkaProducer.close(); + kafkaProducer = null; + } + } } diff --git a/kafka/src/test/java/com/netflix/conductor/kafka/status/events/services/KafkaEventServiceImplTest.java b/kafka/src/test/java/com/netflix/conductor/kafka/status/events/services/KafkaEventServiceImplTest.java new file mode 100644 index 0000000000..6bbbd5a2a5 --- /dev/null +++ b/kafka/src/test/java/com/netflix/conductor/kafka/status/events/services/KafkaEventServiceImplTest.java @@ -0,0 +1,328 @@ +/* + * Copyright 2024 Conductor Authors. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ +package com.netflix.conductor.kafka.status.events.services; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import org.apache.kafka.clients.producer.ProducerConfig; +import org.apache.kafka.common.config.ConfigException; +import org.apache.kafka.common.serialization.StringSerializer; +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.core.LoggerContext; +import org.apache.logging.log4j.core.appender.AbstractAppender; +import org.apache.logging.log4j.core.config.Property; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import com.netflix.conductor.kafka.status.events.config.KafkaProperties; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class KafkaEventServiceImplTest { + + private static final String JAAS_PLAIN = + "org.apache.kafka.common.security.plain.PlainLoginModule required" + + " username=\"conductor\" password=\"secret\";"; + private static final String JAAS_SCRAM = + "org.apache.kafka.common.security.scram.ScramLoginModule required" + + " username=\"conductor\" password=\"secret\";"; + + @TempDir Path tempDir; + + private final List warnings = new ArrayList<>(); + private AbstractAppender appender; + + @BeforeEach + void captureWarnings() { + appender = + new AbstractAppender("capture", null, null, true, Property.EMPTY_ARRAY) { + @Override + public void append(LogEvent event) { + if (event.getLevel() == Level.WARN + && KafkaEventServiceImpl.class + .getName() + .equals(event.getLoggerName())) { + warnings.add(event.toImmutable()); + } + } + }; + appender.start(); + loggerConfig().addAppender(appender, Level.WARN, null); + loggerContext().updateLoggers(); + } + + @AfterEach + void stopCapturingWarnings() { + loggerConfig().removeAppender(appender.getName()); + loggerContext().updateLoggers(); + appender.stop(); + } + + @Test + void defaultsToUnencryptedConnection() { + Properties config = KafkaEventServiceImpl.buildProducerConfig(properties(Map.of())); + + assertEquals("all", config.get(ProducerConfig.ACKS_CONFIG)); + assertNotNull(config.get(ProducerConfig.CLIENT_ID_CONFIG)); + assertEquals("kafka:9092", config.get(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG)); + assertEquals( + StringSerializer.class.getName(), + config.get(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG)); + assertEquals( + KafkaJsonSerializer.class.getName(), + config.get(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG)); + assertFalse(config.containsKey("security.protocol")); + assertTrue(warnings.isEmpty()); + } + + @Test + void sslWithPkcs12Truststore() throws IOException { + Map producer = + Map.of( + "security.protocol", "SSL", + "ssl.truststore.type", "PKCS12", + "ssl.truststore.location", file("truststore.p12"), + "ssl.truststore.password", "changeit"); + + assertPassedThrough(producer); + } + + @Test + void sslWithPemTruststore() throws IOException { + Map producer = + Map.of( + "security.protocol", "SSL", + "ssl.truststore.type", "PEM", + "ssl.truststore.location", file("ca.crt")); + + assertPassedThrough(producer); + } + + @Test + void mtlsWithPkcs12() throws IOException { + Map producer = + Map.of( + "security.protocol", "SSL", + "ssl.truststore.type", "PKCS12", + "ssl.truststore.location", file("truststore.p12"), + "ssl.truststore.password", "changeit", + "ssl.keystore.type", "PKCS12", + "ssl.keystore.location", file("client.p12"), + "ssl.keystore.password", "changeit"); + + assertPassedThrough(producer); + } + + @Test + void mtlsWithPem() throws IOException { + Map producer = + Map.of( + "security.protocol", "SSL", + "ssl.truststore.type", "PEM", + "ssl.truststore.location", file("ca.crt"), + "ssl.keystore.type", "PEM", + "ssl.keystore.location", file("client.pem")); + + assertPassedThrough(producer); + } + + @Test + void saslSslWithPlain() throws IOException { + Map producer = + Map.of( + "security.protocol", "SASL_SSL", + "sasl.mechanism", "PLAIN", + "sasl.jaas.config", JAAS_PLAIN, + "ssl.truststore.type", "PEM", + "ssl.truststore.location", file("ca.crt")); + + assertPassedThrough(producer); + } + + @Test + void saslSslWithScram() throws IOException { + Map producer = + Map.of( + "security.protocol", "SASL_SSL", + "sasl.mechanism", "SCRAM-SHA-512", + "sasl.jaas.config", JAAS_SCRAM, + "ssl.truststore.type", "PKCS12", + "ssl.truststore.location", file("truststore.p12"), + "ssl.truststore.password", "changeit"); + + assertPassedThrough(producer); + } + + @Test + void saslPlaintext() { + Map producer = + Map.of( + "security.protocol", "SASL_PLAINTEXT", + "sasl.mechanism", "PLAIN", + "sasl.jaas.config", JAAS_PLAIN); + + assertPassedThrough(producer); + } + + @ParameterizedTest + @ValueSource( + strings = { + "ssl.keystore.key", + "ssl.keystore.certificate.chain", + "ssl.truststore.certificates" + }) + void rejectsInlineCertificates(String key) { + String pem = "-----BEGIN PRIVATE KEY-----\nMIIsecret\n-----END PRIVATE KEY-----"; + + ConfigException e = + assertThrows( + ConfigException.class, + () -> new KafkaEventServiceImpl(properties(Map.of(key, pem)))); + + assertTrue(e.getMessage().contains(key), e.getMessage()); + assertTrue(e.getMessage().contains("ssl.keystore.location"), e.getMessage()); + assertFalse(e.getMessage().contains("MIIsecret"), "must not echo the key material"); + } + + @ParameterizedTest + @ValueSource(strings = {"ssl.keystore.location", "ssl.truststore.location"}) + void rejectsMissingStoreFile(String key) { + String missing = tempDir.resolve("missing.p12").toString(); + + ConfigException e = + assertThrows( + ConfigException.class, + () -> new KafkaEventServiceImpl(properties(Map.of(key, missing)))); + + assertTrue(e.getMessage().contains(key), e.getMessage()); + assertTrue(e.getMessage().contains(missing), e.getMessage()); + } + + @Test + void rejectsInvalidSecurityProtocol() { + assertThrows( + ConfigException.class, + () -> new KafkaEventServiceImpl(properties(Map.of("security.protocol", "MTLS")))); + } + + @Test + void warnsAboutUnknownSettingsAndKeepsThem() { + Properties config = + KafkaEventServiceImpl.buildProducerConfig( + properties(Map.of("ssl.keystore.locaton", "/tmp/client.p12"))); + + assertEquals("/tmp/client.p12", config.get("ssl.keystore.locaton")); + assertTrue( + warnings.stream() + .anyMatch( + event -> + event.getMessage() + .getFormattedMessage() + .contains("ssl.keystore.locaton")), + "expected a warning naming the unknown setting"); + } + + @Test + void serializersCannotBeOverridden() { + Properties config = + KafkaEventServiceImpl.buildProducerConfig( + properties( + Map.of( + "key.serializer", "com.example.Custom", + "value.serializer", "com.example.Custom"))); + + assertEquals( + StringSerializer.class.getName(), + config.get(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG)); + assertEquals( + KafkaJsonSerializer.class.getName(), + config.get(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG)); + assertEquals(2, warnings.size()); + } + + @Test + void producerSettingsOverrideDefaults() { + Properties config = + KafkaEventServiceImpl.buildProducerConfig( + properties(Map.of("acks", "1", "client.id", "conductor-a"))); + + assertEquals("1", config.get(ProducerConfig.ACKS_CONFIG)); + assertEquals("conductor-a", config.get(ProducerConfig.CLIENT_ID_CONFIG)); + } + + @Test + void bootstrapServersSettingWinsOverProducerSetting() { + Properties config = + KafkaEventServiceImpl.buildProducerConfig( + properties(Map.of("bootstrap.servers", "other:9092"))); + + assertEquals("kafka:9092", config.get(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG)); + } + + @Test + void producerBootstrapServersUsedWhenSettingIsBlank() { + KafkaProperties properties = properties(Map.of("bootstrap.servers", "other:9092")); + properties.setBootstrapServers(""); + + Properties config = KafkaEventServiceImpl.buildProducerConfig(properties); + + assertEquals("other:9092", config.get(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG)); + } + + private void assertPassedThrough(Map producer) { + Properties config = KafkaEventServiceImpl.buildProducerConfig(properties(producer)); + + producer.forEach((key, value) -> assertEquals(value, config.get(key), key)); + // Kafka accepts the full set of settings, including its cross-setting checks. + new ProducerConfig(config); + assertTrue(warnings.isEmpty(), () -> "unexpected warnings: " + warnings); + } + + private KafkaProperties properties(Map producer) { + KafkaProperties properties = new KafkaProperties(); + properties.setBootstrapServers("kafka:9092"); + properties.setProducer(new HashMap<>(producer)); + return properties; + } + + private String file(String name) throws IOException { + return Files.writeString(tempDir.resolve(name), "placeholder").toString(); + } + + private static LoggerContext loggerContext() { + return (LoggerContext) LogManager.getContext(false); + } + + private static org.apache.logging.log4j.core.config.LoggerConfig loggerConfig() { + return loggerContext() + .getConfiguration() + .getLoggerConfig(KafkaEventServiceImpl.class.getName()); + } +} diff --git a/kafka/src/test/java/com/netflix/conductor/kafka/status/events/services/KafkaSecurityContainerTest.java b/kafka/src/test/java/com/netflix/conductor/kafka/status/events/services/KafkaSecurityContainerTest.java new file mode 100644 index 0000000000..6275880655 --- /dev/null +++ b/kafka/src/test/java/com/netflix/conductor/kafka/status/events/services/KafkaSecurityContainerTest.java @@ -0,0 +1,265 @@ +/* + * Copyright 2024 Conductor Authors. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ +package com.netflix.conductor.kafka.status.events.services; + +import java.nio.file.Path; +import java.time.Duration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; + +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.kafka.clients.consumer.KafkaConsumer; +import org.apache.kafka.clients.producer.KafkaProducer; +import org.apache.kafka.clients.producer.ProducerConfig; +import org.apache.kafka.clients.producer.ProducerRecord; +import org.apache.kafka.common.errors.AuthenticationException; +import org.apache.kafka.common.errors.TimeoutException; +import org.apache.kafka.common.serialization.StringDeserializer; +import org.apache.kafka.common.serialization.StringSerializer; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.testcontainers.DockerClientFactory; +import org.testcontainers.junit.jupiter.Testcontainers; + +import com.netflix.conductor.kafka.status.events.config.KafkaProperties; +import com.netflix.conductor.kafka.status.events.listener.TaskStatusKafkaProducer; +import com.netflix.conductor.model.TaskModel; + +import static com.netflix.conductor.kafka.status.events.services.SecureKafkaContainer.MTLS_PORT; +import static com.netflix.conductor.kafka.status.events.services.SecureKafkaContainer.PLAINTEXT_PORT; +import static com.netflix.conductor.kafka.status.events.services.SecureKafkaContainer.SASL_PASSWORD; +import static com.netflix.conductor.kafka.status.events.services.SecureKafkaContainer.SASL_PLAINTEXT_PORT; +import static com.netflix.conductor.kafka.status.events.services.SecureKafkaContainer.SASL_SSL_PORT; +import static com.netflix.conductor.kafka.status.events.services.SecureKafkaContainer.SASL_USER; +import static com.netflix.conductor.kafka.status.events.services.SecureKafkaContainer.SSL_PORT; +import static com.netflix.conductor.kafka.status.events.services.TestCertificates.PASSWORD; + +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Publishes status events through {@link KafkaEventServiceImpl} to a real broker over each + * supported security mode, using the settings a user would put under {@code + * conductor.message-publisher.kafka.producer.*}. + */ +@Testcontainers(disabledWithoutDocker = true) +class KafkaSecurityContainerTest { + + @TempDir static Path certDir; + + private static TestCertificates certs; + private static SecureKafkaContainer kafka; + + @BeforeAll + static void startKafka() throws Exception { + String dockerHost = DockerClientFactory.instance().dockerHostIpAddress(); + certs = TestCertificates.generate(certDir, List.of("localhost", "127.0.0.1", dockerHost)); + kafka = new SecureKafkaContainer(certs); + kafka.start(); + } + + @AfterAll + static void stopKafka() { + if (kafka != null) { + kafka.stop(); + } + } + + @Test + void sslWithPkcs12Truststore() throws Exception { + assertDelivered(SSL_PORT, pkcs12Truststore(Map.of("security.protocol", "SSL"))); + } + + @Test + void sslWithPemTruststore() throws Exception { + assertDelivered(SSL_PORT, pemTruststore(Map.of("security.protocol", "SSL"))); + } + + @Test + void mtlsWithPkcs12() throws Exception { + Map settings = pkcs12Truststore(Map.of("security.protocol", "SSL")); + settings.put("ssl.keystore.type", "PKCS12"); + settings.put("ssl.keystore.location", certs.clientKeystoreP12().toString()); + settings.put("ssl.keystore.password", PASSWORD); + + assertDelivered(MTLS_PORT, settings); + } + + @Test + void mtlsWithPem() throws Exception { + Map settings = pemTruststore(Map.of("security.protocol", "SSL")); + settings.put("ssl.keystore.type", "PEM"); + settings.put("ssl.keystore.location", certs.clientKeystorePem().toString()); + + assertDelivered(MTLS_PORT, settings); + } + + @Test + void saslSslWithPlain() throws Exception { + assertDelivered(SASL_SSL_PORT, pemTruststore(sasl("SASL_SSL", "PLAIN", SASL_PASSWORD))); + } + + @Test + void saslSslWithScram() throws Exception { + assertDelivered( + SASL_SSL_PORT, pkcs12Truststore(sasl("SASL_SSL", "SCRAM-SHA-512", SASL_PASSWORD))); + } + + @Test + void saslPlaintextWithPlain() throws Exception { + assertDelivered(SASL_PLAINTEXT_PORT, sasl("SASL_PLAINTEXT", "PLAIN", SASL_PASSWORD)); + } + + @Test + void mtlsRejectsClientWithoutCertificate() { + Throwable cause = + sendExpectingFailure( + MTLS_PORT, pkcs12Truststore(Map.of("security.protocol", "SSL"))); + + // With TLS 1.3 the broker rejects the missing certificate after the client's side of the + // handshake, so the client may only see the connection drop and time out. + assertTrue( + cause instanceof AuthenticationException || cause instanceof TimeoutException, + () -> "unexpected failure: " + cause); + } + + @Test + void saslRejectsWrongPassword() { + Throwable cause = + sendExpectingFailure( + SASL_SSL_PORT, + pkcs12Truststore(sasl("SASL_SSL", "SCRAM-SHA-512", "wrong-password"))); + + assertInstanceOf(AuthenticationException.class, cause); + } + + @Test + void sslRejectsUntrustedBrokerCertificate() { + Map settings = new HashMap<>(Map.of("security.protocol", "SSL")); + settings.put("ssl.truststore.type", "PKCS12"); + settings.put("ssl.truststore.location", certs.untrustedTruststoreP12().toString()); + settings.put("ssl.truststore.password", PASSWORD); + + assertInstanceOf(AuthenticationException.class, sendExpectingFailure(SSL_PORT, settings)); + } + + /** Publishes a task status event the way Conductor does and reads it back over PLAINTEXT. */ + private void assertDelivered(int port, Map settings) throws Exception { + String topic = "task-status-" + UUID.randomUUID(); + KafkaProperties properties = properties(port, settings); + properties.setTaskStatusTopic(topic); + properties.setAllowedTaskStatuses(TaskModel.Status.COMPLETED.name()); + + TaskModel task = new TaskModel(); + task.setTaskId(UUID.randomUUID().toString()); + task.setTaskType("SIMPLE"); + task.setStatus(TaskModel.Status.COMPLETED); + task.setWorkflowInstanceId(UUID.randomUUID().toString()); + + try (KafkaEventServiceImpl service = new KafkaEventServiceImpl(properties)) { + new TaskStatusKafkaProducer(service, properties).onTaskCompleted(task); + } + + String event = readOne(topic); + assertNotNull(event, "no status event was delivered to " + topic); + assertTrue(event.contains(task.getTaskId()), event); + } + + /** Sends with the same settings the service builds and returns why delivery failed. */ + private Throwable sendExpectingFailure(int port, Map settings) { + Properties config = KafkaEventServiceImpl.buildProducerConfig(properties(port, settings)); + + try (KafkaProducer producer = + new KafkaProducer<>(config, new StringSerializer(), new StringSerializer())) { + ExecutionException e = + assertThrows( + ExecutionException.class, + () -> + producer.send(new ProducerRecord<>("rejected", "key", "value")) + .get(30, TimeUnit.SECONDS)); + return e.getCause(); + } + } + + private String readOne(String topic) { + Properties config = new Properties(); + config.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafka.bootstrapServers(PLAINTEXT_PORT)); + config.put(ConsumerConfig.GROUP_ID_CONFIG, "test-" + UUID.randomUUID()); + config.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); + + try (KafkaConsumer consumer = + new KafkaConsumer<>(config, new StringDeserializer(), new StringDeserializer())) { + consumer.subscribe(List.of(topic)); + long deadline = System.nanoTime() + Duration.ofSeconds(30).toNanos(); + while (System.nanoTime() < deadline) { + for (ConsumerRecord record : + consumer.poll(Duration.ofMillis(500))) { + return record.value(); + } + } + return null; + } + } + + private static KafkaProperties properties(int port, Map settings) { + KafkaProperties properties = new KafkaProperties(); + properties.setBootstrapServers(kafka.bootstrapServers(port)); + Map producer = new HashMap<>(settings); + // Fail fast instead of blocking for the 60s default when a mode is misconfigured. + producer.put(ProducerConfig.MAX_BLOCK_MS_CONFIG, "15000"); + properties.setProducer(producer); + return properties; + } + + private static Map sasl(String protocol, String mechanism, String password) { + String loginModule = + mechanism.equals("PLAIN") + ? "org.apache.kafka.common.security.plain.PlainLoginModule" + : "org.apache.kafka.common.security.scram.ScramLoginModule"; + return Map.of( + "security.protocol", protocol, + "sasl.mechanism", mechanism, + "sasl.jaas.config", + loginModule + + " required username=\"" + + SASL_USER + + "\" password=\"" + + password + + "\";"); + } + + private static Map pkcs12Truststore(Map settings) { + Map result = new HashMap<>(settings); + result.put("ssl.truststore.type", "PKCS12"); + result.put("ssl.truststore.location", certs.truststoreP12().toString()); + result.put("ssl.truststore.password", PASSWORD); + return result; + } + + private static Map pemTruststore(Map settings) { + Map result = new HashMap<>(settings); + result.put("ssl.truststore.type", "PEM"); + result.put("ssl.truststore.location", certs.truststorePem().toString()); + return result; + } +} diff --git a/kafka/src/test/java/com/netflix/conductor/kafka/status/events/services/SecureKafkaContainer.java b/kafka/src/test/java/com/netflix/conductor/kafka/status/events/services/SecureKafkaContainer.java new file mode 100644 index 0000000000..2e36c1e065 --- /dev/null +++ b/kafka/src/test/java/com/netflix/conductor/kafka/status/events/services/SecureKafkaContainer.java @@ -0,0 +1,160 @@ +/* + * Copyright 2024 Conductor Authors. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ +package com.netflix.conductor.kafka.status.events.services; + +import java.time.Duration; + +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.wait.strategy.Wait; +import org.testcontainers.images.builder.Transferable; +import org.testcontainers.utility.DockerImageName; +import org.testcontainers.utility.MountableFile; + +import com.github.dockerjava.api.command.InspectContainerResponse; + +/** + * Single-node KRaft broker with one listener per security mode. The broker is started by a script + * copied in once Docker has assigned host ports, so the advertised listeners can use them. + */ +class SecureKafkaContainer extends GenericContainer { + + /** Matches the kafka-clients version the project uses. */ + static final DockerImageName IMAGE = DockerImageName.parse("apache/kafka:3.9.1"); + + /** Unauthenticated; used by the tests only to read messages back. */ + static final int PLAINTEXT_PORT = 9092; + + /** SSL without client certificates. */ + static final int SSL_PORT = 9094; + + /** SSL that requires a client certificate signed by the test CA. */ + static final int MTLS_PORT = 9095; + + /** SASL_SSL with PLAIN and SCRAM-SHA-512. */ + static final int SASL_SSL_PORT = 9096; + + /** SASL_PLAINTEXT with PLAIN. */ + static final int SASL_PLAINTEXT_PORT = 9097; + + static final String SASL_USER = "conductor"; + static final String SASL_PASSWORD = "conductor-secret"; + + private static final int CONTROLLER_PORT = 9093; + private static final int BROKER_PORT = 9098; + private static final String SECRETS = "/etc/kafka/secrets"; + private static final String STARTER = "/tmp/start-kafka.sh"; + + SecureKafkaContainer(TestCertificates certs) { + super(IMAGE); + withExposedPorts(PLAINTEXT_PORT, SSL_PORT, MTLS_PORT, SASL_SSL_PORT, SASL_PLAINTEXT_PORT); + withCopyFileToContainer( + MountableFile.forHostPath(certs.brokerKeystore(), 0644), SECRETS + "/broker.p12"); + withCopyFileToContainer( + MountableFile.forHostPath(certs.truststoreP12(), 0644), + SECRETS + "/truststore.p12"); + withCommand("sh", "-c", "while [ ! -f " + STARTER + " ]; do sleep 0.1; done; " + STARTER); + waitingFor( + Wait.forLogMessage(".*Kafka Server started.*", 1) + .withStartupTimeout(Duration.ofMinutes(2))); + } + + String bootstrapServers(int port) { + return getHost() + ":" + getMappedPort(port); + } + + @Override + protected void containerIsStarting(InspectContainerResponse containerInfo) { + String brokerHost = containerInfo.getConfig().getHostName(); + copyFileToContainer( + Transferable.of(serverProperties(brokerHost), 0644), "/tmp/server.properties"); + copyFileToContainer(Transferable.of(starterScript(), 0755), STARTER); + } + + private String starterScript() { + String scram = "SCRAM-SHA-512=[name=" + SASL_USER + ",password=" + SASL_PASSWORD + "]"; + return String.join( + "\n", + "#!/bin/bash", + "set -e", + "/opt/kafka/bin/kafka-storage.sh format -c /tmp/server.properties" + + " -t \"$(/opt/kafka/bin/kafka-storage.sh random-uuid)\"" + + " --add-scram '" + + scram + + "'", + "exec /opt/kafka/bin/kafka-server-start.sh /tmp/server.properties", + ""); + } + + private String serverProperties(String brokerHost) { + String plainUsers = + "org.apache.kafka.common.security.plain.PlainLoginModule required" + + " user_" + + SASL_USER + + "=\"" + + SASL_PASSWORD + + "\";"; + return String.join( + "\n", + "process.roles=broker,controller", + "node.id=1", + "controller.quorum.voters=1@localhost:" + CONTROLLER_PORT, + "controller.listener.names=CONTROLLER", + "inter.broker.listener.name=BROKER", + "listeners=" + + String.join( + ",", + "CONTROLLER://localhost:" + CONTROLLER_PORT, + "BROKER://0.0.0.0:" + BROKER_PORT, + "PLAINTEXT://0.0.0.0:" + PLAINTEXT_PORT, + "SSLONEWAY://0.0.0.0:" + SSL_PORT, + "MTLS://0.0.0.0:" + MTLS_PORT, + "SASLSSL://0.0.0.0:" + SASL_SSL_PORT, + "SASLPLAIN://0.0.0.0:" + SASL_PLAINTEXT_PORT), + "advertised.listeners=" + + String.join( + ",", + "BROKER://" + brokerHost + ":" + BROKER_PORT, + "PLAINTEXT://" + bootstrapServers(PLAINTEXT_PORT), + "SSLONEWAY://" + bootstrapServers(SSL_PORT), + "MTLS://" + bootstrapServers(MTLS_PORT), + "SASLSSL://" + bootstrapServers(SASL_SSL_PORT), + "SASLPLAIN://" + bootstrapServers(SASL_PLAINTEXT_PORT)), + "listener.security.protocol.map=CONTROLLER:PLAINTEXT,BROKER:PLAINTEXT," + + "PLAINTEXT:PLAINTEXT,SSLONEWAY:SSL,MTLS:SSL,SASLSSL:SASL_SSL," + + "SASLPLAIN:SASL_PLAINTEXT", + "log.dirs=/tmp/kraft-logs", + "num.partitions=1", + "auto.create.topics.enable=true", + "offsets.topic.replication.factor=1", + "transaction.state.log.replication.factor=1", + "transaction.state.log.min.isr=1", + "group.initial.rebalance.delay.ms=0", + // TLS, shared by the SSL and SASL_SSL listeners + "ssl.keystore.type=PKCS12", + "ssl.keystore.location=" + SECRETS + "/broker.p12", + "ssl.keystore.password=" + TestCertificates.PASSWORD, + "ssl.truststore.type=PKCS12", + "ssl.truststore.location=" + SECRETS + "/truststore.p12", + "ssl.truststore.password=" + TestCertificates.PASSWORD, + "listener.name.ssloneway.ssl.client.auth=none", + "listener.name.mtls.ssl.client.auth=required", + // SASL + "listener.name.saslssl.sasl.enabled.mechanisms=PLAIN,SCRAM-SHA-512", + "listener.name.saslssl.plain.sasl.jaas.config=" + plainUsers, + "listener.name.saslssl.scram-sha-512.sasl.jaas.config=" + + "org.apache.kafka.common.security.scram.ScramLoginModule required;", + "listener.name.saslplain.sasl.enabled.mechanisms=PLAIN", + "listener.name.saslplain.plain.sasl.jaas.config=" + plainUsers, + ""); + } +} diff --git a/kafka/src/test/java/com/netflix/conductor/kafka/status/events/services/TestCertificates.java b/kafka/src/test/java/com/netflix/conductor/kafka/status/events/services/TestCertificates.java new file mode 100644 index 0000000000..b40116b382 --- /dev/null +++ b/kafka/src/test/java/com/netflix/conductor/kafka/status/events/services/TestCertificates.java @@ -0,0 +1,270 @@ +/* + * Copyright 2024 Conductor Authors. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ +package com.netflix.conductor.kafka.status.events.services; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.Key; +import java.security.KeyStore; +import java.security.cert.Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.concurrent.TimeUnit; + +/** + * Throwaway certificates for the container tests, generated per run with the JDK's keytool: a test + * CA, a broker certificate signed by it, a client certificate signed by it, and an unrelated CA + * that the broker certificate does not chain to. + */ +final class TestCertificates { + + static final String PASSWORD = "changeit"; + + private final Path dir; + + private TestCertificates(Path dir) { + this.dir = dir; + } + + /** + * @param brokerHosts host names or IP addresses the broker certificate must be valid for + */ + static TestCertificates generate(Path dir, List brokerHosts) throws Exception { + TestCertificates certs = new TestCertificates(dir); + certs.createCa("ca", "Conductor Test CA"); + certs.createSigned("broker", "localhost", brokerHosts); + certs.createSigned("client", "conductor", List.of()); + certs.writePemKeystore("client.p12", "client", "client.pem"); + certs.createTruststore("ca", "truststore.p12"); + + certs.createCa("other-ca", "Unrelated CA"); + certs.createTruststore("other-ca", "other-truststore.p12"); + return certs; + } + + /** PKCS12 keystore with the broker's key and certificate chain. */ + Path brokerKeystore() { + return dir.resolve("broker.p12"); + } + + /** PKCS12 keystore with the client's key and certificate chain. */ + Path clientKeystoreP12() { + return dir.resolve("client.p12"); + } + + /** PEM file with the client's PKCS#8 private key followed by its certificate chain. */ + Path clientKeystorePem() { + return dir.resolve("client.pem"); + } + + /** PKCS12 truststore with the test CA. */ + Path truststoreP12() { + return dir.resolve("truststore.p12"); + } + + /** PEM file with the test CA certificate. */ + Path truststorePem() { + return dir.resolve("ca.crt"); + } + + /** PKCS12 truststore with a CA that did not sign the broker certificate. */ + Path untrustedTruststoreP12() { + return dir.resolve("other-truststore.p12"); + } + + private void createCa(String alias, String commonName) throws Exception { + keytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + commonName, + "-ext", + "bc:c", + "-validity", + "2", + "-keystore", + alias + ".p12", + "-storetype", + "PKCS12", + "-storepass", + PASSWORD, + "-keypass", + PASSWORD); + keytool( + "-exportcert", + "-rfc", + "-alias", + alias, + "-keystore", + alias + ".p12", + "-storepass", + PASSWORD, + "-file", + alias + ".crt"); + } + + private void createSigned(String alias, String commonName, List hosts) + throws Exception { + String keystore = alias + ".p12"; + keytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + commonName, + "-validity", + "2", + "-keystore", + keystore, + "-storetype", + "PKCS12", + "-storepass", + PASSWORD, + "-keypass", + PASSWORD); + keytool( + "-certreq", + "-alias", + alias, + "-keystore", + keystore, + "-storepass", + PASSWORD, + "-file", + alias + ".csr"); + + List gencert = + new ArrayList<>( + List.of( + "-gencert", + "-alias", + "ca", + "-keystore", + "ca.p12", + "-storepass", + PASSWORD, + "-infile", + alias + ".csr", + "-outfile", + alias + ".crt", + "-rfc", + "-validity", + "2", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=serverAuth,clientAuth")); + if (!hosts.isEmpty()) { + gencert.add("-ext"); + gencert.add( + "SAN=" + String.join(",", hosts.stream().map(TestCertificates::san).toList())); + } + keytool(gencert.toArray(String[]::new)); + + // Install the CA-signed certificate so the key entry carries the full chain. + keytool( + "-importcert", + "-noprompt", + "-alias", + "ca", + "-file", + "ca.crt", + "-keystore", + keystore, + "-storepass", + PASSWORD); + keytool( + "-importcert", + "-alias", + alias, + "-file", + alias + ".crt", + "-keystore", + keystore, + "-storepass", + PASSWORD); + keytool("-delete", "-alias", "ca", "-keystore", keystore, "-storepass", PASSWORD); + } + + private void createTruststore(String caAlias, String truststore) throws Exception { + keytool( + "-importcert", + "-noprompt", + "-alias", + caAlias, + "-file", + caAlias + ".crt", + "-keystore", + truststore, + "-storetype", + "PKCS12", + "-storepass", + PASSWORD); + } + + private void writePemKeystore(String pkcs12, String alias, String pemFile) throws Exception { + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (InputStream in = Files.newInputStream(dir.resolve(pkcs12))) { + keyStore.load(in, PASSWORD.toCharArray()); + } + Key key = keyStore.getKey(alias, PASSWORD.toCharArray()); + + // Java encodes RSA private keys as PKCS#8, the format Kafka requires for PEM keys. + StringBuilder pem = new StringBuilder(pem("PRIVATE KEY", key.getEncoded())); + for (Certificate certificate : keyStore.getCertificateChain(alias)) { + pem.append(pem("CERTIFICATE", certificate.getEncoded())); + } + Files.writeString(dir.resolve(pemFile), pem); + } + + private static String pem(String type, byte[] der) { + String body = + Base64.getMimeEncoder(64, "\n".getBytes(StandardCharsets.US_ASCII)) + .encodeToString(der); + return "-----BEGIN " + type + "-----\n" + body + "\n-----END " + type + "-----\n"; + } + + private static String san(String host) { + return (host.matches("[0-9.]+") || host.contains(":") ? "ip:" : "dns:") + host; + } + + private void keytool(String... args) throws IOException, InterruptedException { + List command = new ArrayList<>(); + command.add(Path.of(System.getProperty("java.home"), "bin", "keytool").toString()); + command.addAll(List.of(args)); + + Process process = + new ProcessBuilder(command) + .directory(dir.toFile()) + .redirectErrorStream(true) + .start(); + String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8); + if (!process.waitFor(60, TimeUnit.SECONDS) || process.exitValue() != 0) { + throw new IllegalStateException( + "keytool " + String.join(" ", args) + " failed:\n" + output); + } + } +} From 4ef763002885b8cb9e0527518bc1239bc60b21bd Mon Sep 17 00:00:00 2001 From: "bojan.malinic" Date: Mon, 23 Nov 2026 13:33:59 +0100 Subject: [PATCH 2/2] Cap Kafka status producer close at 10 seconds on shutdown KafkaProducer.close() waits indefinitely for unsent records, so a Kafka outage during shutdown could hold up Conductor for up to delivery.timeout.ms. Before the producer was closed on shutdown this could not happen, so bound the wait to keep shutdown behaviour as it was. Co-Authored-By: Claude Opus 5.5 --- adr/0001-kafka-status-producer-security.md | 3 ++- .../status/events/services/KafkaEventServiceImpl.java | 9 ++++++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/adr/0001-kafka-status-producer-security.md b/adr/0001-kafka-status-producer-security.md index d478779ddb..8731a7043d 100644 --- a/adr/0001-kafka-status-producer-security.md +++ b/adr/0001-kafka-status-producer-security.md @@ -88,7 +88,8 @@ would require the bootstrap address to resolve at startup. The producer moves from a `static` field to an instance field, so service instances with different settings no longer share whichever producer was created first. Conductor creates one service bean, so runtime behaviour is unchanged. The service implements `AutoCloseable`; -Spring calls `close()` on shutdown, which flushes and closes the producer. +Spring calls `close()` on shutdown, which closes the producer and waits at most 10 seconds +for events still being sent, so a Kafka outage cannot hold up shutdown indefinitely. ### 5. Keep kafka-clients at 3.9.1 diff --git a/kafka/src/main/java/com/netflix/conductor/kafka/status/events/services/KafkaEventServiceImpl.java b/kafka/src/main/java/com/netflix/conductor/kafka/status/events/services/KafkaEventServiceImpl.java index 7fb3ac2a11..1358cb8080 100644 --- a/kafka/src/main/java/com/netflix/conductor/kafka/status/events/services/KafkaEventServiceImpl.java +++ b/kafka/src/main/java/com/netflix/conductor/kafka/status/events/services/KafkaEventServiceImpl.java @@ -16,6 +16,7 @@ import java.net.UnknownHostException; import java.nio.file.Files; import java.nio.file.Path; +import java.time.Duration; import java.util.List; import java.util.Properties; @@ -36,6 +37,12 @@ public class KafkaEventServiceImpl implements KafkaEventService, AutoCloseable { private static final String DEFAULT_CLIENT_ID = "conductor-status-producer"; + /** + * Upper bound for closing the producer on shutdown. Without it, close waits indefinitely for + * unsent events, which would hold up shutdown while Kafka is unreachable. + */ + static final Duration CLOSE_TIMEOUT = Duration.ofSeconds(10); + /** Certificates and keys given as PEM text in config; only file locations are supported. */ static final List INLINE_CERTIFICATE_CONFIGS = List.of( @@ -188,7 +195,7 @@ public void produce(String key, V message, String topic) throws Exception { @Override public synchronized void close() { if (kafkaProducer != null) { - kafkaProducer.close(); + kafkaProducer.close(CLOSE_TIMEOUT); kafkaProducer = null; } }