Skip to main content

risingwave_connector/connector_common/
common.rs

1// Copyright 2024 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::BTreeMap;
16use std::hash::Hash;
17use std::io::Write;
18use std::path::Path;
19use std::sync::{Arc, LazyLock, Weak};
20use std::time::Duration;
21
22use anyhow::{Context, anyhow};
23use async_nats::jetstream::consumer::DeliverPolicy;
24use async_nats::jetstream::{self};
25use aws_sdk_kinesis::Client as KinesisClient;
26use aws_sdk_kinesis::config::{AsyncSleep, SharedAsyncSleep, Sleep};
27use moka::future::Cache as MokaCache;
28use moka::ops::compute::Op;
29use phf::{Set, phf_set};
30use pulsar::authentication::oauth2::{OAuth2Authentication, OAuth2Params};
31use pulsar::{Authentication, OperationRetryOptions, Pulsar, TokioExecutor};
32use rdkafka::ClientConfig;
33use risingwave_common::bail;
34use rustls_pki_types::pem::PemObject;
35use rustls_pki_types::{CertificateDer, PrivatePkcs8KeyDer};
36use serde::Deserialize;
37use serde_with::json::JsonString;
38use serde_with::{DisplayFromStr, serde_as};
39use tempfile::NamedTempFile;
40use time::OffsetDateTime;
41use url::Url;
42use with_options::WithOptions;
43
44use crate::aws_utils::load_file_descriptor_from_s3;
45use crate::deserialize_duration_from_string;
46use crate::enforce_secret::EnforceSecret;
47use crate::error::ConnectorResult;
48use crate::sink::SinkError;
49use crate::source::nats::source::NatsOffset;
50
51pub const PRIVATE_LINK_BROKER_REWRITE_MAP_KEY: &str = "broker.rewrite.endpoints";
52pub const PRIVATE_LINK_TARGETS_KEY: &str = "privatelink.targets";
53
54const AWS_MSK_IAM_AUTH: &str = "AWS_MSK_IAM";
55
56/// The environment variable to disable using default credential from environment.
57/// It's recommended to set this variable to `true` in cloud hosting environment.
58pub const DISABLE_DEFAULT_CREDENTIAL: &str = "DISABLE_DEFAULT_CREDENTIAL";
59
60#[derive(Debug, Clone, Deserialize)]
61pub struct AwsPrivateLinkItem {
62    pub az_id: Option<String>,
63    pub port: u16,
64}
65
66use aws_config::default_provider::region::DefaultRegionChain;
67use aws_config::sts::AssumeRoleProvider;
68use aws_credential_types::provider::SharedCredentialsProvider;
69use aws_types::SdkConfig;
70use aws_types::region::Region;
71use risingwave_common::util::env_var::env_var_is_true;
72
73/// A flatten config map for aws auth.
74#[derive(Deserialize, Debug, Clone, WithOptions, PartialEq)]
75pub struct AwsAuthProps {
76    #[serde(rename = "aws.region", alias = "region", alias = "s3.region")]
77    pub region: Option<String>,
78
79    #[serde(
80        rename = "aws.endpoint_url",
81        alias = "endpoint_url",
82        alias = "endpoint",
83        alias = "s3.endpoint"
84    )]
85    pub endpoint: Option<String>,
86    #[serde(
87        rename = "aws.credentials.access_key_id",
88        alias = "access_key",
89        alias = "s3.access.key"
90    )]
91    pub access_key: Option<String>,
92    #[serde(
93        rename = "aws.credentials.secret_access_key",
94        alias = "secret_key",
95        alias = "s3.secret.key"
96    )]
97    pub secret_key: Option<String>,
98    #[serde(rename = "aws.credentials.session_token", alias = "session_token")]
99    pub session_token: Option<String>,
100    /// IAM role
101    #[serde(rename = "aws.credentials.role.arn", alias = "arn")]
102    pub arn: Option<String>,
103    /// external ID in IAM role trust policy
104    #[serde(rename = "aws.credentials.role.external_id", alias = "external_id")]
105    pub external_id: Option<String>,
106    #[serde(rename = "aws.profile", alias = "profile")]
107    pub profile: Option<String>,
108    #[serde(rename = "aws.msk.signer_timeout_sec")]
109    pub msk_signer_timeout_sec: Option<u64>,
110}
111
112impl EnforceSecret for AwsAuthProps {
113    const ENFORCE_SECRET_PROPERTIES: Set<&'static str> = phf_set! {
114        "access_key",
115        "aws.credentials.access_key_id",
116        "s3.access.key",
117        "secret_key",
118        "aws.credentials.secret_access_key",
119        "s3.secret.key",
120        "session_token",
121        "aws.credentials.session_token",
122    };
123}
124
125impl AwsAuthProps {
126    async fn build_region(&self) -> ConnectorResult<Region> {
127        if let Some(region_name) = &self.region {
128            Ok(Region::new(region_name.clone()))
129        } else {
130            let mut region_chain = DefaultRegionChain::builder();
131            if let Some(profile_name) = &self.profile {
132                region_chain = region_chain.profile_name(profile_name);
133            }
134
135            Ok(region_chain
136                .build()
137                .region()
138                .await
139                .context("region must be provided")?)
140        }
141    }
142
143    async fn build_credential_provider(&self) -> ConnectorResult<SharedCredentialsProvider> {
144        if let (Some(access_key), Some(secret_key)) =
145            (self.access_key.as_ref(), self.secret_key.as_ref())
146        {
147            Ok(SharedCredentialsProvider::new(
148                aws_credential_types::Credentials::from_keys(
149                    access_key,
150                    secret_key,
151                    self.session_token.clone(),
152                ),
153            ))
154        } else if !env_var_is_true(DISABLE_DEFAULT_CREDENTIAL) {
155            Ok(SharedCredentialsProvider::new(
156                Box::pin(aws_config::default_provider::credentials::default_provider()).await,
157            ))
158        } else {
159            bail!("Both `access_key` and `secret_key` must be provided")
160        }
161    }
162
163    async fn with_role_provider(
164        &self,
165        credential: SharedCredentialsProvider,
166    ) -> ConnectorResult<SharedCredentialsProvider> {
167        if let Some(role_name) = &self.arn {
168            let region = self.build_region().await?;
169            let mut role = AssumeRoleProvider::builder(role_name)
170                .session_name("RisingWave")
171                .region(region);
172            if let Some(id) = &self.external_id {
173                role = role.external_id(id);
174            }
175            let provider = Box::pin(role.build_from_provider(credential)).await;
176            Ok(SharedCredentialsProvider::new(provider))
177        } else {
178            Ok(credential)
179        }
180    }
181
182    pub async fn build_config(&self) -> ConnectorResult<SdkConfig> {
183        let region = self.build_region().await?;
184        let credentials_provider = self
185            .with_role_provider(self.build_credential_provider().await?)
186            .await?;
187        let mut config_loader = aws_config::from_env()
188            .region(region)
189            .credentials_provider(credentials_provider);
190
191        if let Some(endpoint) = self.endpoint.as_ref() {
192            config_loader = config_loader.endpoint_url(endpoint);
193        }
194
195        Ok(Box::pin(config_loader.load()).await)
196    }
197}
198
199#[serde_as]
200#[derive(Debug, Clone, Deserialize, WithOptions, PartialEq, Hash, Eq)]
201pub struct KafkaConnectionProps {
202    #[serde(rename = "properties.bootstrap.server", alias = "kafka.brokers")]
203    pub brokers: String,
204
205    /// Security protocol used for RisingWave to communicate with Kafka brokers. Could be
206    /// PLAINTEXT, SSL, `SASL_PLAINTEXT` or `SASL_SSL`.
207    #[serde(rename = "properties.security.protocol")]
208    #[with_option(allow_alter_on_fly)]
209    security_protocol: Option<String>,
210
211    #[serde(rename = "properties.ssl.endpoint.identification.algorithm")]
212    #[with_option(allow_alter_on_fly)]
213    ssl_endpoint_identification_algorithm: Option<String>,
214
215    // For the properties below, please refer to [librdkafka](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md) for more information.
216    /// Path to CA certificate file for verifying the broker's key.
217    #[serde(rename = "properties.ssl.ca.location")]
218    #[with_option(allow_alter_on_fly)]
219    ssl_ca_location: Option<String>,
220
221    /// CA certificate string (PEM format) for verifying the broker's key.
222    #[serde(rename = "properties.ssl.ca.pem")]
223    #[with_option(allow_alter_on_fly)]
224    ssl_ca_pem: Option<String>,
225
226    /// Path to client's certificate file (PEM).
227    #[serde(rename = "properties.ssl.certificate.location")]
228    #[with_option(allow_alter_on_fly)]
229    ssl_certificate_location: Option<String>,
230
231    /// Client's public key string (PEM format) used for authentication.
232    #[serde(rename = "properties.ssl.certificate.pem")]
233    #[with_option(allow_alter_on_fly)]
234    ssl_certificate_pem: Option<String>,
235
236    /// Path to client's private key file (PEM).
237    #[serde(rename = "properties.ssl.key.location")]
238    #[with_option(allow_alter_on_fly)]
239    ssl_key_location: Option<String>,
240
241    /// Client's private key string (PEM format) used for authentication.
242    #[serde(rename = "properties.ssl.key.pem")]
243    #[with_option(allow_alter_on_fly)]
244    ssl_key_pem: Option<String>,
245
246    /// Passphrase of client's private key.
247    #[serde(rename = "properties.ssl.key.password")]
248    #[with_option(allow_alter_on_fly)]
249    ssl_key_password: Option<String>,
250
251    /// SASL mechanism if SASL is enabled. Currently support PLAIN, SCRAM, GSSAPI, OAUTHBEARER, and `AWS_MSK_IAM`.
252    #[serde(rename = "properties.sasl.mechanism")]
253    #[with_option(allow_alter_on_fly)]
254    sasl_mechanism: Option<String>,
255
256    /// SASL username for SASL/PLAIN and SASL/SCRAM.
257    #[serde(rename = "properties.sasl.username")]
258    #[with_option(allow_alter_on_fly)]
259    sasl_username: Option<String>,
260
261    /// SASL password for SASL/PLAIN and SASL/SCRAM.
262    #[serde(rename = "properties.sasl.password")]
263    #[with_option(allow_alter_on_fly)]
264    sasl_password: Option<String>,
265
266    /// Kafka server's Kerberos principal name under SASL/GSSAPI, not including /hostname@REALM.
267    #[serde(rename = "properties.sasl.kerberos.service.name")]
268    #[with_option(allow_alter_on_fly)]
269    sasl_kerberos_service_name: Option<String>,
270
271    /// Path to client's Kerberos keytab file under SASL/GSSAPI.
272    #[serde(rename = "properties.sasl.kerberos.keytab")]
273    #[serde(default, deserialize_with = "deserialize_kinit_arg")]
274    #[with_option(allow_alter_on_fly)]
275    sasl_kerberos_keytab: Option<String>,
276
277    /// Client's Kerberos principal name under SASL/GSSAPI.
278    #[serde(rename = "properties.sasl.kerberos.principal")]
279    #[serde(default, deserialize_with = "deserialize_kinit_arg")]
280    #[with_option(allow_alter_on_fly)]
281    sasl_kerberos_principal: Option<String>,
282
283    /// Minimum time in milliseconds between key refresh attempts under SASL/GSSAPI.
284    #[serde(rename = "properties.sasl.kerberos.min.time.before.relogin")]
285    #[with_option(allow_alter_on_fly)]
286    sasl_kerberos_min_time_before_relogin: Option<String>,
287
288    /// Configurations for SASL/OAUTHBEARER.
289    #[serde(rename = "properties.sasl.oauthbearer.config")]
290    #[with_option(allow_alter_on_fly)]
291    sasl_oathbearer_config: Option<String>,
292
293    /// SASL/OAUTHBEARER token acquisition method. Set to "oidc" to use the OIDC client credentials flow.
294    #[serde(rename = "properties.sasl.oauthbearer.method")]
295    #[with_option(allow_alter_on_fly)]
296    sasl_oauthbearer_method: Option<String>,
297
298    /// Client ID for SASL/OAUTHBEARER OIDC provider.
299    #[serde(rename = "properties.sasl.oauthbearer.client.id")]
300    #[with_option(allow_alter_on_fly)]
301    sasl_oauthbearer_client_id: Option<String>,
302
303    /// Client secret for SASL/OAUTHBEARER OIDC provider.
304    #[serde(rename = "properties.sasl.oauthbearer.client.secret")]
305    #[with_option(allow_alter_on_fly)]
306    sasl_oauthbearer_client_secret: Option<String>,
307
308    /// OIDC token endpoint URL for SASL/OAUTHBEARER.
309    #[serde(rename = "properties.sasl.oauthbearer.token.endpoint.url")]
310    #[with_option(allow_alter_on_fly)]
311    sasl_oauthbearer_token_endpoint_url: Option<String>,
312
313    /// OIDC scope for SASL/OAUTHBEARER.
314    #[serde(rename = "properties.sasl.oauthbearer.scope")]
315    #[with_option(allow_alter_on_fly)]
316    sasl_oauthbearer_scope: Option<String>,
317
318    /// SASL/OAUTHBEARER extensions for broker-facing claims (e.g. Confluent Cloud logicalCluster, identityPoolId).
319    #[serde(rename = "properties.sasl.oauthbearer.extensions")]
320    #[with_option(allow_alter_on_fly)]
321    sasl_oauthbearer_extensions: Option<String>,
322}
323
324impl EnforceSecret for KafkaConnectionProps {
325    const ENFORCE_SECRET_PROPERTIES: Set<&'static str> = phf_set! {
326        "properties.ssl.key.pem",
327        "properties.ssl.key.password",
328        "properties.sasl.password",
329        "properties.sasl.oauthbearer.client.secret",
330    };
331}
332
333#[serde_as]
334#[derive(Debug, Clone, Deserialize, WithOptions)]
335pub struct KafkaCommon {
336    // connection related props are moved to `KafkaConnection`
337    #[serde(rename = "topic", alias = "kafka.topic")]
338    pub topic: String,
339
340    #[serde(
341        rename = "properties.sync.call.timeout",
342        deserialize_with = "deserialize_duration_from_string",
343        default = "default_kafka_sync_call_timeout"
344    )]
345    #[with_option(allow_alter_on_fly)]
346    pub sync_call_timeout: Duration,
347}
348
349#[serde_as]
350#[derive(Debug, Clone, Deserialize, WithOptions, PartialEq, Hash, Eq)]
351pub struct KafkaPrivateLinkCommon {
352    /// This is generated from `private_link_targets` and `private_link_endpoint` in frontend, instead of given by users.
353    #[serde(rename = "broker.rewrite.endpoints")]
354    #[serde_as(as = "Option<JsonString>")]
355    pub broker_rewrite_map: Option<BTreeMap<String, String>>,
356}
357
358const fn default_kafka_sync_call_timeout() -> Duration {
359    Duration::from_secs(5)
360}
361
362const fn default_socket_keepalive_enable() -> bool {
363    true
364}
365
366#[serde_as]
367#[derive(Debug, Clone, Deserialize, WithOptions)]
368pub struct RdKafkaPropertiesCommon {
369    /// Maximum Kafka protocol request message size. Due to differing framing overhead between
370    /// protocol versions the producer is unable to reliably enforce a strict max message limit at
371    /// produce time and may exceed the maximum size by one message in protocol `ProduceRequests`,
372    /// the broker will enforce the topic's max.message.bytes limit
373    #[serde(rename = "properties.message.max.bytes")]
374    #[serde_as(as = "Option<DisplayFromStr>")]
375    #[with_option(allow_alter_on_fly)]
376    pub message_max_bytes: Option<usize>,
377
378    /// Maximum Kafka protocol response message size. This serves as a safety precaution to avoid
379    /// memory exhaustion in case of protocol hickups. This value must be at least fetch.max.bytes
380    /// + 512 to allow for protocol overhead; the value is adjusted automatically unless the
381    /// configuration property is explicitly set.
382    #[serde(rename = "properties.receive.message.max.bytes")]
383    #[serde_as(as = "Option<DisplayFromStr>")]
384    #[with_option(allow_alter_on_fly)]
385    pub receive_message_max_bytes: Option<usize>,
386
387    #[serde(rename = "properties.statistics.interval.ms")]
388    #[serde_as(as = "Option<DisplayFromStr>")]
389    #[with_option(allow_alter_on_fly)]
390    pub statistics_interval_ms: Option<usize>,
391
392    /// Client identifier
393    #[serde(rename = "properties.client.id")]
394    #[serde_as(as = "Option<DisplayFromStr>")]
395    #[with_option(allow_alter_on_fly)]
396    pub client_id: Option<String>,
397
398    #[serde(rename = "properties.enable.ssl.certificate.verification")]
399    #[serde_as(as = "Option<DisplayFromStr>")]
400    #[with_option(allow_alter_on_fly)]
401    pub enable_ssl_certificate_verification: Option<bool>,
402
403    /// Initial backoff time in milliseconds before reconnecting to a broker after a connection
404    /// closes.
405    #[serde(rename = "properties.reconnect.backoff.ms")]
406    #[serde_as(as = "Option<DisplayFromStr>")]
407    #[with_option(allow_alter_on_fly)]
408    pub reconnect_backoff_ms: Option<usize>,
409
410    /// Maximum backoff time in milliseconds before reconnecting to a broker after a connection
411    /// closes.
412    #[serde(rename = "properties.reconnect.backoff.max.ms")]
413    #[serde_as(as = "Option<DisplayFromStr>")]
414    #[with_option(allow_alter_on_fly)]
415    pub reconnect_backoff_max_ms: Option<usize>,
416
417    /// Maximum time in milliseconds allowed for broker connection setup, including TCP setup and
418    /// SSL/SASL handshakes.
419    #[serde(rename = "properties.socket.connection.setup.timeout.ms")]
420    #[serde_as(as = "Option<DisplayFromStr>")]
421    #[with_option(allow_alter_on_fly)]
422    pub socket_connection_setup_timeout_ms: Option<usize>,
423
424    #[serde(
425        rename = "properties.socket.keepalive.enable",
426        default = "default_socket_keepalive_enable"
427    )]
428    #[serde_as(as = "DisplayFromStr")]
429    pub socket_keepalive_enable: bool,
430
431    /// Initial backoff time in milliseconds before retrying a failed protocol request.
432    #[serde(rename = "properties.retry.backoff.ms")]
433    #[serde_as(as = "Option<DisplayFromStr>")]
434    #[with_option(allow_alter_on_fly)]
435    pub retry_backoff_ms: Option<usize>,
436
437    /// Maximum backoff time in milliseconds before retrying a failed protocol request.
438    #[serde(rename = "properties.retry.backoff.max.ms")]
439    #[serde_as(as = "Option<DisplayFromStr>")]
440    #[with_option(allow_alter_on_fly)]
441    pub retry_backoff_max_ms: Option<usize>,
442}
443
444impl RdKafkaPropertiesCommon {
445    pub(crate) fn set_client(&self, c: &mut rdkafka::ClientConfig) {
446        if let Some(v) = self.statistics_interval_ms {
447            c.set("statistics.interval.ms", v.to_string());
448        }
449        if let Some(v) = self.message_max_bytes {
450            c.set("message.max.bytes", v.to_string());
451        }
452        if let Some(v) = self.receive_message_max_bytes {
453            c.set("receive.message.max.bytes", v.to_string());
454        }
455        if let Some(v) = self.client_id.as_ref() {
456            c.set("client.id", v);
457        }
458        if let Some(v) = self.enable_ssl_certificate_verification {
459            c.set("enable.ssl.certificate.verification", v.to_string());
460        }
461        if let Some(v) = self.reconnect_backoff_ms {
462            c.set("reconnect.backoff.ms", v.to_string());
463        }
464        if let Some(v) = self.reconnect_backoff_max_ms {
465            c.set("reconnect.backoff.max.ms", v.to_string());
466        }
467        if let Some(v) = self.socket_connection_setup_timeout_ms {
468            c.set("socket.connection.setup.timeout.ms", v.to_string());
469        }
470        c.set(
471            "socket.keepalive.enable",
472            self.socket_keepalive_enable.to_string(),
473        );
474        if let Some(v) = self.retry_backoff_ms {
475            c.set("retry.backoff.ms", v.to_string());
476        }
477        if let Some(v) = self.retry_backoff_max_ms {
478            c.set("retry.backoff.max.ms", v.to_string());
479        }
480    }
481}
482
483impl KafkaConnectionProps {
484    #[cfg(test)]
485    pub fn test_default() -> Self {
486        Self {
487            brokers: "localhost:9092".to_owned(),
488            security_protocol: None,
489            ssl_ca_location: None,
490            ssl_certificate_location: None,
491            ssl_key_location: None,
492            ssl_ca_pem: None,
493            ssl_certificate_pem: None,
494            ssl_key_pem: None,
495            ssl_key_password: None,
496            ssl_endpoint_identification_algorithm: None,
497            sasl_mechanism: None,
498            sasl_username: None,
499            sasl_password: None,
500            sasl_kerberos_service_name: None,
501            sasl_kerberos_keytab: None,
502            sasl_kerberos_principal: None,
503            sasl_kerberos_min_time_before_relogin: None,
504            sasl_oathbearer_config: None,
505            sasl_oauthbearer_method: None,
506            sasl_oauthbearer_client_id: None,
507            sasl_oauthbearer_client_secret: None,
508            sasl_oauthbearer_token_endpoint_url: None,
509            sasl_oauthbearer_scope: None,
510            sasl_oauthbearer_extensions: None,
511        }
512    }
513
514    pub(crate) fn set_security_properties(&self, config: &mut ClientConfig) {
515        // AWS_MSK_IAM
516        if self.is_aws_msk_iam() {
517            config.set("security.protocol", "SASL_SSL");
518            config.set("sasl.mechanism", "OAUTHBEARER");
519            return;
520        }
521
522        // Security protocol
523        if let Some(security_protocol) = self.security_protocol.as_ref() {
524            config.set("security.protocol", security_protocol);
525        }
526
527        // SSL
528        if let Some(ssl_ca_location) = self.ssl_ca_location.as_ref() {
529            config.set("ssl.ca.location", ssl_ca_location);
530        }
531        if let Some(ssl_ca_pem) = self.ssl_ca_pem.as_ref() {
532            config.set("ssl.ca.pem", ssl_ca_pem);
533        }
534        if let Some(ssl_certificate_location) = self.ssl_certificate_location.as_ref() {
535            config.set("ssl.certificate.location", ssl_certificate_location);
536        }
537        if let Some(ssl_certificate_pem) = self.ssl_certificate_pem.as_ref() {
538            config.set("ssl.certificate.pem", ssl_certificate_pem);
539        }
540        if let Some(ssl_key_location) = self.ssl_key_location.as_ref() {
541            config.set("ssl.key.location", ssl_key_location);
542        }
543        if let Some(ssl_key_pem) = self.ssl_key_pem.as_ref() {
544            config.set("ssl.key.pem", ssl_key_pem);
545        }
546        if let Some(ssl_key_password) = self.ssl_key_password.as_ref() {
547            config.set("ssl.key.password", ssl_key_password);
548        }
549        if let Some(ssl_endpoint_identification_algorithm) =
550            self.ssl_endpoint_identification_algorithm.as_ref()
551        {
552            // accept only `none` and `http` here, let the sdk do the check
553            config.set(
554                "ssl.endpoint.identification.algorithm",
555                ssl_endpoint_identification_algorithm,
556            );
557        }
558
559        // SASL mechanism
560        if let Some(sasl_mechanism) = self.sasl_mechanism.as_ref() {
561            config.set("sasl.mechanism", sasl_mechanism);
562        }
563
564        // SASL/PLAIN & SASL/SCRAM
565        if let Some(sasl_username) = self.sasl_username.as_ref() {
566            config.set("sasl.username", sasl_username);
567        }
568        if let Some(sasl_password) = self.sasl_password.as_ref() {
569            config.set("sasl.password", sasl_password);
570        }
571
572        // SASL/GSSAPI
573        // Always override librdkafka's unquoted default. It is only run for GSSAPI, which is
574        // also librdkafka's default mechanism when `sasl.mechanism` is omitted.
575        config.set("sasl.kerberos.kinit.cmd", KINIT_CMD);
576        if let Some(sasl_kerberos_service_name) = self.sasl_kerberos_service_name.as_ref() {
577            config.set("sasl.kerberos.service.name", sasl_kerberos_service_name);
578        }
579        if let Some(sasl_kerberos_keytab) = self.sasl_kerberos_keytab.as_ref() {
580            config.set("sasl.kerberos.keytab", sasl_kerberos_keytab);
581        }
582        if let Some(sasl_kerberos_principal) = self.sasl_kerberos_principal.as_ref() {
583            config.set("sasl.kerberos.principal", sasl_kerberos_principal);
584        }
585        if let Some(sasl_kerberos_min_time_before_relogin) =
586            self.sasl_kerberos_min_time_before_relogin.as_ref()
587        {
588            config.set(
589                "sasl.kerberos.min.time.before.relogin",
590                sasl_kerberos_min_time_before_relogin,
591            );
592        }
593
594        // SASL/OAUTHBEARER
595        if let Some(sasl_oathbearer_config) = self.sasl_oathbearer_config.as_ref() {
596            config.set("sasl.oauthbearer.config", sasl_oathbearer_config);
597        }
598        if let Some(sasl_oauthbearer_method) = self.sasl_oauthbearer_method.as_ref() {
599            config.set("sasl.oauthbearer.method", sasl_oauthbearer_method);
600        }
601        if let Some(sasl_oauthbearer_client_id) = self.sasl_oauthbearer_client_id.as_ref() {
602            config.set("sasl.oauthbearer.client.id", sasl_oauthbearer_client_id);
603        }
604        if let Some(sasl_oauthbearer_client_secret) = self.sasl_oauthbearer_client_secret.as_ref() {
605            config.set(
606                "sasl.oauthbearer.client.secret",
607                sasl_oauthbearer_client_secret,
608            );
609        }
610        if let Some(sasl_oauthbearer_token_endpoint_url) =
611            self.sasl_oauthbearer_token_endpoint_url.as_ref()
612        {
613            config.set(
614                "sasl.oauthbearer.token.endpoint.url",
615                sasl_oauthbearer_token_endpoint_url,
616            );
617        }
618        if let Some(sasl_oauthbearer_scope) = self.sasl_oauthbearer_scope.as_ref() {
619            config.set("sasl.oauthbearer.scope", sasl_oauthbearer_scope);
620        }
621        if let Some(sasl_oauthbearer_extensions) = self.sasl_oauthbearer_extensions.as_ref() {
622            config.set("sasl.oauthbearer.extensions", sasl_oauthbearer_extensions);
623        }
624        // Only enable unsecured JWT when not using OIDC method.
625        if !self.is_oauthbearer_oidc() {
626            config.set("enable.sasl.oauthbearer.unsecure.jwt", "true");
627        }
628    }
629
630    pub(crate) fn is_oauthbearer_oidc(&self) -> bool {
631        self.sasl_oauthbearer_method
632            .as_deref()
633            .is_some_and(|m| m.eq_ignore_ascii_case("oidc"))
634    }
635
636    pub(crate) fn is_aws_msk_iam(&self) -> bool {
637        if let Some(sasl_mechanism) = self.sasl_mechanism.as_ref()
638            && sasl_mechanism == AWS_MSK_IAM_AUTH
639        {
640            true
641        } else {
642            false
643        }
644    }
645}
646
647#[derive(Clone, Debug, Deserialize, WithOptions)]
648pub struct PulsarCommon {
649    #[serde(rename = "topic", alias = "pulsar.topic")]
650    pub topic: String,
651
652    #[serde(rename = "service.url", alias = "pulsar.service.url")]
653    pub service_url: String,
654
655    #[serde(rename = "auth.token")]
656    pub auth_token: Option<String>,
657}
658
659impl EnforceSecret for PulsarCommon {
660    const ENFORCE_SECRET_PROPERTIES: Set<&'static str> = phf_set! {
661        "pulsar.auth.token",
662    };
663}
664
665#[derive(Clone, Debug, Deserialize, WithOptions)]
666pub struct PulsarOauthCommon {
667    #[serde(rename = "oauth.issuer.url")]
668    pub issuer_url: String,
669
670    #[serde(rename = "oauth.credentials.url")]
671    pub credentials_url: String,
672
673    #[serde(rename = "oauth.audience")]
674    pub audience: String,
675
676    #[serde(rename = "oauth.scope")]
677    pub scope: Option<String>,
678}
679
680fn create_credential_temp_file(credentials: &[u8]) -> std::io::Result<NamedTempFile> {
681    let mut f = NamedTempFile::new()?;
682    f.write_all(credentials)?;
683    f.as_file().sync_all()?;
684    Ok(f)
685}
686
687impl PulsarCommon {
688    pub(crate) async fn build_client(
689        &self,
690        oauth: &Option<PulsarOauthCommon>,
691        aws_auth_props: &AwsAuthProps,
692        operation_retry_options: Option<OperationRetryOptions>,
693    ) -> ConnectorResult<Pulsar<TokioExecutor>> {
694        let mut pulsar_builder = Pulsar::builder(&self.service_url, TokioExecutor);
695        let mut _temp_file = None; // Keep temp file alive
696
697        if let Some(oauth) = oauth.as_ref() {
698            let (credentials_url, temp_file) = self
699                .resolve_pulsar_credentials_url(oauth, aws_auth_props)
700                .await?;
701            _temp_file = temp_file;
702
703            let auth_params = OAuth2Params {
704                issuer_url: oauth.issuer_url.clone(),
705                credentials_url,
706                audience: Some(oauth.audience.clone()),
707                scope: oauth.scope.clone(),
708            };
709
710            pulsar_builder = pulsar_builder
711                .with_auth_provider(OAuth2Authentication::client_credentials(auth_params));
712        } else if let Some(auth_token) = &self.auth_token {
713            pulsar_builder = pulsar_builder.with_auth(Authentication {
714                name: "token".to_owned(),
715                data: Vec::from(auth_token.as_str()),
716            });
717        }
718
719        if let Some(operation_retry_options) = operation_retry_options {
720            tracing::info!(
721                max_retries = ?operation_retry_options.max_retries,
722                retry_delay_ms = operation_retry_options.retry_delay.as_millis(),
723                "applying Pulsar source operation retry override"
724            );
725            pulsar_builder = pulsar_builder.with_operation_retry_options(operation_retry_options);
726        }
727
728        let res = pulsar_builder.build().await.map_err(|e| anyhow!(e))?;
729        drop(_temp_file); // Explicitly drop temp file after client is built
730        Ok(res)
731    }
732
733    pub(crate) async fn resolve_pulsar_credentials_url(
734        &self,
735        oauth: &PulsarOauthCommon,
736        aws_auth_props: &AwsAuthProps,
737    ) -> ConnectorResult<(String, Option<NamedTempFile>)> {
738        // Try parsing as URL first
739        if let Ok(url) = Url::parse(&oauth.credentials_url) {
740            return self
741                .handle_pulsar_credentials_url(&url, aws_auth_props)
742                .await;
743        }
744
745        // If not a valid URL, check if it's an absolute file path
746        let path = Path::new(&oauth.credentials_url);
747        if !path.is_absolute() {
748            bail!("credentials_url must be a valid URL (s3://, file://) or an absolute file path");
749        }
750
751        // Verify the file exists
752        if !tokio::fs::try_exists(&oauth.credentials_url)
753            .await
754            .unwrap_or(false)
755        {
756            bail!("credentials file does not exist: {}", oauth.credentials_url);
757        }
758
759        // Return absolute path with file:// prefix
760        Ok((format!("file://{}", oauth.credentials_url), None))
761    }
762
763    pub(crate) async fn handle_pulsar_credentials_url(
764        &self,
765        url: &Url,
766        aws_auth_props: &AwsAuthProps,
767    ) -> ConnectorResult<(String, Option<NamedTempFile>)> {
768        match url.scheme() {
769            "s3" => {
770                let credentials = load_file_descriptor_from_s3(url, aws_auth_props).await?;
771                let temp_file = create_credential_temp_file(&credentials)
772                    .context("failed to create temp file for pulsar credentials")?;
773
774                let temp_path = temp_file
775                    .path()
776                    .to_str()
777                    .context("temp file path is not valid UTF-8")?;
778
779                Ok((format!("file://{}", temp_path), Some(temp_file)))
780            }
781            "file" => Ok((url.to_string(), None)),
782            _ => bail!(
783                "invalid credentials_url scheme '{}', only file://, s3://, and absolute file paths are supported",
784                url.scheme()
785            ),
786        }
787    }
788}
789
790#[serde_as]
791#[derive(Deserialize, Debug, Clone, WithOptions)]
792pub struct KinesisCommon {
793    #[serde(rename = "stream", alias = "kinesis.stream.name")]
794    pub stream_name: String,
795    #[serde(rename = "aws.region", alias = "kinesis.stream.region")]
796    pub stream_region: String,
797    #[serde(rename = "endpoint", alias = "kinesis.endpoint")]
798    pub endpoint: Option<String>,
799    #[serde(
800        rename = "aws.credentials.access_key_id",
801        alias = "kinesis.credentials.access"
802    )]
803    pub credentials_access_key: Option<String>,
804    #[serde(
805        rename = "aws.credentials.secret_access_key",
806        alias = "kinesis.credentials.secret"
807    )]
808    pub credentials_secret_access_key: Option<String>,
809    #[serde(
810        rename = "aws.credentials.session_token",
811        alias = "kinesis.credentials.session_token"
812    )]
813    pub session_token: Option<String>,
814    #[serde(rename = "aws.credentials.role.arn", alias = "kinesis.assumerole.arn")]
815    pub assume_role_arn: Option<String>,
816    #[serde(
817        rename = "aws.credentials.role.external_id",
818        alias = "kinesis.assumerole.external_id"
819    )]
820    pub assume_role_external_id: Option<String>,
821
822    // sdk options
823    #[serde(
824        rename = "kinesis.sdk.connect_timeout_ms",
825        default = "kinesis_default_connect_timeout_ms"
826    )]
827    #[serde_as(as = "DisplayFromStr")]
828    pub sdk_connect_timeout_ms: u64,
829
830    #[serde(
831        rename = "kinesis.sdk.read_timeout_ms",
832        default = "kinesis_default_read_timeout_ms"
833    )]
834    #[serde_as(as = "DisplayFromStr")]
835    pub sdk_read_timeout_ms: u64,
836
837    #[serde(
838        rename = "kinesis.sdk.operation_timeout_ms",
839        default = "kinesis_default_operation_timeout_ms"
840    )]
841    #[serde_as(as = "DisplayFromStr")]
842    pub sdk_operation_timeout_ms: u64,
843
844    #[serde(
845        rename = "kinesis.sdk.operation_attempt_timeout_ms",
846        default = "kinesis_default_operation_attempt_timeout_ms"
847    )]
848    #[serde_as(as = "DisplayFromStr")]
849    pub sdk_operation_attempt_timeout_ms: u64,
850
851    #[serde(
852        rename = "kinesis.sdk.max_retry_limit",
853        default = "kinesis_default_max_retry_limit"
854    )]
855    #[serde_as(as = "DisplayFromStr")]
856    pub sdk_max_retry_limit: u32,
857
858    #[serde(
859        rename = "kinesis.sdk.init_backoff_ms",
860        default = "kinesis_default_init_backoff_ms"
861    )]
862    #[serde_as(as = "DisplayFromStr")]
863    pub sdk_init_backoff_ms: u64,
864
865    #[serde(
866        rename = "kinesis.sdk.max_backoff_ms",
867        default = "kinesis_default_max_backoff_ms"
868    )]
869    #[serde_as(as = "DisplayFromStr")]
870    pub sdk_max_backoff_ms: u64,
871}
872
873#[derive(Debug)]
874pub struct KinesisAsyncSleepImpl;
875
876impl AsyncSleep for KinesisAsyncSleepImpl {
877    fn sleep(&self, duration: Duration) -> Sleep {
878        Sleep::new(async move { tokio::time::sleep(duration).await })
879    }
880}
881
882const fn kinesis_default_connect_timeout_ms() -> u64 {
883    10000
884}
885
886const fn kinesis_default_read_timeout_ms() -> u64 {
887    10000
888}
889
890const fn kinesis_default_operation_timeout_ms() -> u64 {
891    10000
892}
893
894const fn kinesis_default_operation_attempt_timeout_ms() -> u64 {
895    10000
896}
897
898const fn kinesis_default_init_backoff_ms() -> u64 {
899    1000
900}
901
902const fn kinesis_default_max_backoff_ms() -> u64 {
903    20000
904}
905
906const fn kinesis_default_max_retry_limit() -> u32 {
907    3
908}
909
910impl EnforceSecret for KinesisCommon {
911    const ENFORCE_SECRET_PROPERTIES: Set<&'static str> = phf_set! {
912        "kinesis.credentials.access",
913        "kinesis.credentials.secret",
914        "kinesis.credentials.session_token",
915    };
916}
917
918impl KinesisCommon {
919    pub(crate) async fn build_client(&self) -> ConnectorResult<KinesisClient> {
920        let config = AwsAuthProps {
921            region: Some(self.stream_region.clone()),
922            endpoint: self.endpoint.clone(),
923            access_key: self.credentials_access_key.clone(),
924            secret_key: self.credentials_secret_access_key.clone(),
925            session_token: self.session_token.clone(),
926            arn: self.assume_role_arn.clone(),
927            external_id: self.assume_role_external_id.clone(),
928            profile: Default::default(),
929            msk_signer_timeout_sec: Default::default(),
930        };
931        let aws_config = config.build_config().await?;
932        let mut builder = aws_sdk_kinesis::config::Builder::from(&aws_config);
933        {
934            // for timeout and retry config
935            let sleep_impl = SharedAsyncSleep::new(KinesisAsyncSleepImpl);
936            builder.set_sleep_impl(Some(sleep_impl));
937            let timeout_config = aws_smithy_types::timeout::TimeoutConfig::builder()
938                .connect_timeout(Duration::from_millis(self.sdk_connect_timeout_ms))
939                .read_timeout(Duration::from_millis(self.sdk_read_timeout_ms))
940                .operation_timeout(Duration::from_millis(self.sdk_operation_timeout_ms))
941                .operation_attempt_timeout(Duration::from_millis(
942                    self.sdk_operation_attempt_timeout_ms,
943                ))
944                .build();
945            builder.set_timeout_config(Some(timeout_config));
946
947            let retry_config = aws_smithy_types::retry::RetryConfig::standard()
948                .with_initial_backoff(Duration::from_millis(self.sdk_init_backoff_ms))
949                .with_max_backoff(Duration::from_millis(self.sdk_max_backoff_ms))
950                .with_max_attempts(self.sdk_max_retry_limit);
951            builder.set_retry_config(Some(retry_config));
952        }
953        if let Some(endpoint) = &config.endpoint {
954            builder = builder.endpoint_url(endpoint);
955        }
956        Ok(KinesisClient::from_conf(builder.build()))
957    }
958}
959
960/// Connection properties for NATS, used as a cache key for shared clients.
961/// This includes all properties that affect the connection itself (not stream/subject specific).
962#[derive(Debug, Clone, PartialEq, Eq, Hash)]
963pub struct NatsConnectionProps {
964    pub server_url: String,
965    pub connect_mode: String,
966    pub user: Option<String>,
967    pub password: Option<String>,
968    pub jwt: Option<String>,
969    pub nkey: Option<String>,
970}
971
972/// Shared NATS client cache.
973/// Client connections are cached as `Weak` pointers in the cache.
974/// NATS Connector can access this cache to reuse existing client connections,
975/// and avoid exhausting host machine ports.
976/// When reading from the cache, the connector should `upgrade` the weak pointer to an `Arc` reference.
977/// After all strong (Arc) references are dropped, the client connection will be cleaned up.
978/// Cache eviction naturally takes care of the dangling weak pointers.
979pub static SHARED_NATS_CLIENT: LazyLock<MokaCache<NatsConnectionProps, Weak<async_nats::Client>>> =
980    LazyLock::new(|| MokaCache::builder().build());
981
982#[serde_as]
983#[derive(Deserialize, Debug, Clone, WithOptions)]
984pub struct NatsCommon {
985    #[serde(rename = "server_url")]
986    pub server_url: String,
987    #[serde(rename = "subject")]
988    pub subject: String,
989    #[serde(rename = "connect_mode")]
990    pub connect_mode: String,
991    #[serde(rename = "username")]
992    pub user: Option<String>,
993    #[serde(rename = "password")]
994    pub password: Option<String>,
995    #[serde(rename = "jwt")]
996    pub jwt: Option<String>,
997    #[serde(rename = "nkey")]
998    pub nkey: Option<String>,
999    #[serde(rename = "max_bytes")]
1000    #[serde_as(as = "Option<DisplayFromStr>")]
1001    pub max_bytes: Option<i64>,
1002    #[serde(rename = "max_messages")]
1003    #[serde_as(as = "Option<DisplayFromStr>")]
1004    pub max_messages: Option<i64>,
1005    #[serde(rename = "max_messages_per_subject")]
1006    #[serde_as(as = "Option<DisplayFromStr>")]
1007    pub max_messages_per_subject: Option<i64>,
1008    #[serde(rename = "max_consumers")]
1009    #[serde_as(as = "Option<DisplayFromStr>")]
1010    pub max_consumers: Option<i32>,
1011    #[serde(rename = "max_message_size")]
1012    #[serde_as(as = "Option<DisplayFromStr>")]
1013    pub max_message_size: Option<i32>,
1014    #[serde(rename = "allow_create_stream", default)]
1015    #[serde_as(as = "DisplayFromStr")]
1016    pub allow_create_stream: bool,
1017}
1018
1019impl EnforceSecret for NatsCommon {
1020    const ENFORCE_SECRET_PROPERTIES: Set<&'static str> = phf_set! {
1021        "password",
1022        "jwt",
1023        "nkey",
1024    };
1025}
1026
1027impl NatsCommon {
1028    /// Extract connection properties that can be used as a cache key.
1029    pub fn connection_props(&self) -> NatsConnectionProps {
1030        NatsConnectionProps {
1031            server_url: self.server_url.clone(),
1032            connect_mode: self.connect_mode.clone(),
1033            user: self.user.clone(),
1034            password: self.password.clone(),
1035            jwt: self.jwt.clone(),
1036            nkey: self.nkey.clone(),
1037        }
1038    }
1039
1040    /// Build a new NATS client without caching.
1041    async fn build_client_inner(&self) -> ConnectorResult<async_nats::Client> {
1042        let mut connect_options = async_nats::ConnectOptions::new();
1043        match self.connect_mode.as_str() {
1044            "user_and_password" => {
1045                if let (Some(v_user), Some(v_password)) =
1046                    (self.user.as_ref(), self.password.as_ref())
1047                {
1048                    connect_options =
1049                        connect_options.user_and_password(v_user.into(), v_password.into())
1050                } else {
1051                    bail!(
1052                        "NATS connect mode `user_and_password` requires both `user` and `password`"
1053                    );
1054                }
1055            }
1056
1057            "credential" => {
1058                if let (Some(v_nkey), Some(v_jwt)) = (self.nkey.as_ref(), self.jwt.as_ref()) {
1059                    connect_options = connect_options
1060                        .credentials(&self.create_credential(v_nkey, v_jwt)?)
1061                        .expect("failed to parse static creds")
1062                } else {
1063                    bail!("NATS connect mode `credential` requires both `nkey` and `jwt`");
1064                }
1065            }
1066            "plain" => {}
1067            _ => {
1068                bail!(
1069                    "NATS connect mode must be one of `user_and_password`, `credential`, or `plain`"
1070                );
1071            }
1072        };
1073
1074        let servers = self.server_url.split(',').collect::<Vec<&str>>();
1075        let client = connect_options
1076            .connect(
1077                servers
1078                    .iter()
1079                    .map(|url| url.parse())
1080                    .collect::<Result<Vec<async_nats::ServerAddr>, _>>()?,
1081            )
1082            .await
1083            .context("failed to build the NATS client")
1084            .map_err(SinkError::Nats)?;
1085        Ok(client)
1086    }
1087
1088    /// Build a NATS client, attempting to reuse an existing cached client if available.
1089    /// See `SHARED_NATS_CLIENT` for more details.
1090    pub(crate) async fn build_client(&self) -> ConnectorResult<Arc<async_nats::Client>> {
1091        let connection_props = self.connection_props();
1092        let mut client: Option<Arc<async_nats::Client>> = None;
1093
1094        SHARED_NATS_CLIENT
1095            .entry_by_ref(&connection_props)
1096            .and_try_compute_with::<_, _, crate::error::ConnectorError>(|maybe_entry| async {
1097                if let Some(entry) = maybe_entry
1098                    && let entry_value = entry.into_value()
1099                    && let Some(existing_client) = entry_value.upgrade()
1100                {
1101                    match existing_client.connection_state() {
1102                        async_nats::connection::State::Connected => {
1103                            tracing::info!("reusing existing NATS client for {}", self.server_url);
1104                            client = Some(existing_client);
1105                            return Ok(Op::Nop);
1106                        }
1107                        _ => {
1108                            tracing::warn!(
1109                                server_url = self.server_url,
1110                                "existing NATS client is not connected",
1111                            );
1112                        }
1113                    }
1114                }
1115                tracing::info!(
1116                    server_url = self.server_url,
1117                    "no cached NATS client was found, or the cached client disconnected; building a new client"
1118                );
1119                let new_client = Arc::new(self.build_client_inner().await?);
1120                client = Some(new_client.clone());
1121                Ok(Op::Put(Arc::downgrade(&new_client)))
1122            })
1123            .await?;
1124
1125        Ok(client.expect("client should be set"))
1126    }
1127
1128    pub(crate) async fn build_context(&self) -> ConnectorResult<jetstream::Context> {
1129        let client = self.build_client().await?;
1130        let jetstream = async_nats::jetstream::new((*client).clone());
1131        Ok(jetstream)
1132    }
1133
1134    /// Build a `JetStream` context using a pre-existing client.
1135    pub(crate) fn build_context_from_client(
1136        client: &Arc<async_nats::Client>,
1137    ) -> jetstream::Context {
1138        async_nats::jetstream::new((**client).clone())
1139    }
1140
1141    /// Build a NATS `JetStream` consumer.
1142    ///
1143    /// If `existing_client` is provided, it will be used instead of creating/fetching a new one.
1144    /// This allows callers to reuse a client they already hold.
1145    pub(crate) async fn build_consumer(
1146        &self,
1147        stream: String,
1148        durable_consumer_name: String,
1149        split_id: String,
1150        start_sequence: NatsOffset,
1151        mut config: jetstream::consumer::pull::Config,
1152        existing_client: Option<Arc<async_nats::Client>>,
1153    ) -> ConnectorResult<(
1154        async_nats::jetstream::consumer::Consumer<async_nats::jetstream::consumer::pull::Config>,
1155        Arc<async_nats::Client>,
1156    )> {
1157        let client = match existing_client {
1158            Some(c) => c,
1159            None => self.build_client().await?,
1160        };
1161        let context = Self::build_context_from_client(&client);
1162        let stream = self.build_or_get_stream(context.clone(), stream).await?;
1163        let subject_name = self
1164            .subject
1165            .replace(',', "-")
1166            .replace(['.', '>', '*', ' ', '\t'], "_");
1167        let name = format!("risingwave-consumer-{}-{}", subject_name, split_id);
1168
1169        let deliver_policy = match start_sequence {
1170            NatsOffset::Earliest => DeliverPolicy::All,
1171            NatsOffset::Latest => DeliverPolicy::New,
1172            NatsOffset::SequenceNumber(v) => {
1173                // for compatibility, we do not write to any state table now
1174                let parsed = v
1175                    .parse::<u64>()
1176                    .context("failed to parse nats offset as sequence number")?;
1177                DeliverPolicy::ByStartSequence {
1178                    start_sequence: 1 + parsed,
1179                }
1180            }
1181            NatsOffset::Timestamp(v) => DeliverPolicy::ByStartTime {
1182                start_time: OffsetDateTime::from_unix_timestamp_nanos(v as i128 * 1_000_000)
1183                    .context("invalid timestamp for nats offset")?,
1184            },
1185            NatsOffset::None => DeliverPolicy::All,
1186        };
1187
1188        let consumer = match stream.get_consumer(&name).await {
1189            Ok(consumer) => consumer,
1190            _ => {
1191                stream
1192                    .get_or_create_consumer(&name, {
1193                        config.deliver_policy = deliver_policy;
1194                        config.durable_name = Some(durable_consumer_name);
1195                        config.filter_subjects =
1196                            self.subject.split(',').map(|s| s.to_owned()).collect();
1197                        config
1198                    })
1199                    .await?
1200            }
1201        };
1202        Ok((consumer, client))
1203    }
1204
1205    pub(crate) async fn build_or_get_stream(
1206        &self,
1207        jetstream: jetstream::Context,
1208        stream_str: String,
1209    ) -> ConnectorResult<jetstream::stream::Stream> {
1210        let subjects: Vec<String> = self.subject.split(',').map(|s| s.to_owned()).collect();
1211
1212        // In `SourceEnumerator`, we may create a stream
1213        // In `SourceReader`, the desired stream MUST exist
1214        if let Ok(mut stream_instance) = jetstream.get_stream(&stream_str).await {
1215            tracing::info!(
1216                "load existing nats stream ({:?}) with config {:?}",
1217                stream_str,
1218                stream_instance.info().await?
1219            );
1220            return Ok(stream_instance);
1221        }
1222
1223        if !self.allow_create_stream {
1224            return Err(anyhow!(
1225                "stream {} not found, set `allow_create_stream` to true to create a stream",
1226                stream_str
1227            )
1228            .into());
1229        }
1230
1231        let mut config = jetstream::stream::Config {
1232            name: stream_str.clone(),
1233            max_bytes: 1000000,
1234            subjects,
1235            ..Default::default()
1236        };
1237        if let Some(v) = self.max_bytes {
1238            config.max_bytes = v;
1239        }
1240        if let Some(v) = self.max_messages {
1241            config.max_messages = v;
1242        }
1243        if let Some(v) = self.max_messages_per_subject {
1244            config.max_messages_per_subject = v;
1245        }
1246        if let Some(v) = self.max_consumers {
1247            config.max_consumers = v;
1248        }
1249        if let Some(v) = self.max_message_size {
1250            config.max_message_size = v;
1251        }
1252        tracing::info!(
1253            "create nats stream ({:?}) with config {:?}",
1254            &stream_str,
1255            config
1256        );
1257        let stream = jetstream.get_or_create_stream(config).await?;
1258        Ok(stream)
1259    }
1260
1261    pub(crate) fn create_credential(&self, seed: &str, jwt: &str) -> ConnectorResult<String> {
1262        let creds = format!(
1263            "-----BEGIN NATS USER JWT-----\n{}\n------END NATS USER JWT------\n\n\
1264                         ************************* IMPORTANT *************************\n\
1265                         NKEY Seed printed below can be used to sign and prove identity.\n\
1266                         NKEYs are sensitive and should be treated as secrets.\n\n\
1267                         -----BEGIN USER NKEY SEED-----\n{}\n------END USER NKEY SEED------\n\n\
1268                         *************************************************************",
1269            jwt, seed
1270        );
1271        Ok(creds)
1272    }
1273}
1274
1275pub(crate) fn load_certs(
1276    certificates: &str,
1277) -> ConnectorResult<Vec<rustls_pki_types::CertificateDer<'static>>> {
1278    let cert_bytes = if let Some(path) = certificates.strip_prefix("fs://") {
1279        std::fs::read_to_string(path).map(|cert| cert.as_bytes().to_owned())?
1280    } else {
1281        certificates.as_bytes().to_owned()
1282    };
1283
1284    CertificateDer::pem_slice_iter(&cert_bytes)
1285        .collect::<Result<Vec<_>, _>>()
1286        .context("failed to parse certificates")
1287        .map_err(Into::into)
1288}
1289
1290pub(crate) fn load_private_key(
1291    certificate: &str,
1292) -> ConnectorResult<rustls_pki_types::PrivateKeyDer<'static>> {
1293    let cert_bytes = if let Some(path) = certificate.strip_prefix("fs://") {
1294        std::fs::read_to_string(path).map(|cert| cert.as_bytes().to_owned())?
1295    } else {
1296        certificate.as_bytes().to_owned()
1297    };
1298
1299    let cert = PrivatePkcs8KeyDer::pem_slice_iter(&cert_bytes)
1300        .next()
1301        .ok_or_else(|| anyhow!("No private key found"))?
1302        .context("failed to parse the private key")?;
1303    Ok(cert.into())
1304}
1305
1306#[serde_as]
1307#[derive(Deserialize, Debug, Clone, WithOptions)]
1308pub struct MongodbCommon {
1309    /// The URL of `MongoDB`
1310    #[serde(rename = "mongodb.url")]
1311    pub connect_uri: String,
1312    /// The collection name where data should be written to or read from. For sinks, the format is
1313    /// `db_name.collection_name`. Data can also be written to dynamic collections, see `collection.name.field`
1314    /// for more information.
1315    #[serde(rename = "collection.name")]
1316    pub collection_name: String,
1317}
1318
1319impl EnforceSecret for MongodbCommon {
1320    const ENFORCE_SECRET_PROPERTIES: Set<&'static str> = phf_set! {
1321        "mongodb.url"
1322    };
1323}
1324
1325impl MongodbCommon {
1326    pub(crate) async fn build_client(&self) -> ConnectorResult<mongodb::Client> {
1327        let client = mongodb::Client::with_uri_str(&self.connect_uri).await?;
1328
1329        Ok(client)
1330    }
1331}
1332
1333/// TCP keepalive knobs for long-lived Postgres clients, see `create_pg_client`.
1334#[serde_as]
1335#[derive(Debug, Clone, Deserialize, WithOptions)]
1336pub struct TcpKeepaliveConfig {
1337    #[serde(rename = "tcp.keepalive.idle", default = "default_tcp_keepalive_idle")]
1338    #[serde_as(as = "DisplayFromStr")]
1339    pub tcp_keepalive_idle: u32,
1340    #[serde(
1341        rename = "tcp.keepalive.interval",
1342        default = "default_tcp_keepalive_interval"
1343    )]
1344    #[serde_as(as = "DisplayFromStr")]
1345    pub tcp_keepalive_interval: u32,
1346    #[serde(
1347        rename = "tcp.keepalive.count",
1348        default = "default_tcp_keepalive_count"
1349    )]
1350    #[serde_as(as = "DisplayFromStr")]
1351    pub tcp_keepalive_count: u32,
1352}
1353
1354const fn default_tcp_keepalive_idle() -> u32 {
1355    10 * 60
1356}
1357
1358const fn default_tcp_keepalive_interval() -> u32 {
1359    10
1360}
1361
1362const fn default_tcp_keepalive_count() -> u32 {
1363    3
1364}
1365
1366/// librdkafka's default `kinit` command, overridden to single-quote the keytab and principal.
1367/// The default leaves them unquoted or double-quoted, so user-supplied values can inject shell
1368/// commands.
1369///
1370/// Default: <https://github.com/confluentinc/librdkafka/blob/v2.10.0/src/rdkafka_conf.c#L950-L960>
1371const KINIT_CMD: &str = "kinit -R -t '%{sasl.kerberos.keytab}' -k '%{sasl.kerberos.principal}' \
1372    || kinit -t '%{sasl.kerberos.keytab}' -k '%{sasl.kerberos.principal}'";
1373
1374/// Rejects values that could escape the quotes in [`KINIT_CMD`] or be parsed as a `kinit` flag.
1375fn deserialize_kinit_arg<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
1376where
1377    D: serde::Deserializer<'de>,
1378{
1379    let value = Option::<String>::deserialize(deserializer)?;
1380    if let Some(v) = &value
1381        && (v.contains('\'') || v.starts_with('-'))
1382    {
1383        return Err(serde::de::Error::custom(format!(
1384            "invalid Kerberos value `{v}`: must not contain `'` or start with `-`"
1385        )));
1386    }
1387    Ok(value)
1388}
1389
1390#[cfg(all(test, not(madsim)))]
1391mod tests {
1392    use super::*;
1393
1394    #[test]
1395    fn test_kinit_cmd_quoted_and_args_validated() {
1396        // The quoted command is set for every mechanism, including an omitted one, which
1397        // librdkafka treats as GSSAPI.
1398        for mechanism in [None, Some("GSSAPI"), Some("PLAIN")] {
1399            let mut props = KafkaConnectionProps::test_default();
1400            props.sasl_mechanism = mechanism.map(str::to_owned);
1401            let mut config = rdkafka::ClientConfig::new();
1402            props.set_security_properties(&mut config);
1403            assert_eq!(
1404                config.config_map().get("sasl.kerberos.kinit.cmd").unwrap(),
1405                KINIT_CMD
1406            );
1407        }
1408
1409        // Values that could escape the quotes or be parsed as a `kinit` flag are rejected.
1410        for key in [
1411            "properties.sasl.kerberos.principal",
1412            "properties.sasl.kerberos.keytab",
1413        ] {
1414            for bad in ["x'; id; '", "'", "-c/tmp/cache", "--help"] {
1415                let map = BTreeMap::from([
1416                    ("properties.bootstrap.server", "localhost:9092"),
1417                    (key, bad),
1418                ]);
1419                let result: Result<KafkaConnectionProps, _> =
1420                    serde_json::from_value(serde_json::to_value(map).unwrap());
1421                assert!(result.is_err(), "{key}={bad:?} should be rejected");
1422            }
1423        }
1424    }
1425
1426    #[test]
1427    fn test_oauthbearer_oidc_does_not_set_unsecure_jwt() {
1428        let mut props = KafkaConnectionProps::test_default();
1429        props.sasl_mechanism = Some("OAUTHBEARER".to_owned());
1430        props.sasl_oauthbearer_method = Some("oidc".to_owned());
1431        props.sasl_oauthbearer_client_id = Some("my-client".to_owned());
1432        props.sasl_oauthbearer_client_secret = Some("my-secret".to_owned());
1433        props.sasl_oauthbearer_token_endpoint_url =
1434            Some("https://idp.example.com/token".to_owned());
1435        props.sasl_oauthbearer_scope = Some("kafka".to_owned());
1436
1437        let mut config = rdkafka::ClientConfig::new();
1438        props.set_security_properties(&mut config);
1439
1440        let map = config.config_map();
1441        assert_eq!(map.get("sasl.mechanism").unwrap(), "OAUTHBEARER");
1442        assert_eq!(map.get("sasl.oauthbearer.method").unwrap(), "oidc");
1443        assert_eq!(map.get("sasl.oauthbearer.client.id").unwrap(), "my-client");
1444        assert_eq!(
1445            map.get("sasl.oauthbearer.client.secret").unwrap(),
1446            "my-secret"
1447        );
1448        assert_eq!(
1449            map.get("sasl.oauthbearer.token.endpoint.url").unwrap(),
1450            "https://idp.example.com/token"
1451        );
1452        assert_eq!(map.get("sasl.oauthbearer.scope").unwrap(), "kafka");
1453        assert!(
1454            !map.contains_key("enable.sasl.oauthbearer.unsecure.jwt"),
1455            "unsecure JWT must not be set when method=oidc"
1456        );
1457    }
1458
1459    #[test]
1460    fn test_default_oauthbearer_sets_unsecure_jwt() {
1461        let mut props = KafkaConnectionProps::test_default();
1462        props.sasl_mechanism = Some("OAUTHBEARER".to_owned());
1463        props.sasl_oathbearer_config = Some("principal=user".to_owned());
1464
1465        let mut config = rdkafka::ClientConfig::new();
1466        props.set_security_properties(&mut config);
1467
1468        let map = config.config_map();
1469        assert_eq!(map.get("sasl.mechanism").unwrap(), "OAUTHBEARER");
1470        assert_eq!(
1471            map.get("enable.sasl.oauthbearer.unsecure.jwt").unwrap(),
1472            "true"
1473        );
1474        assert!(!map.contains_key("sasl.oauthbearer.method"));
1475    }
1476
1477    #[test]
1478    fn test_aws_msk_iam_unaffected_by_oidc() {
1479        let mut props = KafkaConnectionProps::test_default();
1480        props.sasl_mechanism = Some("AWS_MSK_IAM".to_owned());
1481
1482        let mut config = rdkafka::ClientConfig::new();
1483        props.set_security_properties(&mut config);
1484
1485        let map = config.config_map();
1486        // MSK IAM takes the early-return path
1487        assert_eq!(map.get("security.protocol").unwrap(), "SASL_SSL");
1488        assert_eq!(map.get("sasl.mechanism").unwrap(), "OAUTHBEARER");
1489        // Should not have any OIDC or unsecure JWT settings
1490        assert!(!map.contains_key("sasl.oauthbearer.method"));
1491        assert!(!map.contains_key("enable.sasl.oauthbearer.unsecure.jwt"));
1492    }
1493
1494    #[test]
1495    fn test_oauthbearer_oidc_with_extensions() {
1496        let mut props = KafkaConnectionProps::test_default();
1497        props.sasl_mechanism = Some("OAUTHBEARER".to_owned());
1498        props.sasl_oauthbearer_method = Some("oidc".to_owned());
1499        props.sasl_oauthbearer_client_id = Some("client".to_owned());
1500        props.sasl_oauthbearer_client_secret = Some("".to_owned());
1501        props.sasl_oauthbearer_token_endpoint_url =
1502            Some("https://idp.example.com/token".to_owned());
1503        props.sasl_oauthbearer_extensions =
1504            Some("logicalCluster=lkc-abc,identityPoolId=pool-xyz".to_owned());
1505
1506        let mut config = rdkafka::ClientConfig::new();
1507        props.set_security_properties(&mut config);
1508
1509        let map = config.config_map();
1510        assert_eq!(
1511            map.get("sasl.oauthbearer.extensions").unwrap(),
1512            "logicalCluster=lkc-abc,identityPoolId=pool-xyz"
1513        );
1514    }
1515}