From b8157c4e507c5febea819e62e0e00ab73fd69507 Mon Sep 17 00:00:00 2001 From: "bojan.malinic" Date: Mon, 23 Nov 2026 15:29:49 +0100 Subject: [PATCH 1/2] Add SSL, mTLS and SASL support to KafkaCancellationNotifier (4.5.0) Add a new AddKafkaCancellationNotifier(IConfiguration) overload that binds the Conductor:KafkaCancellationNotifier section, including security settings for SSL, mTLS (PEM files or PKCS#12 keystore), SASL_SSL and SASL_PLAINTEXT (PLAIN, SCRAM-SHA-256, SCRAM-SHA-512). Settings are validated on startup. Security settings are optional and only passed to librdkafka when configured, so existing setups produce the same client config as before. The existing AddKafkaCancellationNotifier method is unchanged and does not run the new validation. The admin client used for topic creation now shares the consumer's connection settings. Co-Authored-By: Claude Opus 5.5 --- README.md | 95 +++++++++- examples/ConductorSharp.NoApi/Program.cs | 6 +- .../ConductorSharp.NoApi/appsettings.json | 8 + .../AssemblyInfo.cs | 3 + ...ctorSharp.KafkaCancellationNotifier.csproj | 3 +- .../ExecutionManagerBuilderExtensions.cs | 23 +++ .../KafkaOptions.cs | 34 +++- .../Service/KafkaClientConfigFactory.cs | 54 ++++++ .../Service/KafkaConsumerBackgroundService.cs | 20 +- .../Service/KafkaOptionsValidator.cs | 75 ++++++++ .../ConductorSharp.Engine.Tests.csproj | 2 + ...kaCancellationNotifierRegistrationTests.cs | 145 +++++++++++++++ .../Unit/KafkaClientConfigFactoryTests.cs | 167 +++++++++++++++++ .../Unit/KafkaOptionsValidatorTests.cs | 172 ++++++++++++++++++ 14 files changed, 790 insertions(+), 17 deletions(-) create mode 100644 src/ConductorSharp.KafkaCancellationNotifier/AssemblyInfo.cs create mode 100644 src/ConductorSharp.KafkaCancellationNotifier/Service/KafkaClientConfigFactory.cs create mode 100644 src/ConductorSharp.KafkaCancellationNotifier/Service/KafkaOptionsValidator.cs create mode 100644 test/ConductorSharp.Engine.Tests/Unit/KafkaCancellationNotifierRegistrationTests.cs create mode 100644 test/ConductorSharp.Engine.Tests/Unit/KafkaClientConfigFactoryTests.cs create mode 100644 test/ConductorSharp.Engine.Tests/Unit/KafkaOptionsValidatorTests.cs diff --git a/README.md b/README.md index e56a0543..25b27441 100644 --- a/README.md +++ b/README.md @@ -935,7 +935,18 @@ These settings mean that if many workflows start waiting at the same time, regis ## Kafka Cancellation Notifier -Handle task cancellation via Kafka events: +Handle task cancellation via Kafka events. The notifier can be registered in two ways. + +**From configuration (recommended, supports SSL, mTLS and SASL):** + +```csharp +.AddExecutionManager(...) +.AddKafkaCancellationNotifier(configuration.GetSection("Conductor:KafkaCancellationNotifier")) +``` + +Settings are validated on startup, so a misconfigured connection fails fast with a descriptive error. + +**From code (plaintext connections only):** ```csharp .AddExecutionManager(...) @@ -964,6 +975,88 @@ Handle task cancellation via Kafka events: } ``` +### Settings + +Optional settings that are not configured are not passed to Kafka, so the librdkafka default applies. + +| Setting | Required | Default | Description | +|---|---|---|---| +| `BootstrapServers` | Yes | — | Kafka broker list | +| `TopicName` | Yes | — | Topic with Conductor task status events | +| `GroupId` | Yes | — | Consumer group id | +| `CreateTopicOnStartup` | No | `false` | Create the topic if it does not exist | +| `SecurityProtocol` | No | `Plaintext` | `Plaintext`, `Ssl`, `SaslPlaintext` or `SaslSsl` | +| `SaslMechanism` | With `SaslPlaintext`/`SaslSsl` | — | `Plain`, `ScramSha256` or `ScramSha512` | +| `SaslUsername` | With `SaslPlaintext`/`SaslSsl` | — | SASL username | +| `SaslPassword` | With `SaslPlaintext`/`SaslSsl` | — | SASL password | +| `SslCaLocation` | No | System trust store | Path to CA certificate PEM file | +| `SslCertificateLocation` | Together with `SslKeyLocation` | — | Path to client certificate PEM file (mTLS) | +| `SslKeyLocation` | Together with `SslCertificateLocation` | — | Path to client private key PEM file (mTLS) | +| `SslKeyPassword` | No | — | Password of an encrypted private key | +| `SslKeystoreLocation` | No | — | Path to PKCS#12 keystore (mTLS), alternative to certificate and key | +| `SslKeystorePassword` | No | — | Keystore password | +| `EnableSslCertificateVerification` | No | `true` | Verify the broker certificate; disable only for local development | +| `SslEndpointIdentificationAlgorithm` | No | `Https` | `None` disables broker hostname verification | + +`Ssl*` settings are used only when `SecurityProtocol` is `Ssl` or `SaslSsl`. Configured file paths must exist on startup. + +### Security examples + +**SSL** (broker certificate signed by a private CA): +```json +"KafkaCancellationNotifier": { + "BootstrapServers": "broker:9093", + "GroupId": "my-worker", + "TopicName": "conductor.status.task", + "SecurityProtocol": "Ssl", + "SslCaLocation": "/certs/ca.pem" +} +``` + +**mTLS** (client certificate authentication): +```json +"KafkaCancellationNotifier": { + "BootstrapServers": "broker:9093", + "GroupId": "my-worker", + "TopicName": "conductor.status.task", + "SecurityProtocol": "Ssl", + "SslCaLocation": "/certs/ca.pem", + "SslCertificateLocation": "/certs/client.pem", + "SslKeyLocation": "/certs/client.key" +} +``` + +Instead of `SslCertificateLocation` and `SslKeyLocation`, a PKCS#12 keystore can be used with `SslKeystoreLocation` and `SslKeystorePassword`. + +**SASL_SSL** (username and password over TLS): +```json +"KafkaCancellationNotifier": { + "BootstrapServers": "broker:9094", + "GroupId": "my-worker", + "TopicName": "conductor.status.task", + "SecurityProtocol": "SaslSsl", + "SaslMechanism": "ScramSha512", + "SaslUsername": "my-user", + "SaslPassword": "my-password", + "SslCaLocation": "/certs/ca.pem" +} +``` + +**SASL_PLAINTEXT** (username and password without TLS): +```json +"KafkaCancellationNotifier": { + "BootstrapServers": "broker:9092", + "GroupId": "my-worker", + "TopicName": "conductor.status.task", + "SecurityProtocol": "SaslPlaintext", + "SaslMechanism": "Plain", + "SaslUsername": "my-user", + "SaslPassword": "my-password" +} +``` + +Keep passwords out of `appsettings.json`, for example by using environment variables (`Conductor__KafkaCancellationNotifier__SaslPassword`) or a secret store. + ## Toolkit CLI Generate C# models from existing Conductor task/workflow definitions. diff --git a/examples/ConductorSharp.NoApi/Program.cs b/examples/ConductorSharp.NoApi/Program.cs index 48529228..377361d6 100644 --- a/examples/ConductorSharp.NoApi/Program.cs +++ b/examples/ConductorSharp.NoApi/Program.cs @@ -40,11 +40,7 @@ pipelines.AddCustomBehavior(); }) .AddConductorSharpPatterns(); - //.AddKafkaCancellationNotifier( - // kafkaBootstrapServers: configuration.GetValue( - // "Conductor:KafkaCancellationNotifier:BootstrapServers"), - // topicName: configuration.GetValue("Conductor:KafkaCancellationNotifier:TopicName"), - // groupId: configuration.GetValue("Conductor:KafkaCancellationNotifier:GroupId")); + //.AddKafkaCancellationNotifier(configuration.GetSection("Conductor:KafkaCancellationNotifier")); services.RegisterWorkerTask(); services.RegisterWorkerTask(); diff --git a/examples/ConductorSharp.NoApi/appsettings.json b/examples/ConductorSharp.NoApi/appsettings.json index 0e2c41ba..adefdd83 100644 --- a/examples/ConductorSharp.NoApi/appsettings.json +++ b/examples/ConductorSharp.NoApi/appsettings.json @@ -8,6 +8,14 @@ "BootstrapServers": "localhost:29092", "GroupId": "ConductorSharp.NoApi", "TopicName": "conductor.status.task" + // Optional security settings, see README "Kafka Cancellation Notifier" section: + //"SecurityProtocol": "SaslSsl", + //"SaslMechanism": "ScramSha512", + //"SaslUsername": "user", + //"SaslPassword": "password", + //"SslCaLocation": "/certs/ca.pem", + //"SslCertificateLocation": "/certs/client.pem", + //"SslKeyLocation": "/certs/client.key" } } } diff --git a/src/ConductorSharp.KafkaCancellationNotifier/AssemblyInfo.cs b/src/ConductorSharp.KafkaCancellationNotifier/AssemblyInfo.cs new file mode 100644 index 00000000..f7591f45 --- /dev/null +++ b/src/ConductorSharp.KafkaCancellationNotifier/AssemblyInfo.cs @@ -0,0 +1,3 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("ConductorSharp.Engine.Tests")] diff --git a/src/ConductorSharp.KafkaCancellationNotifier/ConductorSharp.KafkaCancellationNotifier.csproj b/src/ConductorSharp.KafkaCancellationNotifier/ConductorSharp.KafkaCancellationNotifier.csproj index 989e052e..7603edd3 100644 --- a/src/ConductorSharp.KafkaCancellationNotifier/ConductorSharp.KafkaCancellationNotifier.csproj +++ b/src/ConductorSharp.KafkaCancellationNotifier/ConductorSharp.KafkaCancellationNotifier.csproj @@ -4,13 +4,14 @@ net6.0 enable enable - 4.4.1 + 4.5.0 Codaxy Codaxy + diff --git a/src/ConductorSharp.KafkaCancellationNotifier/Extensions/ExecutionManagerBuilderExtensions.cs b/src/ConductorSharp.KafkaCancellationNotifier/Extensions/ExecutionManagerBuilderExtensions.cs index 035af988..ba4761ad 100644 --- a/src/ConductorSharp.KafkaCancellationNotifier/Extensions/ExecutionManagerBuilderExtensions.cs +++ b/src/ConductorSharp.KafkaCancellationNotifier/Extensions/ExecutionManagerBuilderExtensions.cs @@ -1,7 +1,10 @@ using ConductorSharp.Engine.Extensions; using ConductorSharp.Engine.Interface; using ConductorSharp.KafkaCancellationNotifier.Service; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Options; namespace ConductorSharp.KafkaCancellationNotifier.Extensions { @@ -29,6 +32,26 @@ public static IExecutionManagerBuilder AddKafkaCancellationNotifier( opts.CreateTopicOnStartup = createTopicOnStartup; }); + return AddNotifierServices(builder); + } + + /// + /// Registers the Kafka cancellation notifier with settings bound from the given configuration section + /// (e.g. Conductor:KafkaCancellationNotifier), including SSL, mTLS and SASL settings. + /// Settings are validated on startup. + /// + public static IExecutionManagerBuilder AddKafkaCancellationNotifier(this IExecutionManagerBuilder builder, IConfiguration configuration) + { + ArgumentNullException.ThrowIfNull(configuration); + + builder.Builder.AddOptions().Bind(configuration).ValidateOnStart(); + builder.Builder.TryAddEnumerable(ServiceDescriptor.Singleton, KafkaOptionsValidator>()); + + return AddNotifierServices(builder); + } + + private static IExecutionManagerBuilder AddNotifierServices(IExecutionManagerBuilder builder) + { builder.Builder.AddSingleton(); builder.Builder.AddHostedService(); diff --git a/src/ConductorSharp.KafkaCancellationNotifier/KafkaOptions.cs b/src/ConductorSharp.KafkaCancellationNotifier/KafkaOptions.cs index 2995a5f4..8e694975 100644 --- a/src/ConductorSharp.KafkaCancellationNotifier/KafkaOptions.cs +++ b/src/ConductorSharp.KafkaCancellationNotifier/KafkaOptions.cs @@ -1,4 +1,6 @@ -namespace ConductorSharp.KafkaCancellationNotifier; +using Confluent.Kafka; + +namespace ConductorSharp.KafkaCancellationNotifier; internal class KafkaOptions { @@ -6,4 +8,34 @@ internal class KafkaOptions public string TopicName { get; set; } = null!; public string GroupId { get; set; } = null!; public bool CreateTopicOnStartup { get; set; } + + // Security settings are optional and passed to librdkafka only when configured, so librdkafka defaults apply otherwise + public SecurityProtocol? SecurityProtocol { get; set; } + + public SaslMechanism? SaslMechanism { get; set; } + public string? SaslUsername { get; set; } + public string? SaslPassword { get; set; } + + public string? SslCaLocation { get; set; } + public string? SslCertificateLocation { get; set; } + public string? SslKeyLocation { get; set; } + public string? SslKeyPassword { get; set; } + public string? SslKeystoreLocation { get; set; } + public string? SslKeystorePassword { get; set; } + public bool? EnableSslCertificateVerification { get; set; } + public SslEndpointIdentificationAlgorithm? SslEndpointIdentificationAlgorithm { get; set; } + + internal bool IsSaslProtocol => SecurityProtocol is Confluent.Kafka.SecurityProtocol.SaslPlaintext or Confluent.Kafka.SecurityProtocol.SaslSsl; + + internal bool IsSslProtocol => SecurityProtocol is Confluent.Kafka.SecurityProtocol.Ssl or Confluent.Kafka.SecurityProtocol.SaslSsl; + + internal bool HasSslSettings => + SslCaLocation is not null + || SslCertificateLocation is not null + || SslKeyLocation is not null + || SslKeyPassword is not null + || SslKeystoreLocation is not null + || SslKeystorePassword is not null + || EnableSslCertificateVerification is not null + || SslEndpointIdentificationAlgorithm is not null; } diff --git a/src/ConductorSharp.KafkaCancellationNotifier/Service/KafkaClientConfigFactory.cs b/src/ConductorSharp.KafkaCancellationNotifier/Service/KafkaClientConfigFactory.cs new file mode 100644 index 00000000..a6e15203 --- /dev/null +++ b/src/ConductorSharp.KafkaCancellationNotifier/Service/KafkaClientConfigFactory.cs @@ -0,0 +1,54 @@ +using Confluent.Kafka; + +namespace ConductorSharp.KafkaCancellationNotifier.Service +{ + internal static class KafkaClientConfigFactory + { + public static ConsumerConfig CreateConsumerConfig(KafkaOptions options) + { + var config = new ConsumerConfig { GroupId = options.GroupId, AutoOffsetReset = AutoOffsetReset.Latest }; + ApplyConnectionSettings(config, options); + return config; + } + + public static AdminClientConfig CreateAdminClientConfig(KafkaOptions options) + { + var config = new AdminClientConfig(); + ApplyConnectionSettings(config, options); + return config; + } + + private static void ApplyConnectionSettings(ClientConfig config, KafkaOptions options) + { + config.BootstrapServers = options.BootstrapServers; + + // Only configured values are set, so an unsecured setup produces exactly the same config as before + if (options.SecurityProtocol is not null) + config.SecurityProtocol = options.SecurityProtocol; + + if (options.SaslMechanism is not null) + config.SaslMechanism = options.SaslMechanism; + if (options.SaslUsername is not null) + config.SaslUsername = options.SaslUsername; + if (options.SaslPassword is not null) + config.SaslPassword = options.SaslPassword; + + if (options.SslCaLocation is not null) + config.SslCaLocation = options.SslCaLocation; + if (options.SslCertificateLocation is not null) + config.SslCertificateLocation = options.SslCertificateLocation; + if (options.SslKeyLocation is not null) + config.SslKeyLocation = options.SslKeyLocation; + if (options.SslKeyPassword is not null) + config.SslKeyPassword = options.SslKeyPassword; + if (options.SslKeystoreLocation is not null) + config.SslKeystoreLocation = options.SslKeystoreLocation; + if (options.SslKeystorePassword is not null) + config.SslKeystorePassword = options.SslKeystorePassword; + if (options.EnableSslCertificateVerification is not null) + config.EnableSslCertificateVerification = options.EnableSslCertificateVerification; + if (options.SslEndpointIdentificationAlgorithm is not null) + config.SslEndpointIdentificationAlgorithm = options.SslEndpointIdentificationAlgorithm; + } + } +} diff --git a/src/ConductorSharp.KafkaCancellationNotifier/Service/KafkaConsumerBackgroundService.cs b/src/ConductorSharp.KafkaCancellationNotifier/Service/KafkaConsumerBackgroundService.cs index 02677733..c7b8430e 100644 --- a/src/ConductorSharp.KafkaCancellationNotifier/Service/KafkaConsumerBackgroundService.cs +++ b/src/ConductorSharp.KafkaCancellationNotifier/Service/KafkaConsumerBackgroundService.cs @@ -50,17 +50,19 @@ ICancellationNotifier notifier protected override async Task ExecuteAsync(CancellationToken stoppingToken) { + if (_kafkaOptions.Value.HasSslSettings && !_kafkaOptions.Value.IsSslProtocol) + _logger.LogWarning( + "SSL settings are configured but SecurityProtocol is {SecurityProtocol}, SSL settings will be ignored", + _kafkaOptions.Value.SecurityProtocol ?? SecurityProtocol.Plaintext + ); + if (_kafkaOptions.Value.CreateTopicOnStartup) await CreateTopicIfDoesNotExists(); - using var consumer = new ConsumerBuilder( - new ConsumerConfig - { - BootstrapServers = _kafkaOptions.Value.BootstrapServers, - GroupId = _kafkaOptions.Value.GroupId, - AutoOffsetReset = AutoOffsetReset.Latest - } - ).SetValueDeserializer(new TaskStatusModelDeserializer()).SetLogHandler(LogHandler).Build(); + using var consumer = new ConsumerBuilder(KafkaClientConfigFactory.CreateConsumerConfig(_kafkaOptions.Value)) + .SetValueDeserializer(new TaskStatusModelDeserializer()) + .SetLogHandler(LogHandler) + .Build(); consumer.Subscribe(_kafkaOptions.Value.TopicName); @@ -95,7 +97,7 @@ await Task.Run( private async Task CreateTopicIfDoesNotExists() { - using var admin = new AdminClientBuilder(new AdminClientConfig { BootstrapServers = _kafkaOptions.Value.BootstrapServers }).Build(); + using var admin = new AdminClientBuilder(KafkaClientConfigFactory.CreateAdminClientConfig(_kafkaOptions.Value)).Build(); try { diff --git a/src/ConductorSharp.KafkaCancellationNotifier/Service/KafkaOptionsValidator.cs b/src/ConductorSharp.KafkaCancellationNotifier/Service/KafkaOptionsValidator.cs new file mode 100644 index 00000000..c28d5e6b --- /dev/null +++ b/src/ConductorSharp.KafkaCancellationNotifier/Service/KafkaOptionsValidator.cs @@ -0,0 +1,75 @@ +using Confluent.Kafka; +using Microsoft.Extensions.Options; + +namespace ConductorSharp.KafkaCancellationNotifier.Service +{ + internal class KafkaOptionsValidator : IValidateOptions + { + private static readonly SaslMechanism[] SupportedSaslMechanisms = + { + SaslMechanism.Plain, + SaslMechanism.ScramSha256, + SaslMechanism.ScramSha512 + }; + + public ValidateOptionsResult Validate(string? name, KafkaOptions options) + { + var errors = new List(); + + RequireValue(errors, options.BootstrapServers, nameof(KafkaOptions.BootstrapServers)); + RequireValue(errors, options.TopicName, nameof(KafkaOptions.TopicName)); + RequireValue(errors, options.GroupId, nameof(KafkaOptions.GroupId)); + + if (options.IsSaslProtocol) + ValidateSasl(errors, options); + + if (options.IsSslProtocol) + ValidateSsl(errors, options); + + return errors.Count == 0 ? ValidateOptionsResult.Success : ValidateOptionsResult.Fail(errors); + } + + private static void ValidateSasl(List errors, KafkaOptions options) + { + if (options.SaslMechanism is null) + errors.Add( + $"{nameof(KafkaOptions.SaslMechanism)} is required when {nameof(KafkaOptions.SecurityProtocol)} is {options.SecurityProtocol}" + ); + else if (!SupportedSaslMechanisms.Contains(options.SaslMechanism.Value)) + errors.Add( + $"{nameof(KafkaOptions.SaslMechanism)} {options.SaslMechanism} is not supported, use one of: {string.Join(", ", SupportedSaslMechanisms)}" + ); + + RequireValue(errors, options.SaslUsername, nameof(KafkaOptions.SaslUsername)); + RequireValue(errors, options.SaslPassword, nameof(KafkaOptions.SaslPassword)); + } + + private static void ValidateSsl(List errors, KafkaOptions options) + { + if ((options.SslCertificateLocation is null) != (options.SslKeyLocation is null)) + errors.Add($"{nameof(KafkaOptions.SslCertificateLocation)} and {nameof(KafkaOptions.SslKeyLocation)} must be configured together"); + + if (options.SslKeystoreLocation is not null && (options.SslCertificateLocation is not null || options.SslKeyLocation is not null)) + errors.Add( + $"{nameof(KafkaOptions.SslKeystoreLocation)} cannot be combined with {nameof(KafkaOptions.SslCertificateLocation)} or {nameof(KafkaOptions.SslKeyLocation)}" + ); + + RequireExistingFile(errors, options.SslCaLocation, nameof(KafkaOptions.SslCaLocation)); + RequireExistingFile(errors, options.SslCertificateLocation, nameof(KafkaOptions.SslCertificateLocation)); + RequireExistingFile(errors, options.SslKeyLocation, nameof(KafkaOptions.SslKeyLocation)); + RequireExistingFile(errors, options.SslKeystoreLocation, nameof(KafkaOptions.SslKeystoreLocation)); + } + + private static void RequireValue(List errors, string? value, string settingName) + { + if (string.IsNullOrWhiteSpace(value)) + errors.Add($"{settingName} is required"); + } + + private static void RequireExistingFile(List errors, string? path, string settingName) + { + if (path is not null && !File.Exists(path)) + errors.Add($"{settingName} file '{path}' does not exist"); + } + } +} diff --git a/test/ConductorSharp.Engine.Tests/ConductorSharp.Engine.Tests.csproj b/test/ConductorSharp.Engine.Tests/ConductorSharp.Engine.Tests.csproj index a67cc2a7..79fbcf49 100644 --- a/test/ConductorSharp.Engine.Tests/ConductorSharp.Engine.Tests.csproj +++ b/test/ConductorSharp.Engine.Tests/ConductorSharp.Engine.Tests.csproj @@ -80,6 +80,7 @@ + @@ -94,6 +95,7 @@ + diff --git a/test/ConductorSharp.Engine.Tests/Unit/KafkaCancellationNotifierRegistrationTests.cs b/test/ConductorSharp.Engine.Tests/Unit/KafkaCancellationNotifierRegistrationTests.cs new file mode 100644 index 00000000..d54796e8 --- /dev/null +++ b/test/ConductorSharp.Engine.Tests/Unit/KafkaCancellationNotifierRegistrationTests.cs @@ -0,0 +1,145 @@ +using ConductorSharp.Engine.Extensions; +using ConductorSharp.KafkaCancellationNotifier; +using ConductorSharp.KafkaCancellationNotifier.Extensions; +using Confluent.Kafka; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Options; + +namespace ConductorSharp.Engine.Tests.Unit +{ + public class KafkaCancellationNotifierRegistrationTests + { + private const string SectionName = "Conductor:KafkaCancellationNotifier"; + + private static (IServiceCollection Services, IExecutionManagerBuilder Builder) CreateBuilder() + { + var services = new ServiceCollection(); + var builder = services + .AddConductorSharp(baseUrl: "http://empty/empty") + .AddExecutionManager( + maxConcurrentWorkers: 1, + sleepInterval: 1, + longPollInterval: 1, + domain: null, + handlerAssemblies: typeof(KafkaCancellationNotifierRegistrationTests).Assembly + ); + + return (services, builder); + } + + private static IConfiguration CreateSection(Dictionary settings) => + new ConfigurationBuilder() + .AddInMemoryCollection(settings.ToDictionary(kv => $"{SectionName}:{kv.Key}", kv => kv.Value)) + .Build() + .GetSection(SectionName); + + private static Dictionary RequiredSettings() => + new() + { + ["BootstrapServers"] = "broker:9093", + ["TopicName"] = "conductor.status.task", + ["GroupId"] = "group" + }; + + [Fact] + public void ExistingMethodRegistersOptionsWithoutValidation() + { + var (services, builder) = CreateBuilder(); + builder.AddKafkaCancellationNotifier(kafkaBootstrapServers: "broker:9092", topicName: "topic", groupId: "", createTopicOnStartup: true); + + using var provider = services.BuildServiceProvider(); + var options = provider.GetRequiredService>().Value; + + Assert.Equal("broker:9092", options.BootstrapServers); + Assert.Equal("topic", options.TopicName); + Assert.Equal("", options.GroupId); + Assert.True(options.CreateTopicOnStartup); + Assert.Null(options.SecurityProtocol); + Assert.False(options.HasSslSettings); + Assert.Empty(provider.GetServices>()); + Assert.Contains(services, d => d.ServiceType == typeof(ICancellationNotifier)); + Assert.Contains(services, d => d.ServiceType == typeof(IHostedService)); + } + + [Fact] + public void ConfigurationOverloadBindsAllSettings() + { + var settings = RequiredSettings(); + settings["CreateTopicOnStartup"] = "true"; + settings["SecurityProtocol"] = "SaslSsl"; + settings["SaslMechanism"] = "ScramSha512"; + settings["SaslUsername"] = "user"; + settings["SaslPassword"] = "password"; + settings["SslKeyPassword"] = "key-password"; + settings["SslKeystorePassword"] = "keystore-password"; + settings["EnableSslCertificateVerification"] = "false"; + settings["SslEndpointIdentificationAlgorithm"] = "None"; + + var (services, builder) = CreateBuilder(); + builder.AddKafkaCancellationNotifier(CreateSection(settings)); + + using var provider = services.BuildServiceProvider(); + var options = provider.GetRequiredService>().Value; + + Assert.Equal("broker:9093", options.BootstrapServers); + Assert.Equal("conductor.status.task", options.TopicName); + Assert.Equal("group", options.GroupId); + Assert.True(options.CreateTopicOnStartup); + Assert.Equal(SecurityProtocol.SaslSsl, options.SecurityProtocol); + Assert.Equal(SaslMechanism.ScramSha512, options.SaslMechanism); + Assert.Equal("user", options.SaslUsername); + Assert.Equal("password", options.SaslPassword); + Assert.Equal("key-password", options.SslKeyPassword); + Assert.Equal("keystore-password", options.SslKeystorePassword); + Assert.False(options.EnableSslCertificateVerification); + Assert.Equal(SslEndpointIdentificationAlgorithm.None, options.SslEndpointIdentificationAlgorithm); + Assert.Contains(services, d => d.ServiceType == typeof(ICancellationNotifier)); + Assert.Contains(services, d => d.ServiceType == typeof(IHostedService)); + } + + [Fact] + public void ConfigurationOverloadLeavesOptionalSettingsUnset() + { + var (services, builder) = CreateBuilder(); + builder.AddKafkaCancellationNotifier(CreateSection(RequiredSettings())); + + using var provider = services.BuildServiceProvider(); + var options = provider.GetRequiredService>().Value; + + Assert.False(options.CreateTopicOnStartup); + Assert.Null(options.SecurityProtocol); + Assert.Null(options.SaslMechanism); + Assert.Null(options.SaslUsername); + Assert.Null(options.SaslPassword); + Assert.False(options.HasSslSettings); + } + + [Fact] + public void ConfigurationOverloadValidatesOnStartup() + { + var settings = RequiredSettings(); + settings["SecurityProtocol"] = "SaslPlaintext"; + + var (services, builder) = CreateBuilder(); + builder.AddKafkaCancellationNotifier(CreateSection(settings)); + + using var provider = services.BuildServiceProvider(); + var exception = Assert.Throws(() => provider.GetRequiredService().Validate()); + + Assert.Contains($"{nameof(KafkaOptions.SaslUsername)} is required", exception.Failures); + } + + [Fact] + public void ConfigurationOverloadPassesStartupValidationWhenValid() + { + var (services, builder) = CreateBuilder(); + builder.AddKafkaCancellationNotifier(CreateSection(RequiredSettings())); + + using var provider = services.BuildServiceProvider(); + + provider.GetRequiredService().Validate(); + } + } +} diff --git a/test/ConductorSharp.Engine.Tests/Unit/KafkaClientConfigFactoryTests.cs b/test/ConductorSharp.Engine.Tests/Unit/KafkaClientConfigFactoryTests.cs new file mode 100644 index 00000000..60878ef7 --- /dev/null +++ b/test/ConductorSharp.Engine.Tests/Unit/KafkaClientConfigFactoryTests.cs @@ -0,0 +1,167 @@ +using ConductorSharp.KafkaCancellationNotifier; +using ConductorSharp.KafkaCancellationNotifier.Service; +using Confluent.Kafka; + +namespace ConductorSharp.Engine.Tests.Unit +{ + public class KafkaClientConfigFactoryTests + { + private static KafkaOptions CreateOptions() => + new() + { + BootstrapServers = "broker:9093", + TopicName = "conductor.status.task", + GroupId = "group" + }; + + [Fact] + public void PlaintextConsumerConfigContainsOnlyPreviouslySetProperties() + { + var config = KafkaClientConfigFactory.CreateConsumerConfig(CreateOptions()); + + Assert.Equal( + new Dictionary + { + ["bootstrap.servers"] = "broker:9093", + ["group.id"] = "group", + ["auto.offset.reset"] = "latest" + }, + config.ToDictionary(kv => kv.Key, kv => kv.Value) + ); + } + + [Fact] + public void PlaintextAdminClientConfigContainsOnlyBootstrapServers() + { + var config = KafkaClientConfigFactory.CreateAdminClientConfig(CreateOptions()); + + Assert.Equal(new Dictionary { ["bootstrap.servers"] = "broker:9093" }, config.ToDictionary(kv => kv.Key, kv => kv.Value)); + } + + [Fact] + public void SslSettingsAreMapped() + { + var options = CreateOptions(); + options.SecurityProtocol = SecurityProtocol.Ssl; + options.SslCaLocation = "/certs/ca.pem"; + options.EnableSslCertificateVerification = false; + options.SslEndpointIdentificationAlgorithm = SslEndpointIdentificationAlgorithm.None; + + var config = KafkaClientConfigFactory.CreateConsumerConfig(options); + + Assert.Equal(SecurityProtocol.Ssl, config.SecurityProtocol); + Assert.Equal("/certs/ca.pem", config.SslCaLocation); + Assert.False(config.EnableSslCertificateVerification); + Assert.Equal(SslEndpointIdentificationAlgorithm.None, config.SslEndpointIdentificationAlgorithm); + Assert.Null(config.SaslMechanism); + Assert.Null(config.SslCertificateLocation); + } + + [Fact] + public void MutualTlsPemSettingsAreMapped() + { + var options = CreateOptions(); + options.SecurityProtocol = SecurityProtocol.Ssl; + options.SslCaLocation = "/certs/ca.pem"; + options.SslCertificateLocation = "/certs/client.pem"; + options.SslKeyLocation = "/certs/client.key"; + options.SslKeyPassword = "key-password"; + + var config = KafkaClientConfigFactory.CreateConsumerConfig(options); + + Assert.Equal("/certs/client.pem", config.SslCertificateLocation); + Assert.Equal("/certs/client.key", config.SslKeyLocation); + Assert.Equal("key-password", config.SslKeyPassword); + Assert.Null(config.SslKeystoreLocation); + } + + [Fact] + public void MutualTlsKeystoreSettingsAreMapped() + { + var options = CreateOptions(); + options.SecurityProtocol = SecurityProtocol.Ssl; + options.SslKeystoreLocation = "/certs/client.p12"; + options.SslKeystorePassword = "keystore-password"; + + var config = KafkaClientConfigFactory.CreateConsumerConfig(options); + + Assert.Equal("/certs/client.p12", config.SslKeystoreLocation); + Assert.Equal("keystore-password", config.SslKeystorePassword); + Assert.Null(config.SslCertificateLocation); + } + + [Fact] + public void SaslPlaintextSettingsAreMapped() + { + var options = CreateOptions(); + options.SecurityProtocol = SecurityProtocol.SaslPlaintext; + options.SaslMechanism = SaslMechanism.Plain; + options.SaslUsername = "user"; + options.SaslPassword = "password"; + + var config = KafkaClientConfigFactory.CreateConsumerConfig(options); + + Assert.Equal(SecurityProtocol.SaslPlaintext, config.SecurityProtocol); + Assert.Equal(SaslMechanism.Plain, config.SaslMechanism); + Assert.Equal("user", config.SaslUsername); + Assert.Equal("password", config.SaslPassword); + Assert.Null(config.SslCaLocation); + } + + [Fact] + public void SaslSslSettingsAreMappedToConsumerAndAdminClient() + { + var options = CreateOptions(); + options.SecurityProtocol = SecurityProtocol.SaslSsl; + options.SaslMechanism = SaslMechanism.ScramSha512; + options.SaslUsername = "user"; + options.SaslPassword = "password"; + options.SslCaLocation = "/certs/ca.pem"; + + var configs = new ClientConfig[] + { + KafkaClientConfigFactory.CreateConsumerConfig(options), + KafkaClientConfigFactory.CreateAdminClientConfig(options) + }; + + Assert.All( + configs, + config => + { + Assert.Equal("broker:9093", config.BootstrapServers); + Assert.Equal(SecurityProtocol.SaslSsl, config.SecurityProtocol); + Assert.Equal(SaslMechanism.ScramSha512, config.SaslMechanism); + Assert.Equal("user", config.SaslUsername); + Assert.Equal("password", config.SaslPassword); + Assert.Equal("/certs/ca.pem", config.SslCaLocation); + } + ); + } + + [Theory] + [InlineData(SecurityProtocol.Plaintext)] + [InlineData(SecurityProtocol.Ssl)] + [InlineData(SecurityProtocol.SaslPlaintext)] + [InlineData(SecurityProtocol.SaslSsl)] + public void LibrdkafkaAcceptsGeneratedConfig(SecurityProtocol protocol) + { + var options = CreateOptions(); + options.SecurityProtocol = protocol; + if (protocol is SecurityProtocol.SaslPlaintext or SecurityProtocol.SaslSsl) + { + options.SaslMechanism = SaslMechanism.ScramSha256; + options.SaslUsername = "user"; + options.SaslPassword = "password"; + } + if (protocol is SecurityProtocol.Ssl or SecurityProtocol.SaslSsl) + { + options.EnableSslCertificateVerification = false; + options.SslEndpointIdentificationAlgorithm = SslEndpointIdentificationAlgorithm.None; + } + + // Building clients makes librdkafka validate the configuration without connecting to a broker + using var consumer = new ConsumerBuilder(KafkaClientConfigFactory.CreateConsumerConfig(options)).Build(); + using var admin = new AdminClientBuilder(KafkaClientConfigFactory.CreateAdminClientConfig(options)).Build(); + } + } +} diff --git a/test/ConductorSharp.Engine.Tests/Unit/KafkaOptionsValidatorTests.cs b/test/ConductorSharp.Engine.Tests/Unit/KafkaOptionsValidatorTests.cs new file mode 100644 index 00000000..c2df4c51 --- /dev/null +++ b/test/ConductorSharp.Engine.Tests/Unit/KafkaOptionsValidatorTests.cs @@ -0,0 +1,172 @@ +using ConductorSharp.KafkaCancellationNotifier; +using ConductorSharp.KafkaCancellationNotifier.Service; +using Confluent.Kafka; + +namespace ConductorSharp.Engine.Tests.Unit +{ + public class KafkaOptionsValidatorTests : IDisposable + { + private readonly KafkaOptionsValidator _validator = new(); + private readonly string _existingFile = Path.GetTempFileName(); + private readonly string _missingFile = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.pem"); + + public void Dispose() => File.Delete(_existingFile); + + private static KafkaOptions CreateOptions() => + new() + { + BootstrapServers = "broker:9093", + TopicName = "conductor.status.task", + GroupId = "group" + }; + + private KafkaOptions CreateSaslOptions(SecurityProtocol protocol) + { + var options = CreateOptions(); + options.SecurityProtocol = protocol; + options.SaslMechanism = SaslMechanism.ScramSha256; + options.SaslUsername = "user"; + options.SaslPassword = "password"; + return options; + } + + private IEnumerable Validate(KafkaOptions options) => _validator.Validate(null, options).Failures ?? Enumerable.Empty(); + + [Fact] + public void PlaintextWithRequiredSettingsIsValid() + { + Assert.True(_validator.Validate(null, CreateOptions()).Succeeded); + } + + [Theory] + [InlineData(nameof(KafkaOptions.BootstrapServers))] + [InlineData(nameof(KafkaOptions.TopicName))] + [InlineData(nameof(KafkaOptions.GroupId))] + public void MissingRequiredSettingFails(string settingName) + { + var options = CreateOptions(); + typeof(KafkaOptions).GetProperty(settingName)!.SetValue(options, " "); + + Assert.Contains($"{settingName} is required", Validate(options)); + } + + [Theory] + [InlineData(SecurityProtocol.SaslPlaintext)] + [InlineData(SecurityProtocol.SaslSsl)] + public void SaslWithAllSettingsIsValid(SecurityProtocol protocol) + { + Assert.Empty(Validate(CreateSaslOptions(protocol))); + } + + [Theory] + [InlineData(SecurityProtocol.SaslPlaintext)] + [InlineData(SecurityProtocol.SaslSsl)] + public void SaslRequiresMechanismAndCredentials(SecurityProtocol protocol) + { + var options = CreateOptions(); + options.SecurityProtocol = protocol; + + var failures = Validate(options).ToList(); + + Assert.Contains(failures, f => f.StartsWith(nameof(KafkaOptions.SaslMechanism))); + Assert.Contains($"{nameof(KafkaOptions.SaslUsername)} is required", failures); + Assert.Contains($"{nameof(KafkaOptions.SaslPassword)} is required", failures); + } + + [Theory] + [InlineData(SaslMechanism.Gssapi)] + [InlineData(SaslMechanism.OAuthBearer)] + public void UnsupportedSaslMechanismFails(SaslMechanism mechanism) + { + var options = CreateSaslOptions(SecurityProtocol.SaslSsl); + options.SaslMechanism = mechanism; + + Assert.Contains(Validate(options), f => f.Contains($"{mechanism} is not supported")); + } + + [Fact] + public void SaslSettingsAreNotRequiredForSsl() + { + var options = CreateOptions(); + options.SecurityProtocol = SecurityProtocol.Ssl; + + Assert.Empty(Validate(options)); + } + + [Fact] + public void MutualTlsWithExistingPemFilesIsValid() + { + var options = CreateOptions(); + options.SecurityProtocol = SecurityProtocol.Ssl; + options.SslCaLocation = _existingFile; + options.SslCertificateLocation = _existingFile; + options.SslKeyLocation = _existingFile; + + Assert.Empty(Validate(options)); + } + + [Fact] + public void MutualTlsWithExistingKeystoreIsValid() + { + var options = CreateOptions(); + options.SecurityProtocol = SecurityProtocol.SaslSsl; + options.SaslMechanism = SaslMechanism.Plain; + options.SaslUsername = "user"; + options.SaslPassword = "password"; + options.SslKeystoreLocation = _existingFile; + + Assert.Empty(Validate(options)); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void CertificateAndKeyMustBeConfiguredTogether(bool configureCertificate) + { + var options = CreateOptions(); + options.SecurityProtocol = SecurityProtocol.Ssl; + if (configureCertificate) + options.SslCertificateLocation = _existingFile; + else + options.SslKeyLocation = _existingFile; + + Assert.Contains(Validate(options), f => f.Contains("must be configured together")); + } + + [Fact] + public void KeystoreCannotBeCombinedWithCertificateAndKey() + { + var options = CreateOptions(); + options.SecurityProtocol = SecurityProtocol.Ssl; + options.SslCertificateLocation = _existingFile; + options.SslKeyLocation = _existingFile; + options.SslKeystoreLocation = _existingFile; + + Assert.Contains(Validate(options), f => f.StartsWith($"{nameof(KafkaOptions.SslKeystoreLocation)} cannot be combined")); + } + + [Theory] + [InlineData(nameof(KafkaOptions.SslCaLocation))] + [InlineData(nameof(KafkaOptions.SslCertificateLocation))] + [InlineData(nameof(KafkaOptions.SslKeyLocation))] + [InlineData(nameof(KafkaOptions.SslKeystoreLocation))] + public void MissingFileFails(string settingName) + { + var options = CreateOptions(); + options.SecurityProtocol = SecurityProtocol.Ssl; + typeof(KafkaOptions).GetProperty(settingName)!.SetValue(options, _missingFile); + + Assert.Contains($"{settingName} file '{_missingFile}' does not exist", Validate(options)); + } + + [Fact] + public void SslSettingsAreNotValidatedWhenProtocolIsNotSsl() + { + var options = CreateOptions(); + options.SslCaLocation = _missingFile; + options.SslCertificateLocation = _missingFile; + + Assert.Empty(Validate(options)); + } + } +} From f916fb3380fc2d6390b5c6804b5b4843e4b6465f Mon Sep 17 00:00:00 2001 From: "bojan.malinic" Date: Mon, 23 Nov 2026 15:39:49 +0100 Subject: [PATCH 2/2] Bump ConductorSharp packages to 4.5.0 and document Kafka security in SKILL.md Keep all packages on the same version as KafkaCancellationNotifier, and describe the new IConfiguration overload and security settings in the SKILL.md Kafka section. Co-Authored-By: Claude Opus 5.5 --- SKILL.md | 24 +++++++++++++++++++ .../ConductorSharp.Client.csproj | 2 +- .../ConductorSharp.Engine.csproj | 2 +- .../ConductorSharp.Patterns.csproj | 2 +- .../ConductorSharp.Toolkit.csproj | 2 +- 5 files changed, 28 insertions(+), 4 deletions(-) diff --git a/SKILL.md b/SKILL.md index b65779d4..56d3e439 100644 --- a/SKILL.md +++ b/SKILL.md @@ -760,6 +760,30 @@ public class MyController( ### Kafka Cancellation Notifier +Register from configuration (supports SSL, mTLS, SASL_SSL and SASL_PLAINTEXT; settings are validated on startup): + +```csharp +.AddExecutionManager(...) +.AddKafkaCancellationNotifier(configuration.GetSection("Conductor:KafkaCancellationNotifier")) +``` + +```json +"KafkaCancellationNotifier": { + "BootstrapServers": "broker:9094", + "GroupId": "my-worker-group", + "TopicName": "conductor.status.task", + "SecurityProtocol": "SaslSsl", + "SaslMechanism": "ScramSha512", + "SaslUsername": "my-user", + "SaslPassword": "my-password", + "SslCaLocation": "/certs/ca.pem" +} +``` + +`BootstrapServers`, `GroupId` and `TopicName` are required. `SecurityProtocol` defaults to `Plaintext`. SASL protocols require `SaslMechanism` (`Plain`, `ScramSha256`, `ScramSha512`), `SaslUsername` and `SaslPassword`. For mTLS, set `SslCertificateLocation` and `SslKeyLocation` (PEM files) or `SslKeystoreLocation` (PKCS#12). Certificates are configured as file paths only. See the README for the full settings reference. + +Or register from code (plaintext connections only): + ```csharp .AddExecutionManager(...) .AddKafkaCancellationNotifier( diff --git a/src/ConductorSharp.Client/ConductorSharp.Client.csproj b/src/ConductorSharp.Client/ConductorSharp.Client.csproj index 1a506640..946018b3 100644 --- a/src/ConductorSharp.Client/ConductorSharp.Client.csproj +++ b/src/ConductorSharp.Client/ConductorSharp.Client.csproj @@ -6,7 +6,7 @@ Codaxy Codaxy ConductorSharp.Client - 4.4.1 + 4.5.0 Client library for Netflix Conductor, with some additional quality of life features. https://github.com/codaxy/conductor-sharp netflix;conductor diff --git a/src/ConductorSharp.Engine/ConductorSharp.Engine.csproj b/src/ConductorSharp.Engine/ConductorSharp.Engine.csproj index df478cee..d2e48908 100644 --- a/src/ConductorSharp.Engine/ConductorSharp.Engine.csproj +++ b/src/ConductorSharp.Engine/ConductorSharp.Engine.csproj @@ -6,7 +6,7 @@ Codaxy Codaxy ConductorSharp.Engine - 4.4.1 + 4.5.0 Client library for Netflix Conductor, with some additional quality of life features. https://github.com/codaxy/conductor-sharp netflix;conductor diff --git a/src/ConductorSharp.Patterns/ConductorSharp.Patterns.csproj b/src/ConductorSharp.Patterns/ConductorSharp.Patterns.csproj index 70163e9e..f2273b42 100644 --- a/src/ConductorSharp.Patterns/ConductorSharp.Patterns.csproj +++ b/src/ConductorSharp.Patterns/ConductorSharp.Patterns.csproj @@ -7,7 +7,7 @@ False Codaxy Codaxy - 4.4.1 + 4.5.0 diff --git a/src/ConductorSharp.Toolkit/ConductorSharp.Toolkit.csproj b/src/ConductorSharp.Toolkit/ConductorSharp.Toolkit.csproj index 0b48430b..1d5c5a4e 100644 --- a/src/ConductorSharp.Toolkit/ConductorSharp.Toolkit.csproj +++ b/src/ConductorSharp.Toolkit/ConductorSharp.Toolkit.csproj @@ -7,7 +7,7 @@ disable true dotnet-conductorsharp - 4.4.1 + 4.5.0