@@ -2,7 +2,8 @@ import { Kafka, logLevel, CompressionCodecs, CompressionTypes } from "kafkajs";
2
2
import SnappyCodec from "kafkajs-snappy" ;
3
3
import "@sensejs/kafkajs-zstd-support" ;
4
4
5
- import { LogMessageBuilder , requireDefined , randomId , getLog } from "juava" ;
5
+ import { readFileSync } from "fs" ;
6
+ import { isTruish , LogMessageBuilder , requireDefined , randomId , getLog } from "juava" ;
6
7
import JSON5 from "json5" ;
7
8
const log = getLog ( "kafka" ) ;
8
9
@@ -25,7 +26,7 @@ function translateLevel(l: logLevel): LogMessageBuilder {
25
26
26
27
export type KafkaCredentials = {
27
28
brokers : string [ ] | string ;
28
- ssl ?: boolean ;
29
+ ssl ?: boolean | Record < string , any > ;
29
30
sasl ?: {
30
31
mechanism : "scram-sha-256" | "scram-sha-512" ;
31
32
username : string ;
@@ -34,9 +35,37 @@ export type KafkaCredentials = {
34
35
} ;
35
36
36
37
export function getCredentialsFromEnv ( ) : KafkaCredentials {
38
+ const ssl = isTruish ( process . env . KAFKA_SSL ) ;
39
+ const sslSkipVerify = isTruish ( process . env . KAFKA_SSL_SKIP_VERIFY ) ;
40
+
41
+ let sslOption : KafkaCredentials [ "ssl" ] = undefined ;
42
+
43
+ if ( ssl ) {
44
+ if ( sslSkipVerify ) {
45
+ // TLS enabled, but server TLS certificate is not verified
46
+ sslOption = {
47
+ rejectUnauthorized : false ,
48
+ checkServerIdentity : ( ) => undefined ,
49
+ } ;
50
+ } else if ( process . env . KAFKA_SSL_CA ) {
51
+ // TLS enabled, server TLS certificate is verified using a custom CA certificate
52
+ sslOption = {
53
+ ca : process . env . KAFKA_SSL_CA ,
54
+ } ;
55
+ } else if ( process . env . KAFKA_SSL_CA_FILE ) {
56
+ // TLS enabled, server TLS certificate is verified using a custom CA certificate (loaded from a local file)
57
+ sslOption = {
58
+ ca : readFileSync ( process . env . KAFKA_SSL_CA_FILE , "utf-8" ) ,
59
+ } ;
60
+ } else {
61
+ // TLS enabled, no extra configurations
62
+ sslOption = true ;
63
+ }
64
+ }
65
+
37
66
return {
38
67
brokers : requireDefined ( process . env . KAFKA_BOOTSTRAP_SERVERS , "env KAFKA_BOOTSTRAP_SERVERS is required" ) . split ( "," ) ,
39
- ssl : process . env . KAFKA_SSL === "true" || process . env . KAFKA_SSL === "1" ,
68
+ ssl : sslOption ,
40
69
sasl : process . env . KAFKA_SASL ? JSON5 . parse ( process . env . KAFKA_SASL ) : undefined ,
41
70
} ;
42
71
}
@@ -57,13 +86,7 @@ export function connectToKafka(opts: { defaultAppId: string } & KafkaCredentials
57
86
// },
58
87
clientId : process . env . APPLICATION_ID || opts . defaultAppId ,
59
88
brokers : typeof opts . brokers === "string" ? opts . brokers . split ( "," ) : opts . brokers ,
60
- ssl : opts . ssl
61
- ? {
62
- rejectUnauthorized : false ,
63
- checkServerIdentity : ( ) => undefined ,
64
- }
65
- : undefined ,
66
-
89
+ ssl : opts . ssl ,
67
90
...sasl ,
68
91
} ) ;
69
92
}
0 commit comments