| 1 |
/* |
| 2 |
* librdkafka - The Apache Kafka C/C++ library |
| 3 |
* |
| 4 |
* Copyright (c) 2021-2022, Magnus Edenhill |
| 5 |
* 2023, Confluent Inc. |
| 6 |
|
| 7 |
* All rights reserved. |
| 8 |
* |
| 9 |
* Redistribution and use in source and binary forms, with or without |
| 10 |
* modification, are permitted provided that the following conditions are met: |
| 11 |
* |
| 12 |
* 1. Redistributions of source code must retain the above copyright notice, |
| 13 |
* this list of conditions and the following disclaimer. |
| 14 |
* 2. Redistributions in binary form must reproduce the above copyright notice, |
| 15 |
* this list of conditions and the following disclaimer in the documentation |
| 16 |
* and/or other materials provided with the distribution. |
| 17 |
* |
| 18 |
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| 19 |
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| 20 |
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| 21 |
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE |
| 22 |
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR |
| 23 |
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF |
| 24 |
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
| 25 |
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN |
| 26 |
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) |
| 27 |
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
| 28 |
* POSSIBILITY OF SUCH DAMAGE. |
| 29 |
*/ |
| 30 |
|
| 31 |
|
| 32 |
/** |
| 33 |
* Builtin SASL OAUTHBEARER OIDC support |
| 34 |
*/ |
| 35 |
#include "rdkafka_int.h" |
| 36 |
#include "rdkafka_sasl_int.h" |
| 37 |
#include "rdunittest.h" |
| 38 |
#include "cJSON.h" |
| 39 |
#include <curl/curl.h> |
| 40 |
#include "rdhttp.h" |
| 41 |
#include "rdkafka_sasl_oauthbearer_oidc.h" |
| 42 |
#include "rdbase64.h" |
| 43 |
|
| 44 |
|
| 45 |
/** |
| 46 |
* @brief Generate Authorization field for HTTP header. |
| 47 |
* The field contains base64-encoded string which |
| 48 |
* is generated from \p client_id and \p client_secret. |
| 49 |
* |
| 50 |
* @returns Return the authorization field. |
| 51 |
* |
| 52 |
* @locality Any thread. |
| 53 |
*/ |
| 54 |
static char * |
| 55 |
rd_kafka_oidc_client_credentials_build_auth_header(const char *client_id, |
| 56 |
const char *client_secret) { |
| 57 |
|
| 58 |
rd_chariov_t client_authorization_in; |
| 59 |
rd_chariov_t client_authorization_out; |
| 60 |
|
| 61 |
size_t authorization_base64_header_size; |
| 62 |
char *authorization_base64_header; |
| 63 |
|
| 64 |
client_authorization_in.size = |
| 65 |
strlen(client_id) + strlen(client_secret) + 2; |
| 66 |
client_authorization_in.ptr = rd_malloc(client_authorization_in.size); |
| 67 |
rd_snprintf(client_authorization_in.ptr, client_authorization_in.size, |
| 68 |
"%s:%s", client_id, client_secret); |
| 69 |
|
| 70 |
client_authorization_in.size--; |
| 71 |
rd_base64_encode(&client_authorization_in, &client_authorization_out); |
| 72 |
rd_assert(client_authorization_out.ptr); |
| 73 |
|
| 74 |
authorization_base64_header_size = |
| 75 |
strlen("Authorization: Basic ") + client_authorization_out.size + 1; |
| 76 |
authorization_base64_header = |
| 77 |
rd_malloc(authorization_base64_header_size); |
| 78 |
rd_snprintf(authorization_base64_header, |
| 79 |
authorization_base64_header_size, "Authorization: Basic %s", |
| 80 |
client_authorization_out.ptr); |
| 81 |
|
| 82 |
rd_free(client_authorization_in.ptr); |
| 83 |
rd_free(client_authorization_out.ptr); |
| 84 |
return authorization_base64_header; |
| 85 |
} |
| 86 |
|
| 87 |
|
| 88 |
/** |
| 89 |
* @brief Build headers for HTTP(S) requests based on \p client_id |
| 90 |
* and \p client_secret. The result will be returned in \p *headersp. |
| 91 |
* |
| 92 |
* @locality Any thread. |
| 93 |
*/ |
| 94 |
static void |
| 95 |
rd_kafka_oidc_client_credentials_build_headers(const char *client_id, |
| 96 |
const char *client_secret, |
| 97 |
struct curl_slist **headersp) { |
| 98 |
char *authorization_base64_header; |
| 99 |
|
| 100 |
authorization_base64_header = |
| 101 |
rd_kafka_oidc_client_credentials_build_auth_header(client_id, |
| 102 |
client_secret); |
| 103 |
|
| 104 |
*headersp = curl_slist_append(*headersp, "Accept: application/json"); |
| 105 |
*headersp = curl_slist_append(*headersp, authorization_base64_header); |
| 106 |
|
| 107 |
*headersp = curl_slist_append( |
| 108 |
*headersp, "Content-Type: application/x-www-form-urlencoded"); |
| 109 |
|
| 110 |
rd_free(authorization_base64_header); |
| 111 |
} |
| 112 |
|
| 113 |
/** |
| 114 |
* @brief The format of JWT is Header.Payload.Signature. |
| 115 |
* Extract and decode payloads from JWT \p src. |
| 116 |
* The decoded payloads will be returned in \p *bufplainp. |
| 117 |
* |
| 118 |
* @returns Return error message while decoding the payload. |
| 119 |
*/ |
| 120 |
static const char *rd_kafka_jwt_b64_decode_payload(const char *src, |
| 121 |
char **bufplainp) { |
| 122 |
char *converted_src; |
| 123 |
char *payload = NULL; |
| 124 |
|
| 125 |
const char *errstr = NULL; |
| 126 |
|
| 127 |
int i, padding, len; |
| 128 |
|
| 129 |
int payload_len; |
| 130 |
int nbytesdecoded; |
| 131 |
|
| 132 |
int payloads_start = 0; |
| 133 |
int payloads_end = 0; |
| 134 |
|
| 135 |
len = (int)strlen(src); |
| 136 |
converted_src = rd_malloc(len + 4); |
| 137 |
|
| 138 |
for (i = 0; i < len; i++) { |
| 139 |
switch (src[i]) { |
| 140 |
case '-': |
| 141 |
converted_src[i] = '+'; |
| 142 |
break; |
| 143 |
|
| 144 |
case '_': |
| 145 |
converted_src[i] = '/'; |
| 146 |
break; |
| 147 |
|
| 148 |
case '.': |
| 149 |
if (payloads_start == 0) |
| 150 |
payloads_start = i + 1; |
| 151 |
else { |
| 152 |
if (payloads_end > 0) { |
| 153 |
errstr = |
| 154 |
"The token is invalid with more " |
| 155 |
"than 2 delimiters"; |
| 156 |
goto done; |
| 157 |
} |
| 158 |
payloads_end = i; |
| 159 |
} |
| 160 |
/* FALLTHRU */ |
| 161 |
|
| 162 |
default: |
| 163 |
converted_src[i] = src[i]; |
| 164 |
} |
| 165 |
} |
| 166 |
|
| 167 |
if (payloads_start == 0 || payloads_end == 0) { |
| 168 |
errstr = "The token is invalid with less than 2 delimiters"; |
| 169 |
goto done; |
| 170 |
} |
| 171 |
|
| 172 |
payload_len = payloads_end - payloads_start; |
| 173 |
payload = rd_malloc(payload_len + 4); |
| 174 |
strncpy(payload, (converted_src + payloads_start), payload_len); |
| 175 |
|
| 176 |
padding = 4 - (payload_len % 4); |
| 177 |
if (padding < 4) { |
| 178 |
while (padding--) |
| 179 |
payload[payload_len++] = '='; |
| 180 |
} |
| 181 |
|
| 182 |
nbytesdecoded = ((payload_len + 3) / 4) * 3; |
| 183 |
*bufplainp = rd_malloc(nbytesdecoded + 1); |
| 184 |
|
| 185 |
if (EVP_DecodeBlock((uint8_t *)(*bufplainp), (uint8_t *)payload, |
| 186 |
(int)payload_len) == -1) { |
| 187 |
errstr = "Failed to decode base64 payload"; |
| 188 |
} |
| 189 |
|
| 190 |
done: |
| 191 |
RD_IF_FREE(payload, rd_free); |
| 192 |
RD_IF_FREE(converted_src, rd_free); |
| 193 |
return errstr; |
| 194 |
} |
| 195 |
|
| 196 |
/** |
| 197 |
* @brief Build post_fields with \p scope. |
| 198 |
* The format of the post_fields is |
| 199 |
* `grant_type=client_credentials&scope=scope` |
| 200 |
* The post_fields will be returned in \p *post_fields. |
| 201 |
* The post_fields_size will be returned in \p post_fields_size. |
| 202 |
* |
| 203 |
*/ |
| 204 |
static void |
| 205 |
rd_kafka_oidc_client_credentials_build_post_fields(const char *scope, |
| 206 |
char **post_fields, |
| 207 |
size_t *post_fields_size) { |
| 208 |
size_t scope_size = 0; |
| 209 |
|
| 210 |
if (scope) |
| 211 |
scope_size = strlen(scope); |
| 212 |
if (scope_size == 0) { |
| 213 |
*post_fields = rd_strdup("grant_type=client_credentials"); |
| 214 |
*post_fields_size = strlen("grant_type=client_credentials"); |
| 215 |
} else { |
| 216 |
*post_fields_size = |
| 217 |
strlen("grant_type=client_credentials&scope=") + scope_size; |
| 218 |
*post_fields = rd_malloc(*post_fields_size + 1); |
| 219 |
rd_snprintf(*post_fields, *post_fields_size + 1, |
| 220 |
"grant_type=client_credentials&scope=%s", scope); |
| 221 |
} |
| 222 |
} |
| 223 |
|
| 224 |
/** |
| 225 |
* @brief Get JWT algorithm label string for the specified signing algorithm. |
| 226 |
* |
| 227 |
* @param token_signing_algo The algorithm enum value |
| 228 |
* |
| 229 |
* @returns String representation of the algorithm. |
| 230 |
* |
| 231 |
* @locality Any thread. |
| 232 |
*/ |
| 233 |
static char *rd_kafka_oidc_assertion_get_algo_label( |
| 234 |
const rd_kafka_oauthbearer_assertion_algorithm_t token_signing_algo) { |
| 235 |
switch (token_signing_algo) { |
| 236 |
case RD_KAFKA_SASL_OAUTHBEARER_ASSERTION_ALGORITHM_RS256: |
| 237 |
return "RS256"; |
| 238 |
case RD_KAFKA_SASL_OAUTHBEARER_ASSERTION_ALGORITHM_ES256: |
| 239 |
return "ES256"; |
| 240 |
default: |
| 241 |
rd_assert(!*"Unknown JOSE algorithm"); |
| 242 |
return NULL; |
| 243 |
} |
| 244 |
} |
| 245 |
|
| 246 |
/** |
| 247 |
* @brief Parse a JWT template file and extract header and payload JSON |
| 248 |
* objects. |
| 249 |
* |
| 250 |
* Reads and parses the JWT template file, which should contain a JSON object |
| 251 |
* with "header" and "payload" properties. |
| 252 |
* |
| 253 |
* @param rk |
| 254 |
* @param jwt_template_file_path Path to the template file |
| 255 |
* @param header Pointer to store the parsed header JSON object |
| 256 |
* @param payload Pointer to store the parsed payload JSON object |
| 257 |
* |
| 258 |
* @returns 0 on success, -1 on failure |
| 259 |
* |
| 260 |
* @locality Any thread. |
| 261 |
*/ |
| 262 |
static int |
| 263 |
rd_kafka_oidc_assertion_parse_template_file(rd_kafka_t *rk, |
| 264 |
const char *jwt_template_file_path, |
| 265 |
cJSON **header, |
| 266 |
cJSON **payload) { |
| 267 |
char *template_content = NULL; |
| 268 |
cJSON *template_json = NULL; |
| 269 |
int ret = -1; |
| 270 |
size_t file_size; |
| 271 |
|
| 272 |
*header = NULL; |
| 273 |
*payload = NULL; |
| 274 |
|
| 275 |
template_content = |
| 276 |
rd_file_read(jwt_template_file_path, &file_size, 1024 * 1024); |
| 277 |
if (!template_content) { |
| 278 |
rd_kafka_log(rk, LOG_ERR, "JWT", |
| 279 |
"Failed to open JWT template file: %s", |
| 280 |
jwt_template_file_path); |
| 281 |
return -1; |
| 282 |
} |
| 283 |
|
| 284 |
if (file_size == 0) { |
| 285 |
rd_kafka_log(rk, LOG_ERR, "JWT", |
| 286 |
"JWT template file is empty or invalid"); |
| 287 |
rd_free(template_content); |
| 288 |
return -1; |
| 289 |
} |
| 290 |
|
| 291 |
template_json = cJSON_Parse((char *)template_content); |
| 292 |
if (!template_json) { |
| 293 |
rd_kafka_log(rk, LOG_ERR, "JWT", |
| 294 |
"Failed to parse JWT template JSON"); |
| 295 |
goto cleanup; |
| 296 |
} |
| 297 |
|
| 298 |
cJSON *header_item = cJSON_GetObjectItem(template_json, "header"); |
| 299 |
cJSON *payload_item = cJSON_GetObjectItem(template_json, "payload"); |
| 300 |
|
| 301 |
if (!header_item || !payload_item) { |
| 302 |
rd_kafka_log(rk, LOG_ERR, "JWT", |
| 303 |
"JWT template must contain both 'header' " |
| 304 |
"and 'payload' objects"); |
| 305 |
goto cleanup; |
| 306 |
} |
| 307 |
|
| 308 |
*header = cJSON_Duplicate(header_item, 1); |
| 309 |
*payload = cJSON_Duplicate(payload_item, 1); |
| 310 |
|
| 311 |
if (!*header || !*payload) { |
| 312 |
rd_kafka_log(rk, LOG_ERR, "JWT", |
| 313 |
"Failed to duplicate header or payload objects"); |
| 314 |
if (*header) { |
| 315 |
cJSON_Delete(*header); |
| 316 |
*header = NULL; |
| 317 |
} |
| 318 |
goto cleanup; |
| 319 |
} |
| 320 |
|
| 321 |
ret = 0; |
| 322 |
|
| 323 |
cleanup: |
| 324 |
if (template_content) |
| 325 |
rd_free(template_content); |
| 326 |
if (template_json) |
| 327 |
cJSON_Delete(template_json); |
| 328 |
|
| 329 |
return ret; |
| 330 |
} |
| 331 |
|
| 332 |
/** |
| 333 |
* @brief Create JWT assertion. |
| 334 |
* |
| 335 |
* Creates a JWT token signed with the specified private key using the |
| 336 |
* algorithm specified. The token can be created from a template file or |
| 337 |
* will create a minimal default token if no template is provided. |
| 338 |
* |
| 339 |
* @param rk The rd_kafka_t instance for logging |
| 340 |
* @param private_key_pem PEM formatted private key string (mutually exclusive |
| 341 |
* with key_file_location) |
| 342 |
* @param key_file_location Path to private key file (mutually exclusive with |
| 343 |
* private_key_pem) |
| 344 |
* @param passphrase Optional passphrase for encrypted private key |
| 345 |
* @param token_signing_algo Algorithm to use for signing (RS256 or ES256) |
| 346 |
* @param jwt_template_file Optional path to JWT template file |
| 347 |
* @param subject Optional subject claim value. |
| 348 |
* @param issuer Optional issuer claim value. |
| 349 |
* @param audience Optional audience claim value. |
| 350 |
* @param nbf `nbf` claim value to express seconds of validity in the past. |
| 351 |
* @param exp `exp` claim value to express seconds of validity in the future. |
| 352 |
* @param jti_include Whether to include a JTI claim (UUID) |
| 353 |
* |
| 354 |
* @returns Newly allocated JWT string, caller must free with rd_free(). NULL on |
| 355 |
* error. |
| 356 |
* |
| 357 |
* @locality Any thread. |
| 358 |
*/ |
| 359 |
static char *rd_kafka_oidc_assertion_create( |
| 360 |
rd_kafka_t *rk, |
| 361 |
const char *private_key_pem, |
| 362 |
const char *key_file_location, |
| 363 |
const char *passphrase, |
| 364 |
const rd_kafka_oauthbearer_assertion_algorithm_t token_signing_algo, |
| 365 |
const char *jwt_template_file, |
| 366 |
const char *subject, |
| 367 |
const char *issuer, |
| 368 |
const char *audience, |
| 369 |
const int nbf, |
| 370 |
const int exp, |
| 371 |
const rd_bool_t jti_include) { |
| 372 |
|
| 373 |
char *encoded_header = NULL; |
| 374 |
char *encoded_payload = NULL; |
| 375 |
char *encoded_signature = NULL; |
| 376 |
char *unsigned_token = NULL; |
| 377 |
char *result = NULL; |
| 378 |
char *header_str = NULL; |
| 379 |
char *payload_str = NULL; |
| 380 |
EVP_PKEY *pkey = NULL; |
| 381 |
BIO *bio = NULL; |
| 382 |
cJSON *header_json_obj = NULL; |
| 383 |
cJSON *payload_json_obj = NULL; |
| 384 |
EVP_MD_CTX *mdctx = NULL; |
| 385 |
unsigned char *sig = NULL; |
| 386 |
rd_chariov_t header_iov; |
| 387 |
rd_chariov_t payload_iov; |
| 388 |
rd_chariov_t sig_iov; |
| 389 |
rd_kafka_Uuid_t jti_uuid; |
| 390 |
char *jti_uuid_str = NULL; |
| 391 |
|
| 392 |
rd_ts_t issued_at = rd_uclock() / 1000000; |
| 393 |
rd_ts_t not_before = issued_at - nbf; |
| 394 |
rd_ts_t expiration_time = issued_at + exp; |
| 395 |
|
| 396 |
if (jwt_template_file) { |
| 397 |
if (rd_kafka_oidc_assertion_parse_template_file( |
| 398 |
rk, jwt_template_file, &header_json_obj, |
| 399 |
&payload_json_obj) != 0) { |
| 400 |
rd_kafka_log(rk, LOG_ERR, "JWT", |
| 401 |
"Failed to process JWT template file %s", |
| 402 |
jwt_template_file); |
| 403 |
return NULL; |
| 404 |
} |
| 405 |
} else { |
| 406 |
header_json_obj = cJSON_CreateObject(); |
| 407 |
payload_json_obj = cJSON_CreateObject(); |
| 408 |
} |
| 409 |
|
| 410 |
/* Add required header fields */ |
| 411 |
cJSON_DeleteItemFromObjectCaseSensitive(header_json_obj, "alg"); |
| 412 |
cJSON_DeleteItemFromObjectCaseSensitive(header_json_obj, "typ"); |
| 413 |
cJSON_DeleteItemFromObjectCaseSensitive(payload_json_obj, "iat"); |
| 414 |
cJSON_DeleteItemFromObjectCaseSensitive(payload_json_obj, "exp"); |
| 415 |
cJSON_DeleteItemFromObjectCaseSensitive(payload_json_obj, "nbf"); |
| 416 |
cJSON_AddStringToObject( |
| 417 |
header_json_obj, "alg", |
| 418 |
rd_kafka_oidc_assertion_get_algo_label(token_signing_algo)); |
| 419 |
cJSON_AddStringToObject(header_json_obj, "typ", "JWT"); |
| 420 |
|
| 421 |
/* Add required payload fields */ |
| 422 |
cJSON_AddNumberToObject(payload_json_obj, "iat", (double)issued_at); |
| 423 |
cJSON_AddNumberToObject(payload_json_obj, "exp", |
| 424 |
(double)expiration_time); |
| 425 |
cJSON_AddNumberToObject(payload_json_obj, "nbf", (double)not_before); |
| 426 |
|
| 427 |
if (subject) { |
| 428 |
cJSON_DeleteItemFromObjectCaseSensitive(payload_json_obj, |
| 429 |
"sub"); |
| 430 |
cJSON_AddStringToObject(payload_json_obj, "sub", subject); |
| 431 |
} |
| 432 |
|
| 433 |
if (issuer) { |
| 434 |
cJSON_DeleteItemFromObjectCaseSensitive(payload_json_obj, |
| 435 |
"iss"); |
| 436 |
cJSON_AddStringToObject(payload_json_obj, "iss", issuer); |
| 437 |
} |
| 438 |
|
| 439 |
if (audience) { |
| 440 |
cJSON_DeleteItemFromObjectCaseSensitive(payload_json_obj, |
| 441 |
"aud"); |
| 442 |
cJSON_AddStringToObject(payload_json_obj, "aud", audience); |
| 443 |
} |
| 444 |
|
| 445 |
if (jti_include) { |
| 446 |
jti_uuid = rd_kafka_Uuid_random(); |
| 447 |
jti_uuid_str = rd_kafka_Uuid_str(&jti_uuid); |
| 448 |
cJSON_DeleteItemFromObjectCaseSensitive(payload_json_obj, |
| 449 |
"jti"); |
| 450 |
cJSON_AddStringToObject(payload_json_obj, "jti", jti_uuid_str); |
| 451 |
rd_free(jti_uuid_str); |
| 452 |
} |
| 453 |
|
| 454 |
header_str = cJSON_PrintUnformatted(header_json_obj); |
| 455 |
payload_str = cJSON_PrintUnformatted(payload_json_obj); |
| 456 |
|
| 457 |
if (!header_str || !payload_str) { |
| 458 |
rd_kafka_log(rk, LOG_ERR, "JWT", |
| 459 |
"Failed to convert template objects to JSON"); |
| 460 |
goto cleanup; |
| 461 |
} |
| 462 |
|
| 463 |
header_iov.ptr = header_str; |
| 464 |
header_iov.size = strlen(header_str); |
| 465 |
encoded_header = rd_base64_encode_str_urlsafe(&header_iov); |
| 466 |
|
| 467 |
payload_iov.ptr = payload_str; |
| 468 |
payload_iov.size = strlen(payload_str); |
| 469 |
encoded_payload = rd_base64_encode_str_urlsafe(&payload_iov); |
| 470 |
if (!encoded_header || !encoded_payload) |
| 471 |
goto cleanup; |
| 472 |
|
| 473 |
size_t unsigned_token_len = |
| 474 |
strlen(encoded_header) + strlen(encoded_payload) + 2; |
| 475 |
unsigned_token = rd_malloc(unsigned_token_len); |
| 476 |
|
| 477 |
if (!unsigned_token) |
| 478 |
goto cleanup; |
| 479 |
rd_snprintf(unsigned_token, unsigned_token_len, "%s.%s", encoded_header, |
| 480 |
encoded_payload); |
| 481 |
|
| 482 |
if (private_key_pem) { |
| 483 |
bio = BIO_new_mem_buf((void *)private_key_pem, -1); |
| 484 |
} else if (key_file_location) { |
| 485 |
bio = BIO_new_file(key_file_location, "r"); |
| 486 |
} |
| 487 |
|
| 488 |
if (!bio) { |
| 489 |
rd_kafka_log(rk, LOG_ERR, "JWT", |
| 490 |
"Failed to create BIO for private key"); |
| 491 |
goto cleanup; |
| 492 |
} |
| 493 |
|
| 494 |
if (passphrase) { |
| 495 |
pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL, |
| 496 |
(void *)passphrase); |
| 497 |
} else { |
| 498 |
pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL); |
| 499 |
} |
| 500 |
BIO_free(bio); |
| 501 |
bio = NULL; |
| 502 |
|
| 503 |
if (!pkey) { |
| 504 |
rd_kafka_log(rk, LOG_ERR, "JWT", "Failed to load private key"); |
| 505 |
goto cleanup; |
| 506 |
} |
| 507 |
|
| 508 |
mdctx = EVP_MD_CTX_new(); |
| 509 |
if (!mdctx) { |
| 510 |
rd_kafka_log(rk, LOG_ERR, "JWT", |
| 511 |
"Failed to create message digest context"); |
| 512 |
goto cleanup; |
| 513 |
} |
| 514 |
|
| 515 |
const EVP_MD *md = EVP_sha256(); /* Both RS256 and ES256 use SHA-256 */ |
| 516 |
|
| 517 |
if (EVP_DigestSignInit(mdctx, NULL, md, NULL, pkey) != 1) { |
| 518 |
rd_kafka_log(rk, LOG_ERR, "JWT", |
| 519 |
"Failed to initialize signing context"); |
| 520 |
goto cleanup; |
| 521 |
} |
| 522 |
|
| 523 |
if (EVP_DigestSignUpdate(mdctx, unsigned_token, |
| 524 |
strlen(unsigned_token)) != 1) { |
| 525 |
rd_kafka_log(rk, LOG_ERR, "JWT", |
| 526 |
"Failed to update digest with token data"); |
| 527 |
goto cleanup; |
| 528 |
} |
| 529 |
|
| 530 |
size_t siglen = 0; |
| 531 |
if (EVP_DigestSignFinal(mdctx, NULL, &siglen) != 1) { |
| 532 |
rd_kafka_log(rk, LOG_ERR, "JWT", |
| 533 |
"Failed to get signature length"); |
| 534 |
goto cleanup; |
| 535 |
} |
| 536 |
|
| 537 |
sig = rd_malloc(siglen); |
| 538 |
if (!sig) { |
| 539 |
rd_kafka_log(rk, LOG_ERR, "JWT", |
| 540 |
"Failed to allocate memory for signature"); |
| 541 |
goto cleanup; |
| 542 |
} |
| 543 |
|
| 544 |
if (EVP_DigestSignFinal(mdctx, sig, &siglen) != 1) { |
| 545 |
rd_kafka_log(rk, LOG_ERR, "JWT", "Failed to create signature"); |
| 546 |
goto cleanup; |
| 547 |
} |
| 548 |
|
| 549 |
sig_iov.ptr = (char *)sig; |
| 550 |
sig_iov.size = siglen; |
| 551 |
encoded_signature = rd_base64_encode_str_urlsafe(&sig_iov); |
| 552 |
|
| 553 |
if (!encoded_signature) |
| 554 |
goto cleanup; |
| 555 |
|
| 556 |
size_t jwt_len = strlen(encoded_header) + strlen(encoded_payload) + |
| 557 |
strlen(encoded_signature) + 3; |
| 558 |
result = rd_malloc(jwt_len); |
| 559 |
if (!result) |
| 560 |
goto cleanup; |
| 561 |
rd_snprintf(result, jwt_len, "%s.%s.%s", encoded_header, |
| 562 |
encoded_payload, encoded_signature); |
| 563 |
|
| 564 |
cleanup: |
| 565 |
if (encoded_header) |
| 566 |
rd_free(encoded_header); |
| 567 |
if (encoded_payload) |
| 568 |
rd_free(encoded_payload); |
| 569 |
if (encoded_signature) |
| 570 |
rd_free(encoded_signature); |
| 571 |
if (unsigned_token) |
| 572 |
rd_free(unsigned_token); |
| 573 |
if (sig) |
| 574 |
rd_free(sig); |
| 575 |
|
| 576 |
if (header_json_obj) { |
| 577 |
if (header_str) |
| 578 |
free(header_str); /* cJSON_PrintUnformatted uses malloc |
| 579 |
*/ |
| 580 |
cJSON_Delete(header_json_obj); |
| 581 |
} else if (header_str) { |
| 582 |
rd_free(header_str); /* rd_malloc was used */ |
| 583 |
} |
| 584 |
|
| 585 |
if (payload_json_obj) { |
| 586 |
if (payload_str) |
| 587 |
free(payload_str); /* cJSON_PrintUnformatted uses malloc |
| 588 |
*/ |
| 589 |
cJSON_Delete(payload_json_obj); |
| 590 |
} else if (payload_str) { |
| 591 |
rd_free(payload_str); /* rd_malloc was used */ |
| 592 |
} |
| 593 |
|
| 594 |
if (pkey) |
| 595 |
EVP_PKEY_free(pkey); |
| 596 |
if (mdctx) |
| 597 |
EVP_MD_CTX_free(mdctx); |
| 598 |
|
| 599 |
return result; |
| 600 |
} |
| 601 |
|
| 602 |
|
| 603 |
/** |
| 604 |
* @brief Build request body for JWT bearer token request. |
| 605 |
* |
| 606 |
* Creates a URL-encoded request body for token exchange with the JWT assertion |
| 607 |
* and optional scope. |
| 608 |
* |
| 609 |
* @param assertion The JWT assertion to include in the request. |
| 610 |
* @param scope Optional scope to include in the request (will be URL encoded). |
| 611 |
* |
| 612 |
* @returns Newly allocated string with the URL-encoded request body. |
| 613 |
* Caller must free with rd_free(). NULL on memory allocation failure. |
| 614 |
* |
| 615 |
* @locality Any thread. |
| 616 |
*/ |
| 617 |
static char *rd_kafka_oidc_jwt_bearer_build_request_body(const char *assertion, |
| 618 |
const char *scope) { |
| 619 |
const char *assertion_prefix = |
| 620 |
"grant_type=urn:ietf:params:oauth:" |
| 621 |
"grant-type:jwt-bearer" |
| 622 |
"&assertion="; |
| 623 |
int assertion_prefix_len = strlen(assertion_prefix) + strlen(assertion); |
| 624 |
int body_size = assertion_prefix_len + 1; |
| 625 |
char *scope_escaped = NULL; |
| 626 |
if (scope) { |
| 627 |
scope_escaped = curl_easy_escape(NULL, scope, 0); |
| 628 |
body_size += strlen("&scope=") + strlen(scope_escaped); |
| 629 |
} |
| 630 |
|
| 631 |
char *body = rd_malloc(body_size); |
| 632 |
|
| 633 |
rd_snprintf(body, body_size, "%s%s", assertion_prefix, assertion); |
| 634 |
if (scope) { |
| 635 |
rd_snprintf(&body[assertion_prefix_len], |
| 636 |
body_size - assertion_prefix_len, "&scope=%s", |
| 637 |
scope_escaped); |
| 638 |
rd_free(scope_escaped); |
| 639 |
} |
| 640 |
return body; |
| 641 |
} |
| 642 |
|
| 643 |
/** |
| 644 |
* @brief JWT assertion from file |
| 645 |
* |
| 646 |
* @param file_path Path to the file containing the JWT assertion. |
| 647 |
* |
| 648 |
* @returns Newly allocated string with the JWT assertion. |
| 649 |
* Caller must free with rd_free(). NULL on error. |
| 650 |
*/ |
| 651 |
static char *rd_kafka_oidc_assertion_read_from_file(const char *file_path) { |
| 652 |
if (!file_path) |
| 653 |
return NULL; |
| 654 |
const size_t max_size = 1024 * 1024; /* 1MB limit */ |
| 655 |
return rd_file_read(file_path, NULL, max_size); |
| 656 |
} |
| 657 |
|
| 658 |
/** |
| 659 |
* @brief Try to validate a token field from the JSON response. |
| 660 |
* Extracts and validates the token, then decodes its payload to get |
| 661 |
* subject and expiration. |
| 662 |
* |
| 663 |
* @param rk The rd_kafka_t instance |
| 664 |
* @param json The JSON response from the token endpoint |
| 665 |
* @param field_name The name of the field to extract (e.g., "access_token" or |
| 666 |
* "id_token") |
| 667 |
* @param token_out Pointer to store the extracted token |
| 668 |
* @param sub_out Pointer to store the subject from the token |
| 669 |
* @param exp_out Pointer to store the expiration from the token |
| 670 |
* @param errstr_out Buffer to store error message |
| 671 |
* @param errstr_size Size of error message buffer |
| 672 |
* |
| 673 |
* @returns The extracted token or NULL on failure. |
| 674 |
*/ |
| 675 |
static char *rd_kafka_oidc_token_try_validate(cJSON *json, |
| 676 |
const char *field, |
| 677 |
const char *sub_claim_name, |
| 678 |
char **sub, |
| 679 |
double *exp, |
| 680 |
char *errstr, |
| 681 |
size_t errstr_size) { |
| 682 |
cJSON *access_token_json, *jwt_exp, *jwt_sub, *payloads = NULL; |
| 683 |
char *jwt_token = NULL, *decoded_payloads = NULL; |
| 684 |
const char *decode_errstr = NULL; |
| 685 |
*sub = NULL; |
| 686 |
|
| 687 |
access_token_json = cJSON_GetObjectItem(json, field); |
| 688 |
|
| 689 |
if (!access_token_json) { |
| 690 |
rd_snprintf(errstr, errstr_size, |
| 691 |
"Expected JSON response with \"%s\" field", field); |
| 692 |
goto fail; |
| 693 |
} |
| 694 |
|
| 695 |
jwt_token = cJSON_GetStringValue(access_token_json); |
| 696 |
if (!jwt_token) { |
| 697 |
rd_snprintf(errstr, errstr_size, |
| 698 |
"Expected token as a string value"); |
| 699 |
goto fail; |
| 700 |
} |
| 701 |
|
| 702 |
decode_errstr = |
| 703 |
rd_kafka_jwt_b64_decode_payload(jwt_token, &decoded_payloads); |
| 704 |
if (decode_errstr != NULL) { |
| 705 |
rd_snprintf(errstr, errstr_size, |
| 706 |
"Failed to decode JWT payload: %s", decode_errstr); |
| 707 |
goto fail; |
| 708 |
} |
| 709 |
|
| 710 |
payloads = cJSON_Parse(decoded_payloads); |
| 711 |
if (payloads == NULL) { |
| 712 |
rd_snprintf(errstr, errstr_size, |
| 713 |
"Failed to parse JSON JWT payload"); |
| 714 |
goto fail; |
| 715 |
} |
| 716 |
|
| 717 |
jwt_exp = cJSON_GetObjectItem(payloads, "exp"); |
| 718 |
if (jwt_exp == NULL) { |
| 719 |
rd_snprintf(errstr, errstr_size, |
| 720 |
"Expected JSON JWT response with " |
| 721 |
"\"exp\" field"); |
| 722 |
goto fail; |
| 723 |
} |
| 724 |
|
| 725 |
*exp = cJSON_GetNumberValue(jwt_exp); |
| 726 |
if (*exp <= 0) { |
| 727 |
rd_snprintf(errstr, errstr_size, |
| 728 |
"Expected JSON JWT response with " |
| 729 |
"valid \"exp\" field"); |
| 730 |
goto fail; |
| 731 |
} |
| 732 |
|
| 733 |
rd_dassert(sub_claim_name && *sub_claim_name); |
| 734 |
|
| 735 |
jwt_sub = cJSON_GetObjectItem(payloads, sub_claim_name); |
| 736 |
if (jwt_sub == NULL) { |
| 737 |
rd_snprintf(errstr, errstr_size, |
| 738 |
"Expected JSON JWT response with " |
| 739 |
"\"%s\" field", |
| 740 |
sub_claim_name); |
| 741 |
goto fail; |
| 742 |
} |
| 743 |
|
| 744 |
*sub = cJSON_GetStringValue(jwt_sub); |
| 745 |
if (*sub == NULL || **sub == '\0') { |
| 746 |
/* Reset to NULL to prevent a dangling pointer to cJSON |
| 747 |
* internal memory after cJSON_Delete(payloads) */ |
| 748 |
*sub = NULL; |
| 749 |
rd_snprintf(errstr, errstr_size, |
| 750 |
"Expected JSON JWT response with " |
| 751 |
"valid \"%s\" field (non-empty value required)", |
| 752 |
sub_claim_name); |
| 753 |
goto fail; |
| 754 |
} |
| 755 |
*sub = rd_strdup(*sub); |
| 756 |
done: |
| 757 |
if (payloads) |
| 758 |
cJSON_Delete(payloads); |
| 759 |
if (decoded_payloads) |
| 760 |
rd_free(decoded_payloads); |
| 761 |
return jwt_token; |
| 762 |
fail: |
| 763 |
jwt_token = NULL; |
| 764 |
goto done; |
| 765 |
} |
| 766 |
|
| 767 |
/** |
| 768 |
* @brief Implementation of JWT token refresh callback function. |
| 769 |
* Creates a JWT assertion, exchanges it for an access token, |
| 770 |
* and sets the token for SASL OAUTHBEARER authentication. |
| 771 |
* |
| 772 |
* @param rk The rd_kafka_t instance. |
| 773 |
* @param oauthbearer_config The OAUTHBEARER configuration. |
| 774 |
* @param opaque Opaque pointer passed to the callback. |
| 775 |
* |
| 776 |
* @locality rdkafka main thread |
| 777 |
*/ |
| 778 |
void rd_kafka_oidc_token_jwt_bearer_refresh_cb(rd_kafka_t *rk, |
| 779 |
const char *oauthbearer_config, |
| 780 |
void *opaque) { |
| 781 |
const int timeout_s = 20; |
| 782 |
const int retry = 4; |
| 783 |
const int retry_ms = 5 * 1000; |
| 784 |
|
| 785 |
char *jwt_assertion = NULL; |
| 786 |
char *request_body = NULL; |
| 787 |
struct curl_slist *headers = NULL; |
| 788 |
rd_http_error_t *herr = NULL; |
| 789 |
cJSON *json = NULL; |
| 790 |
char *jwt_token = NULL; |
| 791 |
char set_token_errstr[512]; |
| 792 |
double exp = 0; |
| 793 |
char **extensions = NULL; |
| 794 |
char **extension_key_value = NULL; |
| 795 |
size_t extension_key_value_cnt = 0; |
| 796 |
size_t extension_cnt; |
| 797 |
char *sub = NULL; |
| 798 |
char validate_errstr[512]; |
| 799 |
|
| 800 |
if (rd_kafka_terminating(rk)) |
| 801 |
return; |
| 802 |
|
| 803 |
if (rk->rk_conf.sasl.oauthbearer.assertion.file) { |
| 804 |
jwt_assertion = rd_kafka_oidc_assertion_read_from_file( |
| 805 |
rk->rk_conf.sasl.oauthbearer.assertion.file); |
| 806 |
} else { |
| 807 |
jwt_assertion = rd_kafka_oidc_assertion_create( |
| 808 |
rk, rk->rk_conf.sasl.oauthbearer.assertion.private_key.pem, |
| 809 |
rk->rk_conf.sasl.oauthbearer.assertion.private_key.file, |
| 810 |
rk->rk_conf.sasl.oauthbearer.assertion.private_key |
| 811 |
.passphrase, |
| 812 |
rk->rk_conf.sasl.oauthbearer.assertion.algorithm, |
| 813 |
rk->rk_conf.sasl.oauthbearer.assertion.jwt_template_file, |
| 814 |
rk->rk_conf.sasl.oauthbearer.assertion.claim.subject, |
| 815 |
rk->rk_conf.sasl.oauthbearer.assertion.claim.issuer, |
| 816 |
rk->rk_conf.sasl.oauthbearer.assertion.claim.audience, |
| 817 |
rk->rk_conf.sasl.oauthbearer.assertion.claim.not_before_s, |
| 818 |
rk->rk_conf.sasl.oauthbearer.assertion.claim.expiration_s, |
| 819 |
rk->rk_conf.sasl.oauthbearer.assertion.claim.jti_include); |
| 820 |
} |
| 821 |
|
| 822 |
if (!jwt_assertion) { |
| 823 |
rd_kafka_oauthbearer_set_token_failure( |
| 824 |
rk, "Failed to create JWT assertion"); |
| 825 |
goto done; |
| 826 |
} |
| 827 |
|
| 828 |
request_body = rd_kafka_oidc_jwt_bearer_build_request_body( |
| 829 |
jwt_assertion, rk->rk_conf.sasl.oauthbearer.scope); |
| 830 |
|
| 831 |
if (!request_body) { |
| 832 |
rd_kafka_oauthbearer_set_token_failure( |
| 833 |
rk, "Failed to build JWT request body"); |
| 834 |
goto done; |
| 835 |
} |
| 836 |
|
| 837 |
headers = curl_slist_append( |
| 838 |
headers, "Content-Type: application/x-www-form-urlencoded"); |
| 839 |
headers = curl_slist_append(headers, "Accept: application/json"); |
| 840 |
|
| 841 |
herr = rd_http_post_expect_json( |
| 842 |
rk, rk->rk_conf.sasl.oauthbearer.token_endpoint_url, headers, |
| 843 |
request_body, strlen(request_body), timeout_s, retry, retry_ms, |
| 844 |
&json); |
| 845 |
|
| 846 |
if (unlikely(herr != NULL)) { |
| 847 |
rd_kafka_log( |
| 848 |
rk, LOG_ERR, "JWT", |
| 849 |
"Failed to retrieve JWT token from \"%s\": %s (%d)", |
| 850 |
rk->rk_conf.sasl.oauthbearer.token_endpoint_url, |
| 851 |
herr->errstr, herr->code); |
| 852 |
rd_kafka_oauthbearer_set_token_failure(rk, herr->errstr); |
| 853 |
rd_http_error_destroy(herr); |
| 854 |
goto done; |
| 855 |
} |
| 856 |
|
| 857 |
/* |
| 858 |
* RFC 7523 Section 1 says that an access token should be returned |
| 859 |
* https://datatracker.ietf.org/doc/html/rfc7523#section-1 |
| 860 |
* Some providers (e.g. GCP) return an `id_token` instead, depending |
| 861 |
* on the configured `target_audience` in the request JWT bearer token. |
| 862 |
* This may be because the validation endpoint is not accessible |
| 863 |
* for validating the `access_token` while the `id_token` is validated |
| 864 |
* through the JWKS URL. |
| 865 |
* This function will try to validate the `access_token` and then the |
| 866 |
* `id_token`. |
| 867 |
*/ |
| 868 |
jwt_token = rd_kafka_oidc_token_try_validate( |
| 869 |
json, "access_token", rk->rk_conf.sasl.oauthbearer.sub_claim_name, |
| 870 |
&sub, &exp, validate_errstr, sizeof(validate_errstr)); |
| 871 |
if (!jwt_token) |
| 872 |
jwt_token = rd_kafka_oidc_token_try_validate( |
| 873 |
json, "id_token", |
| 874 |
rk->rk_conf.sasl.oauthbearer.sub_claim_name, &sub, &exp, |
| 875 |
validate_errstr, sizeof(validate_errstr)); |
| 876 |
|
| 877 |
if (!jwt_token) { |
| 878 |
rd_kafka_oauthbearer_set_token_failure(rk, validate_errstr); |
| 879 |
goto done; |
| 880 |
} |
| 881 |
|
| 882 |
|
| 883 |
if (rk->rk_conf.sasl.oauthbearer.extensions_str) { |
| 884 |
extensions = |
| 885 |
rd_string_split(rk->rk_conf.sasl.oauthbearer.extensions_str, |
| 886 |
',', rd_true, &extension_cnt); |
| 887 |
|
| 888 |
extension_key_value = rd_kafka_conf_kv_split( |
| 889 |
(const char **)extensions, extension_cnt, |
| 890 |
&extension_key_value_cnt); |
| 891 |
} |
| 892 |
|
| 893 |
if (rd_kafka_oauthbearer_set_token( |
| 894 |
rk, jwt_token, (int64_t)exp * 1000, sub, |
| 895 |
(const char **)extension_key_value, extension_key_value_cnt, |
| 896 |
set_token_errstr, |
| 897 |
sizeof(set_token_errstr)) != RD_KAFKA_RESP_ERR_NO_ERROR) { |
| 898 |
rd_kafka_oauthbearer_set_token_failure(rk, validate_errstr); |
| 899 |
} |
| 900 |
|
| 901 |
done: |
| 902 |
RD_IF_FREE(sub, rd_free); |
| 903 |
RD_IF_FREE(jwt_assertion, rd_free); |
| 904 |
RD_IF_FREE(request_body, rd_free); |
| 905 |
RD_IF_FREE(headers, curl_slist_free_all); |
| 906 |
RD_IF_FREE(json, cJSON_Delete); |
| 907 |
RD_IF_FREE(extensions, rd_free); |
| 908 |
RD_IF_FREE(extension_key_value, rd_free); |
| 909 |
/* jwt_token is freed as part of the json object */ |
| 910 |
} |
| 911 |
|
| 912 |
/** |
| 913 |
* @brief Implementation of Oauth/OIDC token refresh callback function, |
| 914 |
* will receive the JSON response after HTTP call to token provider, |
| 915 |
* then extract the jwt from the JSON response, and forward it to |
| 916 |
* the broker. |
| 917 |
*/ |
| 918 |
void rd_kafka_oidc_token_client_credentials_refresh_cb( |
| 919 |
rd_kafka_t *rk, |
| 920 |
const char *oauthbearer_config, |
| 921 |
void *opaque) { |
| 922 |
const int timeout_s = 20; |
| 923 |
const int retry = 4; |
| 924 |
const int retry_ms = 5 * 1000; |
| 925 |
|
| 926 |
double exp; |
| 927 |
|
| 928 |
cJSON *json = NULL; |
| 929 |
|
| 930 |
rd_http_error_t *herr; |
| 931 |
|
| 932 |
char *jwt_token; |
| 933 |
char *post_fields = NULL; |
| 934 |
|
| 935 |
struct curl_slist *headers = NULL; |
| 936 |
|
| 937 |
const char *token_url; |
| 938 |
char *sub = NULL; |
| 939 |
|
| 940 |
size_t post_fields_size; |
| 941 |
size_t extension_cnt; |
| 942 |
size_t extension_key_value_cnt = 0; |
| 943 |
|
| 944 |
char set_token_errstr[512]; |
| 945 |
|
| 946 |
char **extensions = NULL; |
| 947 |
char **extension_key_value = NULL; |
| 948 |
|
| 949 |
if (rd_kafka_terminating(rk)) |
| 950 |
return; |
| 951 |
|
| 952 |
rd_kafka_oidc_client_credentials_build_headers( |
| 953 |
rk->rk_conf.sasl.oauthbearer.client_id, |
| 954 |
rk->rk_conf.sasl.oauthbearer.client_secret, &headers); |
| 955 |
|
| 956 |
/* Build post fields */ |
| 957 |
rd_kafka_oidc_client_credentials_build_post_fields( |
| 958 |
rk->rk_conf.sasl.oauthbearer.scope, &post_fields, |
| 959 |
&post_fields_size); |
| 960 |
|
| 961 |
token_url = rk->rk_conf.sasl.oauthbearer.token_endpoint_url; |
| 962 |
|
| 963 |
herr = rd_http_post_expect_json(rk, token_url, headers, post_fields, |
| 964 |
post_fields_size, timeout_s, retry, |
| 965 |
retry_ms, &json); |
| 966 |
|
| 967 |
if (unlikely(herr != NULL)) { |
| 968 |
rd_kafka_log(rk, LOG_ERR, "OIDC", |
| 969 |
"Failed to retrieve OIDC " |
| 970 |
"token from \"%s\": %s (%d)", |
| 971 |
token_url, herr->errstr, herr->code); |
| 972 |
rd_kafka_oauthbearer_set_token_failure(rk, herr->errstr); |
| 973 |
rd_http_error_destroy(herr); |
| 974 |
goto done; |
| 975 |
} |
| 976 |
|
| 977 |
jwt_token = rd_kafka_oidc_token_try_validate( |
| 978 |
json, "access_token", rk->rk_conf.sasl.oauthbearer.sub_claim_name, |
| 979 |
&sub, &exp, set_token_errstr, sizeof(set_token_errstr)); |
| 980 |
if (!jwt_token) { |
| 981 |
rd_kafka_oauthbearer_set_token_failure(rk, set_token_errstr); |
| 982 |
goto done; |
| 983 |
} |
| 984 |
|
| 985 |
if (rk->rk_conf.sasl.oauthbearer.extensions_str) { |
| 986 |
extensions = |
| 987 |
rd_string_split(rk->rk_conf.sasl.oauthbearer.extensions_str, |
| 988 |
',', rd_true, &extension_cnt); |
| 989 |
|
| 990 |
extension_key_value = rd_kafka_conf_kv_split( |
| 991 |
(const char **)extensions, extension_cnt, |
| 992 |
&extension_key_value_cnt); |
| 993 |
} |
| 994 |
|
| 995 |
if (rd_kafka_oauthbearer_set_token( |
| 996 |
rk, jwt_token, (int64_t)exp * 1000, sub, |
| 997 |
(const char **)extension_key_value, extension_key_value_cnt, |
| 998 |
set_token_errstr, |
| 999 |
sizeof(set_token_errstr)) != RD_KAFKA_RESP_ERR_NO_ERROR) |
| 1000 |
rd_kafka_oauthbearer_set_token_failure(rk, set_token_errstr); |
| 1001 |
|
| 1002 |
done: |
| 1003 |
RD_IF_FREE(sub, rd_free); |
| 1004 |
RD_IF_FREE(post_fields, rd_free); |
| 1005 |
RD_IF_FREE(json, cJSON_Delete); |
| 1006 |
RD_IF_FREE(headers, curl_slist_free_all); |
| 1007 |
RD_IF_FREE(extensions, rd_free); |
| 1008 |
RD_IF_FREE(extension_key_value, rd_free); |
| 1009 |
} |
| 1010 |
|
| 1011 |
/** |
| 1012 |
* @brief Implementation of Oauth/OIDC token refresh callback function |
| 1013 |
* for Azure IMDS, |
| 1014 |
* will receive the JSON response after HTTP(S) GET call to token |
| 1015 |
* provider, then extract the jwt from the JSON response, and |
| 1016 |
* forward it to the broker. |
| 1017 |
*/ |
| 1018 |
void rd_kafka_oidc_token_metadata_azure_imds_refresh_cb( |
| 1019 |
rd_kafka_t *rk, |
| 1020 |
const char *oauthbearer_config, |
| 1021 |
void *opaque) { |
| 1022 |
const int timeout_s = 20; |
| 1023 |
const int retries = 4; |
| 1024 |
const int retry_ms = 5 * 1000; |
| 1025 |
|
| 1026 |
double exp; |
| 1027 |
|
| 1028 |
cJSON *json = NULL; |
| 1029 |
|
| 1030 |
rd_http_error_t *herr; |
| 1031 |
|
| 1032 |
char *jwt_token; |
| 1033 |
|
| 1034 |
struct curl_slist *headers = NULL; |
| 1035 |
|
| 1036 |
const char *token_endpoint_url_initial = NULL; |
| 1037 |
char *token_endpoint_url = NULL; |
| 1038 |
char *sub = NULL; |
| 1039 |
|
| 1040 |
size_t extension_cnt; |
| 1041 |
size_t extension_key_value_cnt = 0; |
| 1042 |
|
| 1043 |
char set_token_errstr[512]; |
| 1044 |
|
| 1045 |
char **extensions = NULL; |
| 1046 |
char **extension_key_value = NULL; |
| 1047 |
char *query = NULL; |
| 1048 |
static char *headers_array[] = {"Metadata: true"}; |
| 1049 |
|
| 1050 |
if (rd_kafka_terminating(rk)) |
| 1051 |
return; |
| 1052 |
|
| 1053 |
if (rk->rk_conf.sasl.oauthbearer_config) |
| 1054 |
query = rd_kafka_conf_kv_get( |
| 1055 |
rk->rk_conf.sasl.oauthbearer_config, "query", ','); |
| 1056 |
token_endpoint_url_initial = |
| 1057 |
rk->rk_conf.sasl.oauthbearer.token_endpoint_url; |
| 1058 |
if (!token_endpoint_url_initial) |
| 1059 |
token_endpoint_url_initial = |
| 1060 |
RD_KAFKA_SASL_OAUTHBEARER_METADATA_AUTHENTICATION_URL_AZURE_IMDS; |
| 1061 |
if (query && *query) { |
| 1062 |
token_endpoint_url = rd_http_get_params_append( |
| 1063 |
token_endpoint_url_initial, query); |
| 1064 |
|
| 1065 |
if (token_endpoint_url == NULL) { |
| 1066 |
rd_snprintf( |
| 1067 |
set_token_errstr, sizeof(set_token_errstr), |
| 1068 |
"Failed to append params \"%s\" to token endpoint " |
| 1069 |
"URL \"%s\"", |
| 1070 |
query, |
| 1071 |
rk->rk_conf.sasl.oauthbearer.token_endpoint_url); |
| 1072 |
rd_kafka_log(rk, LOG_ERR, "OIDC", "%s", |
| 1073 |
set_token_errstr); |
| 1074 |
rd_kafka_oauthbearer_set_token_failure( |
| 1075 |
rk, set_token_errstr); |
| 1076 |
goto done; |
| 1077 |
} |
| 1078 |
} else { |
| 1079 |
token_endpoint_url = rd_strdup(token_endpoint_url_initial); |
| 1080 |
} |
| 1081 |
|
| 1082 |
herr = rd_http_get_json(rk, token_endpoint_url, headers_array, 1, |
| 1083 |
timeout_s, retries, retry_ms, &json); |
| 1084 |
|
| 1085 |
if (unlikely(herr != NULL)) { |
| 1086 |
rd_kafka_log(rk, LOG_ERR, "OIDC", |
| 1087 |
"Failed to retrieve OIDC " |
| 1088 |
"token from \"%s\": %s (%d)", |
| 1089 |
token_endpoint_url, herr->errstr, herr->code); |
| 1090 |
rd_kafka_oauthbearer_set_token_failure(rk, herr->errstr); |
| 1091 |
rd_http_error_destroy(herr); |
| 1092 |
goto done; |
| 1093 |
} |
| 1094 |
|
| 1095 |
jwt_token = rd_kafka_oidc_token_try_validate( |
| 1096 |
json, "access_token", rk->rk_conf.sasl.oauthbearer.sub_claim_name, |
| 1097 |
&sub, &exp, set_token_errstr, sizeof(set_token_errstr)); |
| 1098 |
if (!jwt_token) { |
| 1099 |
rd_kafka_oauthbearer_set_token_failure(rk, set_token_errstr); |
| 1100 |
goto done; |
| 1101 |
} |
| 1102 |
|
| 1103 |
if (rk->rk_conf.sasl.oauthbearer.extensions_str) { |
| 1104 |
extensions = |
| 1105 |
rd_string_split(rk->rk_conf.sasl.oauthbearer.extensions_str, |
| 1106 |
',', rd_true, &extension_cnt); |
| 1107 |
|
| 1108 |
extension_key_value = rd_kafka_conf_kv_split( |
| 1109 |
(const char **)extensions, extension_cnt, |
| 1110 |
&extension_key_value_cnt); |
| 1111 |
} |
| 1112 |
|
| 1113 |
if (rd_kafka_oauthbearer_set_token( |
| 1114 |
rk, jwt_token, (int64_t)exp * 1000, sub, |
| 1115 |
(const char **)extension_key_value, extension_key_value_cnt, |
| 1116 |
set_token_errstr, |
| 1117 |
sizeof(set_token_errstr)) != RD_KAFKA_RESP_ERR_NO_ERROR) |
| 1118 |
rd_kafka_oauthbearer_set_token_failure(rk, set_token_errstr); |
| 1119 |
|
| 1120 |
done: |
| 1121 |
RD_IF_FREE(sub, rd_free); |
| 1122 |
RD_IF_FREE(json, cJSON_Delete); |
| 1123 |
RD_IF_FREE(headers, curl_slist_free_all); |
| 1124 |
RD_IF_FREE(extensions, rd_free); |
| 1125 |
RD_IF_FREE(extension_key_value, rd_free); |
| 1126 |
RD_IF_FREE(token_endpoint_url, rd_free); |
| 1127 |
RD_IF_FREE(query, rd_free); |
| 1128 |
} |
| 1129 |
|
| 1130 |
/** |
| 1131 |
* @brief Make sure the jwt is able to be extracted from HTTP(S) response. |
| 1132 |
* The JSON response after HTTP(S) call to token provider will be in |
| 1133 |
* rd_http_req_t.hreq_buf and jwt is the value of field "access_token", |
| 1134 |
* the format is {"access_token":"*******"}. |
| 1135 |
* This function mocks up the rd_http_req_t.hreq_buf using an dummy |
| 1136 |
* jwt. The rd_http_parse_json will extract the jwt from rd_http_req_t |
| 1137 |
* and make sure the extracted jwt is same with the dummy one. |
| 1138 |
*/ |
| 1139 |
static int ut_sasl_oauthbearer_oidc_should_succeed(void) { |
| 1140 |
/* Generate a token in the https://jwt.io/ website by using the |
| 1141 |
* following steps: |
| 1142 |
* 1. Select the algorithm RS256 from the Algorithm drop-down menu. |
| 1143 |
* 2. Enter the header and the payload. |
| 1144 |
* payload should contains "exp", "iat", "sub", for example: |
| 1145 |
* payloads = {"exp": 1636532769, |
| 1146 |
"iat": 1516239022, |
| 1147 |
"sub": "sub"} |
| 1148 |
header should contains "kid", for example: |
| 1149 |
headers={"kid": "abcedfg"} */ |
| 1150 |
static const char *expected_jwt_token = |
| 1151 |
"eyJhbGciOiJIUzI1NiIsInR5" |
| 1152 |
"cCI6IkpXVCIsImtpZCI6ImFiY2VkZmcifQ" |
| 1153 |
"." |
| 1154 |
"eyJpYXQiOjE2MzIzNzUzMjAsInN1YiI6InN" |
| 1155 |
"1YiIsImV4cCI6MTYzMjM3NTYyMH0" |
| 1156 |
"." |
| 1157 |
"bT5oY8K-rS2gQ7Awc40844bK3zhzBhZb7sputErqQHY"; |
| 1158 |
char *expected_token_value; |
| 1159 |
size_t token_len; |
| 1160 |
rd_http_req_t hreq; |
| 1161 |
rd_http_error_t *herr; |
| 1162 |
cJSON *json = NULL; |
| 1163 |
char *token; |
| 1164 |
cJSON *parsed_token; |
| 1165 |
rd_kafka_t *rk = rd_calloc(1, sizeof(*rk)); |
| 1166 |
|
| 1167 |
RD_UT_BEGIN(); |
| 1168 |
|
| 1169 |
herr = rd_http_req_init(rk, &hreq, ""); |
| 1170 |
|
| 1171 |
RD_UT_ASSERT(!herr, |
| 1172 |
"Expected initialize to succeed, " |
| 1173 |
"but failed with error code: %d, error string: %s", |
| 1174 |
herr->code, herr->errstr); |
| 1175 |
|
| 1176 |
token_len = strlen("access_token") + strlen(expected_jwt_token) + 8; |
| 1177 |
|
| 1178 |
expected_token_value = rd_malloc(token_len); |
| 1179 |
rd_snprintf(expected_token_value, token_len, "{\"%s\":\"%s\"}", |
| 1180 |
"access_token", expected_jwt_token); |
| 1181 |
rd_buf_write(hreq.hreq_buf, expected_token_value, token_len); |
| 1182 |
|
| 1183 |
herr = rd_http_parse_json(&hreq, &json); |
| 1184 |
RD_UT_ASSERT(!herr, |
| 1185 |
"Failed to parse JSON token: error code: %d, " |
| 1186 |
"error string: %s", |
| 1187 |
herr->code, herr->errstr); |
| 1188 |
|
| 1189 |
RD_UT_ASSERT(json, "Expected non-empty json."); |
| 1190 |
|
| 1191 |
parsed_token = cJSON_GetObjectItem(json, "access_token"); |
| 1192 |
|
| 1193 |
RD_UT_ASSERT(parsed_token, "Expected access_token in JSON response."); |
| 1194 |
token = parsed_token->valuestring; |
| 1195 |
|
| 1196 |
RD_UT_ASSERT(!strcmp(expected_jwt_token, token), |
| 1197 |
"Incorrect token received: " |
| 1198 |
"expected=%s; received=%s", |
| 1199 |
expected_jwt_token, token); |
| 1200 |
|
| 1201 |
rd_free(expected_token_value); |
| 1202 |
rd_http_error_destroy(herr); |
| 1203 |
rd_http_req_destroy(&hreq); |
| 1204 |
cJSON_Delete(json); |
| 1205 |
rd_free(rk); |
| 1206 |
|
| 1207 |
RD_UT_PASS(); |
| 1208 |
} |
| 1209 |
|
| 1210 |
|
| 1211 |
/** |
| 1212 |
* @brief Make sure JSON doesn't include the "access_token" key, |
| 1213 |
* it will fail and return an empty token. |
| 1214 |
*/ |
| 1215 |
static int ut_sasl_oauthbearer_oidc_with_empty_key(void) { |
| 1216 |
static const char *empty_token_format = "{}"; |
| 1217 |
size_t token_len; |
| 1218 |
rd_http_req_t hreq; |
| 1219 |
rd_http_error_t *herr; |
| 1220 |
cJSON *json = NULL; |
| 1221 |
cJSON *parsed_token; |
| 1222 |
rd_kafka_t *rk = rd_calloc(1, sizeof(*rk)); |
| 1223 |
|
| 1224 |
RD_UT_BEGIN(); |
| 1225 |
|
| 1226 |
herr = rd_http_req_init(rk, &hreq, ""); |
| 1227 |
RD_UT_ASSERT(!herr, |
| 1228 |
"Expected initialization to succeed, " |
| 1229 |
"but it failed with error code: %d, error string: %s", |
| 1230 |
herr->code, herr->errstr); |
| 1231 |
|
| 1232 |
token_len = strlen(empty_token_format); |
| 1233 |
|
| 1234 |
rd_buf_write(hreq.hreq_buf, empty_token_format, token_len); |
| 1235 |
|
| 1236 |
herr = rd_http_parse_json(&hreq, &json); |
| 1237 |
|
| 1238 |
RD_UT_ASSERT(!herr, |
| 1239 |
"Expected JSON token parsing to succeed, " |
| 1240 |
"but it failed with error code: %d, error string: %s", |
| 1241 |
herr->code, herr->errstr); |
| 1242 |
|
| 1243 |
RD_UT_ASSERT(json, "Expected non-empty json."); |
| 1244 |
|
| 1245 |
parsed_token = cJSON_GetObjectItem(json, "access_token"); |
| 1246 |
|
| 1247 |
RD_UT_ASSERT(!parsed_token, |
| 1248 |
"Did not expecte access_token in JSON response"); |
| 1249 |
|
| 1250 |
rd_http_req_destroy(&hreq); |
| 1251 |
rd_http_error_destroy(herr); |
| 1252 |
cJSON_Delete(json); |
| 1253 |
cJSON_Delete(parsed_token); |
| 1254 |
rd_free(rk); |
| 1255 |
RD_UT_PASS(); |
| 1256 |
} |
| 1257 |
|
| 1258 |
/** |
| 1259 |
* @brief Make sure the post_fields return correct with the scope. |
| 1260 |
*/ |
| 1261 |
static int ut_sasl_oauthbearer_oidc_post_fields(void) { |
| 1262 |
static const char *scope = "test-scope"; |
| 1263 |
static const char *expected_post_fields = |
| 1264 |
"grant_type=client_credentials&scope=test-scope"; |
| 1265 |
|
| 1266 |
size_t expected_post_fields_size = strlen(expected_post_fields); |
| 1267 |
|
| 1268 |
size_t post_fields_size; |
| 1269 |
|
| 1270 |
char *post_fields; |
| 1271 |
|
| 1272 |
RD_UT_BEGIN(); |
| 1273 |
|
| 1274 |
rd_kafka_oidc_client_credentials_build_post_fields(scope, &post_fields, |
| 1275 |
&post_fields_size); |
| 1276 |
|
| 1277 |
RD_UT_ASSERT(expected_post_fields_size == post_fields_size, |
| 1278 |
"Expected expected_post_fields_size is %" PRIusz |
| 1279 |
" received post_fields_size is %" PRIusz, |
| 1280 |
expected_post_fields_size, post_fields_size); |
| 1281 |
RD_UT_ASSERT(!strcmp(expected_post_fields, post_fields), |
| 1282 |
"Expected expected_post_fields is %s" |
| 1283 |
" received post_fields is %s", |
| 1284 |
expected_post_fields, post_fields); |
| 1285 |
|
| 1286 |
rd_free(post_fields); |
| 1287 |
|
| 1288 |
RD_UT_PASS(); |
| 1289 |
} |
| 1290 |
|
| 1291 |
/** |
| 1292 |
* @brief Make sure the post_fields return correct with the empty scope. |
| 1293 |
*/ |
| 1294 |
static int ut_sasl_oauthbearer_oidc_post_fields_with_empty_scope(void) { |
| 1295 |
static const char *scope = NULL; |
| 1296 |
static const char *expected_post_fields = |
| 1297 |
"grant_type=client_credentials"; |
| 1298 |
|
| 1299 |
size_t expected_post_fields_size = strlen(expected_post_fields); |
| 1300 |
|
| 1301 |
size_t post_fields_size; |
| 1302 |
|
| 1303 |
char *post_fields; |
| 1304 |
|
| 1305 |
RD_UT_BEGIN(); |
| 1306 |
|
| 1307 |
rd_kafka_oidc_client_credentials_build_post_fields(scope, &post_fields, |
| 1308 |
&post_fields_size); |
| 1309 |
|
| 1310 |
RD_UT_ASSERT(expected_post_fields_size == post_fields_size, |
| 1311 |
"Expected expected_post_fields_size is %" PRIusz |
| 1312 |
" received post_fields_size is %" PRIusz, |
| 1313 |
expected_post_fields_size, post_fields_size); |
| 1314 |
RD_UT_ASSERT(!strcmp(expected_post_fields, post_fields), |
| 1315 |
"Expected expected_post_fields is %s" |
| 1316 |
" received post_fields is %s", |
| 1317 |
expected_post_fields, post_fields); |
| 1318 |
|
| 1319 |
rd_free(post_fields); |
| 1320 |
|
| 1321 |
RD_UT_PASS(); |
| 1322 |
} |
| 1323 |
|
| 1324 |
/** All JWTs use a fake signature since token_try_validate() only |
| 1325 |
* decodes and inspects the payload; signature verification is done |
| 1326 |
* separately by the broker. |
| 1327 |
* |
| 1328 |
* JWT payloads (decoded): |
| 1329 |
* JWT_SUB_ONLY: |
| 1330 |
* {"exp":9999999999,"iat":1000000000,"sub":"subject"} |
| 1331 |
* |
| 1332 |
* JWT_MULTI_CLAIMS: |
| 1333 |
* {"exp":9999999999,"iat":1000000000,"sub":"subject", |
| 1334 |
* "client_id":"client_id_123","azp":"azp_123"} |
| 1335 |
* |
| 1336 |
* JWT_EMPTY_SUB: |
| 1337 |
* {"exp":9999999999,"iat":1000000000,"sub":""} |
| 1338 |
* |
| 1339 |
* JWT_MISSING_SUB: |
| 1340 |
* {"exp":9999999999,"iat":1000000000,"client_id":"client_id_123"} |
| 1341 |
*/ |
| 1342 |
/* payload: {"exp":9999999999,"iat":1000000000,"sub":"subject"} */ |
| 1343 |
#define UT_JWT_SUB_ONLY \ |
| 1344 |
"eyJhbGciOiJSUzI1NiIsImtpZCI6ImFiY2RlZmcifQ" \ |
| 1345 |
"." \ |
| 1346 |
"eyJleHAiOjk5OTk5OTk5OTksImlhdCI6MTAwMDAwMDAwMCwic" \ |
| 1347 |
"3ViIjoic3ViamVjdCJ9" \ |
| 1348 |
"." \ |
| 1349 |
"fakesignature" |
| 1350 |
/* payload: {"exp":9999999999,"iat":1000000000,"sub":"subject", |
| 1351 |
* "client_id":"client_id_123","azp":"azp_123"} */ |
| 1352 |
#define UT_JWT_MULTI_CLAIMS \ |
| 1353 |
"eyJhbGciOiJSUzI1NiIsImtpZCI6ImFiY2RlZmcifQ" \ |
| 1354 |
"." \ |
| 1355 |
"eyJleHAiOjk5OTk5OTk5OTksImlhdCI6MTAwMDAwMDAwMCwic3ViIjoic3ViamVj" \ |
| 1356 |
"dCIsImNsaWVudF9pZCI6ImNsaWVudF9pZF8xMjMiLCJhenAiOiJhenBfMTIzIn0" \ |
| 1357 |
"." \ |
| 1358 |
"fakesignature" |
| 1359 |
/* payload: {"exp":9999999999,"iat":1000000000,"sub":""} */ |
| 1360 |
#define UT_JWT_EMPTY_SUB \ |
| 1361 |
"eyJhbGciOiJSUzI1NiIsImtpZCI6ImFiY2RlZmcifQ" \ |
| 1362 |
"." \ |
| 1363 |
"eyJleHAiOjk5OTk5OTk5OTksImlhdCI6MTAwMDAwMDAwMCwic3ViIjoiIn0" \ |
| 1364 |
"." \ |
| 1365 |
"fakesignature" |
| 1366 |
/* payload: {"exp":9999999999,"iat":1000000000,"client_id":"client_id_123"} */ |
| 1367 |
#define UT_JWT_MISSING_SUB \ |
| 1368 |
"eyJhbGciOiJSUzI1NiIsImtpZCI6ImFiY2RlZmcifQ" \ |
| 1369 |
"." \ |
| 1370 |
"eyJleHAiOjk5OTk5OTk5OTksImlhdCI6MTAwMDAwMDAwMCwiY2xpZW50X2lkIjoi" \ |
| 1371 |
"Y2xpZW50X2lkXzEyMyJ9" \ |
| 1372 |
"." \ |
| 1373 |
"fakesignature" |
| 1374 |
|
| 1375 |
/** |
| 1376 |
* @brief Verifies the extraction logic of the subject from the configured JWT |
| 1377 |
* claim name, falls back to "sub" when unconfigured, and rejects missing or |
| 1378 |
* empty claim values. |
| 1379 |
*/ |
| 1380 |
static int ut_sasl_oauthbearer_oidc_sub_claim_name(void) { |
| 1381 |
|
| 1382 |
const struct { |
| 1383 |
const char *test_name; |
| 1384 |
const char *jwt; |
| 1385 |
const char *sub_claim_name; |
| 1386 |
rd_bool_t expect_success; |
| 1387 |
const char *expected_sub; |
| 1388 |
} tests[] = { |
| 1389 |
{"Explicit 'sub' claim name", UT_JWT_SUB_ONLY, "sub", rd_true, |
| 1390 |
"subject"}, |
| 1391 |
{"Custom 'client_id' claim", UT_JWT_MULTI_CLAIMS, "client_id", |
| 1392 |
rd_true, "client_id_123"}, |
| 1393 |
{"Custom 'azp' claim", UT_JWT_MULTI_CLAIMS, "azp", rd_true, |
| 1394 |
"azp_123"}, |
| 1395 |
{"Custom 'client_id' claim succeeds without sub", |
| 1396 |
UT_JWT_MISSING_SUB, "client_id", rd_true, "client_id_123"}, |
| 1397 |
{"Missing 'sub' claim fails", UT_JWT_MISSING_SUB, "sub", rd_false, |
| 1398 |
NULL}, |
| 1399 |
{"Empty 'sub' value fails", UT_JWT_EMPTY_SUB, "sub", rd_false, |
| 1400 |
NULL}, |
| 1401 |
{"Nonexistent claim name fails", UT_JWT_SUB_ONLY, "nonexistent", |
| 1402 |
rd_false, NULL}, |
| 1403 |
}; |
| 1404 |
|
| 1405 |
unsigned int i; |
| 1406 |
|
| 1407 |
RD_UT_BEGIN(); |
| 1408 |
|
| 1409 |
for (i = 0; i < RD_ARRAYSIZE(tests); i++) { |
| 1410 |
char *sub = NULL; |
| 1411 |
double exp_v = 0; |
| 1412 |
char errstr[256]; |
| 1413 |
char *result; |
| 1414 |
cJSON *json; |
| 1415 |
char access_token_json[2048]; |
| 1416 |
|
| 1417 |
rd_snprintf(access_token_json, sizeof(access_token_json), |
| 1418 |
"{\"access_token\":\"%s\"}", tests[i].jwt); |
| 1419 |
json = cJSON_Parse(access_token_json); |
| 1420 |
RD_UT_ASSERT(json != NULL, "[%s] Failed to build test JSON", |
| 1421 |
tests[i].test_name); |
| 1422 |
|
| 1423 |
result = rd_kafka_oidc_token_try_validate( |
| 1424 |
json, "access_token", tests[i].sub_claim_name, &sub, &exp_v, |
| 1425 |
errstr, sizeof(errstr)); |
| 1426 |
|
| 1427 |
if (tests[i].expect_success) { |
| 1428 |
RD_UT_ASSERT(result != NULL, |
| 1429 |
"[%s] Expected success but got error: %s", |
| 1430 |
tests[i].test_name, errstr); |
| 1431 |
RD_UT_ASSERT(sub != NULL, "[%s] Expected non-NULL sub", |
| 1432 |
tests[i].test_name); |
| 1433 |
RD_UT_ASSERT(!strcmp(sub, tests[i].expected_sub), |
| 1434 |
"[%s] Expected sub '%s', got '%s'", |
| 1435 |
tests[i].test_name, tests[i].expected_sub, |
| 1436 |
sub); |
| 1437 |
} else { |
| 1438 |
RD_UT_ASSERT(result == NULL, |
| 1439 |
"[%s] Expected failure but got sub '%s'", |
| 1440 |
tests[i].test_name, sub ? sub : "(null)"); |
| 1441 |
} |
| 1442 |
|
| 1443 |
RD_IF_FREE(sub, rd_free); |
| 1444 |
cJSON_Delete(json); |
| 1445 |
} |
| 1446 |
|
| 1447 |
RD_UT_PASS(); |
| 1448 |
} |
| 1449 |
|
| 1450 |
|
| 1451 |
/** |
| 1452 |
* @brief make sure the jwt is able to be extracted from HTTP(S) requests |
| 1453 |
* or fail as expected. |
| 1454 |
*/ |
| 1455 |
int unittest_sasl_oauthbearer_oidc(void) { |
| 1456 |
int fails = 0; |
| 1457 |
fails += ut_sasl_oauthbearer_oidc_should_succeed(); |
| 1458 |
fails += ut_sasl_oauthbearer_oidc_with_empty_key(); |
| 1459 |
fails += ut_sasl_oauthbearer_oidc_post_fields(); |
| 1460 |
fails += ut_sasl_oauthbearer_oidc_post_fields_with_empty_scope(); |
| 1461 |
fails += ut_sasl_oauthbearer_oidc_sub_claim_name(); |
| 1462 |
return fails; |
| 1463 |
} |
| 1464 |
|
| 1465 |
/** |
| 1466 |
* @brief Test the Base64Url encoding functionality. |
| 1467 |
* Verifies that the encoding correctly handles special characters |
| 1468 |
* and padding removal. |
| 1469 |
*/ |
| 1470 |
static int ut_sasl_oauthbearer_oidc_jwt_bearer_base64url_encode(void) { |
| 1471 |
/* Test cases with expected inputs and outputs */ |
| 1472 |
static const struct { |
| 1473 |
const char *input; |
| 1474 |
const char *expected_output; |
| 1475 |
} test_cases[] = { |
| 1476 |
/* Regular case */ |
| 1477 |
{"Hello, world!", "SGVsbG8sIHdvcmxkIQ"}, |
| 1478 |
/* Case with padding characters that should be removed */ |
| 1479 |
{"test", "dGVzdA"}, |
| 1480 |
/* Empty string */ |
| 1481 |
{"", ""}, |
| 1482 |
/* Special characters that trigger Base64 padding */ |
| 1483 |
{"f", "Zg"}, |
| 1484 |
{"fo", "Zm8"}, |
| 1485 |
{"foo", "Zm9v"}, |
| 1486 |
{"foob", "Zm9vYg"}, |
| 1487 |
{"fooba", "Zm9vYmE"}, |
| 1488 |
{"foobar", "Zm9vYmFy"}, |
| 1489 |
/* Characters that produce + and / in standard Base64 */ |
| 1490 |
{"\x3E\x3F", |
| 1491 |
"Pj8"}, /* encodes to ">?" in standard Base64 with + and / */ |
| 1492 |
}; |
| 1493 |
unsigned int i; |
| 1494 |
|
| 1495 |
RD_UT_BEGIN(); |
| 1496 |
|
| 1497 |
for (i = 0; i < RD_ARRAYSIZE(test_cases); i++) { |
| 1498 |
rd_chariov_t input_iov; |
| 1499 |
input_iov.ptr = (char *)test_cases[i].input; |
| 1500 |
input_iov.size = strlen(test_cases[i].input); |
| 1501 |
char *output = rd_base64_encode_str_urlsafe(&input_iov); |
| 1502 |
|
| 1503 |
RD_UT_ASSERT(output != NULL, |
| 1504 |
"Expected non-NULL output for input: %s", |
| 1505 |
test_cases[i].input); |
| 1506 |
|
| 1507 |
RD_UT_ASSERT(!strcmp(output, test_cases[i].expected_output), |
| 1508 |
"Base64Url encoding failed: expected %s, got %s", |
| 1509 |
test_cases[i].expected_output, output); |
| 1510 |
|
| 1511 |
rd_free(output); |
| 1512 |
} |
| 1513 |
|
| 1514 |
RD_UT_PASS(); |
| 1515 |
} |
| 1516 |
|
| 1517 |
/** |
| 1518 |
* @brief Test JWT request body building. |
| 1519 |
* Verifies that the request body is correctly formatted with |
| 1520 |
* the required parameters. |
| 1521 |
*/ |
| 1522 |
static int ut_sasl_oauthbearer_oidc_jwt_bearer_build_request_body(void) { |
| 1523 |
const char *assertion = "test.jwt.assertion"; |
| 1524 |
const char *scope = "test.scope"; |
| 1525 |
const char *expected = |
| 1526 |
"grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=" |
| 1527 |
"test.jwt.assertion&scope=test.scope"; |
| 1528 |
char *body; |
| 1529 |
|
| 1530 |
RD_UT_BEGIN(); |
| 1531 |
|
| 1532 |
body = rd_kafka_oidc_jwt_bearer_build_request_body(assertion, scope); |
| 1533 |
|
| 1534 |
RD_UT_ASSERT(body != NULL, "Expected non-NULL request body"); |
| 1535 |
|
| 1536 |
RD_UT_ASSERT(!strcmp(body, expected), |
| 1537 |
"Request body incorrect: expected '%s', got '%s'", |
| 1538 |
expected, body); |
| 1539 |
|
| 1540 |
rd_free(body); |
| 1541 |
|
| 1542 |
RD_UT_PASS(); |
| 1543 |
} |
| 1544 |
|
| 1545 |
/** |
| 1546 |
* @brief Test JWT assertion file parsing. |
| 1547 |
* Verifies that the function correctly reads a JWT from a file. |
| 1548 |
*/ |
| 1549 |
static int ut_sasl_oauthbearer_oidc_assertion_parse_from_file(void) { |
| 1550 |
|
| 1551 |
char tempfile_path[512]; |
| 1552 |
FILE *tempfile; |
| 1553 |
const char *test_jwt = "header.payload.signature"; |
| 1554 |
char *result; |
| 1555 |
|
| 1556 |
RD_UT_BEGIN(); |
| 1557 |
|
| 1558 |
tempfile = rd_file_mkstemp("rdtmp", "wb", tempfile_path, |
| 1559 |
sizeof(tempfile_path)); |
| 1560 |
fprintf(tempfile, "%s", test_jwt); |
| 1561 |
fclose(tempfile); |
| 1562 |
|
| 1563 |
/* Test parsing from file */ |
| 1564 |
result = rd_kafka_oidc_assertion_read_from_file(tempfile_path); |
| 1565 |
RD_UT_ASSERT(result != NULL, |
| 1566 |
"Expected non-NULL result from parsing file"); |
| 1567 |
RD_UT_ASSERT(!strcmp(result, test_jwt), |
| 1568 |
"Incorrect JWT parsed: expected '%s', got '%s'", test_jwt, |
| 1569 |
result); |
| 1570 |
|
| 1571 |
rd_free(result); |
| 1572 |
|
| 1573 |
/* Test with NULL path */ |
| 1574 |
result = rd_kafka_oidc_assertion_read_from_file(NULL); |
| 1575 |
RD_UT_ASSERT(result == NULL, "Expected NULL result with NULL path"); |
| 1576 |
|
| 1577 |
/* Test with non-existent file */ |
| 1578 |
result = |
| 1579 |
rd_kafka_oidc_assertion_read_from_file("/non/existent/file/path"); |
| 1580 |
RD_UT_ASSERT(result == NULL, |
| 1581 |
"Expected NULL result with non-existent file"); |
| 1582 |
|
| 1583 |
remove(tempfile_path); |
| 1584 |
|
| 1585 |
RD_UT_PASS(); |
| 1586 |
} |
| 1587 |
|
| 1588 |
/** |
| 1589 |
* @brief Mock function for testing JWT template processing. |
| 1590 |
* Creates a file with valid JWT template JSON. |
| 1591 |
*/ |
| 1592 |
static char *ut_create_mock_jwt_template_file(void) { |
| 1593 |
FILE *tempfile; |
| 1594 |
char tempfile_path[512]; |
| 1595 |
|
| 1596 |
const char *template_json = |
| 1597 |
"{\n" |
| 1598 |
" \"header\": {\n" |
| 1599 |
" \"kid\": \"test-key-id\"\n" |
| 1600 |
" },\n" |
| 1601 |
" \"payload\": {\n" |
| 1602 |
" \"sub\": \"test-subject\",\n" |
| 1603 |
" \"aud\": \"test-audience\"\n" |
| 1604 |
" }\n" |
| 1605 |
"}"; |
| 1606 |
|
| 1607 |
tempfile = rd_file_mkstemp("rdtmp", "wb", tempfile_path, |
| 1608 |
sizeof(tempfile_path)); |
| 1609 |
if (!tempfile) |
| 1610 |
return NULL; |
| 1611 |
|
| 1612 |
fprintf(tempfile, "%s", template_json); |
| 1613 |
fclose(tempfile); |
| 1614 |
|
| 1615 |
return rd_strdup(tempfile_path); |
| 1616 |
} |
| 1617 |
|
| 1618 |
/** |
| 1619 |
* @brief Test JWT template file processing. |
| 1620 |
* Verifies that the function correctly parses header and payload from |
| 1621 |
* template. |
| 1622 |
*/ |
| 1623 |
static int ut_sasl_oauthbearer_oidc_assertion_process_template_file(void) { |
| 1624 |
char *template_path; |
| 1625 |
rd_kafka_t *rk; |
| 1626 |
cJSON *header = NULL, *payload = NULL; |
| 1627 |
int result; |
| 1628 |
|
| 1629 |
RD_UT_BEGIN(); |
| 1630 |
|
| 1631 |
rk = rd_calloc(1, sizeof(*rk)); |
| 1632 |
|
| 1633 |
template_path = ut_create_mock_jwt_template_file(); |
| 1634 |
RD_UT_ASSERT(template_path != NULL, "Failed to create template file"); |
| 1635 |
|
| 1636 |
/* Test template processing */ |
| 1637 |
result = rd_kafka_oidc_assertion_parse_template_file(rk, template_path, |
| 1638 |
&header, &payload); |
| 1639 |
RD_UT_ASSERT(result == 0, "Expected success from template processing"); |
| 1640 |
RD_UT_ASSERT(header != NULL, "Expected non-NULL header JSON"); |
| 1641 |
RD_UT_ASSERT(payload != NULL, "Expected non-NULL payload JSON"); |
| 1642 |
|
| 1643 |
/* Verify header contents */ |
| 1644 |
cJSON *kid = cJSON_GetObjectItem(header, "kid"); |
| 1645 |
RD_UT_ASSERT(kid != NULL, "Expected kid in header"); |
| 1646 |
RD_UT_ASSERT(cJSON_IsString(kid), "Expected kid to be string"); |
| 1647 |
RD_UT_ASSERT(!strcmp(cJSON_GetStringValue(kid), "test-key-id"), |
| 1648 |
"Incorrect kid value"); |
| 1649 |
|
| 1650 |
/* Verify payload contents */ |
| 1651 |
cJSON *sub = cJSON_GetObjectItem(payload, "sub"); |
| 1652 |
RD_UT_ASSERT(sub != NULL, "Expected sub in payload"); |
| 1653 |
RD_UT_ASSERT(cJSON_IsString(sub), "Expected sub to be string"); |
| 1654 |
RD_UT_ASSERT(!strcmp(cJSON_GetStringValue(sub), "test-subject"), |
| 1655 |
"Incorrect sub value"); |
| 1656 |
|
| 1657 |
cJSON *aud = cJSON_GetObjectItem(payload, "aud"); |
| 1658 |
RD_UT_ASSERT(aud != NULL, "Expected aud in payload"); |
| 1659 |
RD_UT_ASSERT(cJSON_IsString(aud), "Expected aud to be string"); |
| 1660 |
RD_UT_ASSERT(!strcmp(cJSON_GetStringValue(aud), "test-audience"), |
| 1661 |
"Incorrect aud value"); |
| 1662 |
|
| 1663 |
/* Test with non-existent file */ |
| 1664 |
cJSON_Delete(header); |
| 1665 |
cJSON_Delete(payload); |
| 1666 |
header = NULL; |
| 1667 |
payload = NULL; |
| 1668 |
|
| 1669 |
result = rd_kafka_oidc_assertion_parse_template_file( |
| 1670 |
rk, "/non/existent/file", &header, &payload); |
| 1671 |
RD_UT_ASSERT(result == -1, "Expected failure with non-existent file"); |
| 1672 |
RD_UT_ASSERT(header == NULL, |
| 1673 |
"Expected NULL header with failed processing"); |
| 1674 |
RD_UT_ASSERT(payload == NULL, |
| 1675 |
"Expected NULL payload with failed processing"); |
| 1676 |
|
| 1677 |
unlink(template_path); |
| 1678 |
rd_free(template_path); |
| 1679 |
rd_free(rk); |
| 1680 |
if (header) |
| 1681 |
cJSON_Delete(header); |
| 1682 |
if (payload) |
| 1683 |
cJSON_Delete(payload); |
| 1684 |
|
| 1685 |
RD_UT_PASS(); |
| 1686 |
} |
| 1687 |
|
| 1688 |
/** |
| 1689 |
* @brief Test JWT assertion creation with minimal approach. |
| 1690 |
* Creates a simplified test that validates the format of the created |
| 1691 |
* JWT. |
| 1692 |
*/ |
| 1693 |
static int ut_sasl_oauthbearer_oidc_assertion_create(void) { |
| 1694 |
rd_kafka_t *rk; |
| 1695 |
char *private_key_pem; |
| 1696 |
char *jwt; |
| 1697 |
char *header_part, *payload_part, *signature_part; |
| 1698 |
char *dot1, *dot2; |
| 1699 |
|
| 1700 |
RD_UT_BEGIN(); |
| 1701 |
|
| 1702 |
rk = rd_calloc(1, sizeof(*rk)); |
| 1703 |
|
| 1704 |
/* Random key for signing */ |
| 1705 |
private_key_pem = |
| 1706 |
"-----BEGIN PRIVATE KEY-----\n" |
| 1707 |
"MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCuBS7qG5Cd2voa\n" |
| 1708 |
"7nSU2xaDbe6QOYU2P4bIY58SKHbFyq1iB517r61ImsWD+UfZuVxCqXRaWdxxnG/D\n" |
| 1709 |
"5VGTQzBOZYlgSYxdJ1KvITXO8kj5i2zBT/LI9R9MTQ7nLFh+vQm1aM8Ts1PmA5t9\n" |
| 1710 |
"zFtR9B8RfqN9kbt+2LnLY57aJxEkFC3D89D0WWT97UJWKo7/vxMqp9K9uAIL2Efo\n" |
| 1711 |
"5rp9qwyPbx9LmTbfZ8Vog6mG6tAQQHSUqw0PnfhADCVCkYtkzYcyDZy3qZQFu1bY\n" |
| 1712 |
"KuuMoMjssyCUL5tTHyNZju0p3Z0bSfOV/nkqHpSSjHKCeQkSKS18/7In6cfY/M4k\n" |
| 1713 |
"8rM4HWkdAgMBAAECggEAFsTo2YrXxj/Dn8h5ioyMCpBUuZw9GNcBDLE0PAz9VW3q\n" |
| 1714 |
"d7wlV+ypkKlnlJgGVa+SKcrARZ4iYN8mJIyZutn8tRVF/0pASmP9xppizvwWnkgm\n" |
| 1715 |
"57hNPQwNl08x1v+PaK3VWl4nUh2RqbPpIXGetT9q3UAjpiduT++Nh9Y2D7cy3/Ro\n" |
| 1716 |
"ritnpBDs1R6y5J3rxiE1s8kLYwhDRCPsgUg/ZtKPDTTFz42ArrFeqM91FmjHYP3t\n" |
| 1717 |
"p9Uh6CIZ80D6CsMX/TnZFfhKe6EvKBSl4W6tcdFlnXW52fm/670iKSmcJ09+fzPO\n" |
| 1718 |
"T1BLrkXGv51bFnlvUyJqQGVEv5+0+HUX/oTpTknMQQKBgQDbYhqip5e8r1f5v32B\n" |
| 1719 |
"k1r3xtEiWU2mZoTHJu6bVeuigzVhz4pTMVZChElJ4QnhwwO0t5Oe4Su1MZtjMRw7\n" |
| 1720 |
"qIE+YM2pXss25LRXbmWItuRWINzpe8omlxQSOj2tNO/67l0P4vmmrT5wkU2cG6TR\n" |
| 1721 |
"ddzorO3NDA4MY4+Xdli+SHXwUQKBgQDLEMqlwyvaGjuZ30l6F13fWnEt9PNCtJsa\n" |
| 1722 |
"nsdKJKyFMThdysY/PK40o2GTRRhgYa2jigN3OCYSSznRRZRlqznqL1bOLlYV6zS8\n" |
| 1723 |
"TGhdLXuApyLAjZYIK4RtZJYGR9+yg8rH13uNektgW8KnHh5Ko/ptRVoEukf3SBsh\n" |
| 1724 |
"f0Fib3ylDQKBgE11Bth0+bMJ6bLpNEPiphSjosVQ6ISe37R8/3Pi0y5uyxM8tqcG\n" |
| 1725 |
"3WDg2gt2pAmM1CsjQcCv2cHAwQ81kLVTmkZO4W4yZOd9ulrARKMPh/EM61KYfVhA\n" |
| 1726 |
"sTp6S7py3WQocr0gM2rw8gHGm7NJY1j9F0EjhVaHMhKXuGQOyehtJw7xAoGAPwuA\n" |
| 1727 |
"jwRQSg+Y74XmbxRwHZcbynPhTpV6DkK7huZp9ZQ5ds0szZdOUqNi+PEbx1isKzj/\n" |
| 1728 |
"KHVzRHy8f5+FmicV/QIjhjHWokl6/vcN89faHzBE1tleejzgiYIQHfUUm3zVaUQa\n" |
| 1729 |
"ZOtSGaGDhpUQPIY6itBcSVl4XGqzmavDpgcNAMUCgYBFFGtG+RbSySzKfRUp3vc5\n" |
| 1730 |
"8YqIdrtXfW9gc9s1+Pw8wfgrY0Rrvy+e3ClSwgGENxgxBvWvhzq2m0S8x2jdLAl1\n" |
| 1731 |
"b+VLGCOpUvS4iN2yrHkoHS7BSW40wLuVooJUAaNOIEPqiv1JC75q2dhTRrANp6WB\n" |
| 1732 |
"bm+7yWVTNlXYuKQqtuOkNQ==\n" |
| 1733 |
"-----END PRIVATE KEY-----\n"; |
| 1734 |
|
| 1735 |
jwt = rd_kafka_oidc_assertion_create( |
| 1736 |
rk, private_key_pem, NULL, NULL, |
| 1737 |
RD_KAFKA_SASL_OAUTHBEARER_ASSERTION_ALGORITHM_RS256, NULL, |
| 1738 |
"test-subject", "test-issuer", "test-audience", 2, 300, rd_true); |
| 1739 |
|
| 1740 |
RD_UT_ASSERT(jwt != NULL, "Failed to create JWT assertion"); |
| 1741 |
|
| 1742 |
dot1 = strchr(jwt, '.'); |
| 1743 |
RD_UT_ASSERT(dot1 != NULL, "JWT missing first dot separator"); |
| 1744 |
|
| 1745 |
dot2 = strchr(dot1 + 1, '.'); |
| 1746 |
RD_UT_ASSERT(dot2 != NULL, "JWT missing second dot separator"); |
| 1747 |
|
| 1748 |
header_part = rd_strndup(jwt, dot1 - jwt); |
| 1749 |
payload_part = rd_strndup(dot1 + 1, dot2 - (dot1 + 1)); |
| 1750 |
signature_part = rd_strdup(dot2 + 1); |
| 1751 |
|
| 1752 |
RD_UT_ASSERT(strlen(header_part) > 0, "JWT header part is empty"); |
| 1753 |
RD_UT_ASSERT(strlen(payload_part) > 0, "JWT payload part is empty"); |
| 1754 |
RD_UT_ASSERT(strlen(signature_part) > 0, "JWT signature part is empty"); |
| 1755 |
|
| 1756 |
RD_UT_ASSERT(!strchr(header_part, '='), |
| 1757 |
"JWT header contains padding character"); |
| 1758 |
RD_UT_ASSERT(!strchr(payload_part, '='), |
| 1759 |
"JWT payload contains padding character"); |
| 1760 |
RD_UT_ASSERT(!strchr(signature_part, '='), |
| 1761 |
"JWT signature contains padding character"); |
| 1762 |
|
| 1763 |
RD_UT_ASSERT(!strchr(header_part, '+'), |
| 1764 |
"JWT header contains '+' character"); |
| 1765 |
RD_UT_ASSERT(!strchr(header_part, '/'), |
| 1766 |
"JWT header contains '/' character"); |
| 1767 |
RD_UT_ASSERT(!strchr(payload_part, '+'), |
| 1768 |
"JWT payload contains '+' character"); |
| 1769 |
RD_UT_ASSERT(!strchr(payload_part, '/'), |
| 1770 |
"JWT payload contains '/' character"); |
| 1771 |
RD_UT_ASSERT(!strchr(signature_part, '+'), |
| 1772 |
"JWT signature contains '+' character"); |
| 1773 |
RD_UT_ASSERT(!strchr(signature_part, '/'), |
| 1774 |
"JWT signature contains '/' character"); |
| 1775 |
|
| 1776 |
rd_free(header_part); |
| 1777 |
rd_free(payload_part); |
| 1778 |
rd_free(signature_part); |
| 1779 |
rd_free(jwt); |
| 1780 |
rd_free(rk); |
| 1781 |
|
| 1782 |
RD_UT_PASS(); |
| 1783 |
} |
| 1784 |
|
| 1785 |
int unittest_sasl_oauthbearer_oidc_jwt_bearer(void) { |
| 1786 |
int fails = 0; |
| 1787 |
|
| 1788 |
fails += ut_sasl_oauthbearer_oidc_jwt_bearer_base64url_encode(); |
| 1789 |
fails += ut_sasl_oauthbearer_oidc_jwt_bearer_build_request_body(); |
| 1790 |
|
| 1791 |
return fails; |
| 1792 |
} |
| 1793 |
|
| 1794 |
int unittest_sasl_oauthbearer_oidc_assertion(void) { |
| 1795 |
int fails = 0; |
| 1796 |
|
| 1797 |
fails += ut_sasl_oauthbearer_oidc_assertion_parse_from_file(); |
| 1798 |
fails += ut_sasl_oauthbearer_oidc_assertion_process_template_file(); |
| 1799 |
fails += ut_sasl_oauthbearer_oidc_assertion_create(); |
| 1800 |
|
| 1801 |
return fails; |
| 1802 |
} |