| 1 | /* |
| 2 | * Copyright (C) 2026 Teluu Inc. (http://www.teluu.com) |
| 3 | * |
| 4 | * This program is free software; you can redistribute it and/or modify |
| 5 | * it under the terms of the GNU General Public License as published by |
| 6 | * the Free Software Foundation; either version 2 of the License, or |
| 7 | * (at your option) any later version. |
| 8 | * |
| 9 | * This program is distributed in the hope that it will be useful, |
| 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | * GNU General Public License for more details. |
| 13 | * |
| 14 | * You should have received a copy of the GNU General Public License |
| 15 | * along with this program; if not, write to the Free Software |
| 16 | * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
| 17 | */ |
| 18 | |
| 19 | /* |
| 20 | * pjsua2-level tests for the AuthChallenge class. |
| 21 | * |
| 22 | * Scenarios covered: |
| 23 | * 1. Immediate (sync) response: onAuthChallenge calls respond() directly. |
| 24 | * 2. Deferred response: onAuthChallenge calls defer(), event loop responds |
| 25 | * with existing account credentials. |
| 26 | * 3. Deferred respond with credentials: no creds on account, event loop |
| 27 | * calls respond(creds). |
| 28 | * 4. Deferred abandon: event loop calls abandon(). |
| 29 | * 5. Account deletion with outstanding deferred challenge. |
| 30 | */ |
| 31 | |
| 32 | #include <iostream> |
| 33 | #include <memory> |
| 34 | |
| 35 | #include "auth_challenge.hpp" |
| 36 | |
| 37 | #define THIS_FILE "auth_challenge.cpp" |
| 38 | |
| 39 | /* Always-active assertion (not compiled out by NDEBUG). */ |
| 40 | #define TEST_ASSERT(expr) \ |
| 41 | do { \ |
| 42 | if (!(expr)) { \ |
| 43 | PJ_LOG(1,(THIS_FILE, "TEST ASSERT FAILED: %s (%s:%d)", \ |
| 44 | #expr, THIS_FILE, __LINE__)); \ |
| 45 | pj_log_push_indent(); \ |
| 46 | throw Error(PJ_EINVAL, "test assertion", \ |
| 47 | #expr, THIS_FILE, __LINE__); \ |
| 48 | } \ |
| 49 | } while (0) |
| 50 | #define TEST_USER "pjsua2-auth-test" |
| 51 | |
| 52 | using namespace pj; |
| 53 | |
| 54 | /***************************************************************************** |
| 55 | * Mock registrar (C-level module on pjsua's endpoint) |
| 56 | * |
| 57 | * - First REGISTER without Authorization -> 401 + WWW-Authenticate |
| 58 | * - REGISTER with Authorization present -> 200 OK |
| 59 | *****************************************************************************/ |
| 60 | |
| 61 | static unsigned g_mock_req_count; |
| 62 | static unsigned g_mock_auth_count; |
| 63 | |
| 64 | static pj_bool_t g_mock_enabled; |
| 65 | |
| 66 | static pj_bool_t mock_registrar_on_rx_request(pjsip_rx_data *rdata) |
| 67 | { |
| 68 | pjsip_msg *msg = rdata->msg_info.msg; |
| 69 | pjsip_hdr hdr_list; |
| 70 | int code; |
| 71 | |
| 72 | if (!g_mock_enabled) |
| 73 | return PJ_FALSE; |
| 74 | |
| 75 | if (msg->line.req.method.id != PJSIP_REGISTER_METHOD) |
| 76 | return PJ_FALSE; |
| 77 | |
| 78 | /* Filter by From user */ |
| 79 | { |
| 80 | pjsip_sip_uri *uri; |
| 81 | uri = (pjsip_sip_uri*)pjsip_uri_get_uri( |
| 82 | rdata->msg_info.from->uri); |
| 83 | if (pj_strcmp2(&uri->user, TEST_USER) != 0) |
| 84 | return PJ_FALSE; |
| 85 | } |
| 86 | |
| 87 | g_mock_req_count++; |
| 88 | pj_list_init(&hdr_list); |
| 89 | |
| 90 | if (pjsip_msg_find_hdr(msg, PJSIP_H_AUTHORIZATION, NULL) == NULL) { |
| 91 | const pj_str_t hname = pj_str((char*)"WWW-Authenticate"); |
| 92 | const pj_str_t hvalue = |
| 93 | pj_str((char*)"Digest realm=\"test\", nonce=\"testnonce\""); |
| 94 | pjsip_generic_string_hdr *hwww = |
| 95 | pjsip_generic_string_hdr_create(rdata->tp_info.pool, |
| 96 | &hname, &hvalue); |
| 97 | pj_list_push_back(&hdr_list, hwww); |
| 98 | code = 401; |
| 99 | } else { |
| 100 | g_mock_auth_count++; |
| 101 | code = 200; |
| 102 | } |
| 103 | |
| 104 | pjsip_endpt_respond_stateless(pjsua_get_pjsip_endpt(), rdata, |
| 105 | code, NULL, &hdr_list, NULL); |
| 106 | return PJ_TRUE; |
| 107 | } |
| 108 | |
| 109 | static pjsip_module g_mock_reg_mod; |
| 110 | |
| 111 | static void reset_mock_registrar() |
| 112 | { |
| 113 | g_mock_req_count = 0; |
| 114 | g_mock_auth_count = 0; |
| 115 | g_mock_enabled = PJ_TRUE; |
| 116 | } |
| 117 | |
| 118 | |
| 119 | /***************************************************************************** |
| 120 | * Test state |
| 121 | *****************************************************************************/ |
| 122 | |
| 123 | enum TestAction { |
| 124 | ACTION_SYNC_RESPOND, |
| 125 | ACTION_DEFER_RESPOND, |
| 126 | ACTION_DEFER_RESPOND_CREDS, |
| 127 | ACTION_DEFER_ABANDON, |
| 128 | ACTION_DEFER_DELETE_ACC |
| 129 | }; |
| 130 | |
| 131 | struct AuthTestState { |
| 132 | TestAction action; |
| 133 | bool challengeReceived; |
| 134 | bool regDone; |
| 135 | int regCode; |
| 136 | bool deferEnabled; |
| 137 | std::unique_ptr<AuthChallenge> deferred; |
| 138 | }; |
| 139 | |
| 140 | static AuthTestState g_state; |
| 141 | |
| 142 | |
| 143 | /***************************************************************************** |
| 144 | * TestAccount — overrides onAuthChallenge and onRegState |
| 145 | *****************************************************************************/ |
| 146 | |
| 147 | class TestAccount : public Account |
| 148 | { |
| 149 | public: |
| 150 | using Account::Account; |
| 151 | |
| 152 | virtual void onRegState(OnRegStateParam &prm) override |
| 153 | { |
| 154 | g_state.regDone = true; |
| 155 | g_state.regCode = prm.code; |
| 156 | } |
| 157 | |
| 158 | virtual void onAuthChallenge(OnAuthChallengeParam &prm) override |
| 159 | { |
| 160 | g_state.challengeReceived = true; |
| 161 | |
| 162 | switch (g_state.action) { |
| 163 | case ACTION_SYNC_RESPOND: |
| 164 | /* Respond immediately (sync path) */ |
| 165 | prm.challenge.respond(); |
| 166 | break; |
| 167 | |
| 168 | case ACTION_DEFER_RESPOND: |
| 169 | case ACTION_DEFER_RESPOND_CREDS: |
| 170 | case ACTION_DEFER_ABANDON: |
| 171 | case ACTION_DEFER_DELETE_ACC: |
| 172 | if (!g_state.deferEnabled) { |
| 173 | /* Let the library handle it */ |
| 174 | return; |
| 175 | } |
| 176 | try { |
| 177 | g_state.deferred.reset(prm.challenge.defer()); |
| 178 | } catch (Error &err) { |
| 179 | std::cerr << "defer() failed: " << err.info() << std::endl; |
| 180 | } |
| 181 | break; |
| 182 | } |
| 183 | } |
| 184 | }; |
| 185 | |
| 186 | |
| 187 | /***************************************************************************** |
| 188 | * Helpers |
| 189 | *****************************************************************************/ |
| 190 | |
| 191 | static void poll_events(unsigned max_ms) |
| 192 | { |
| 193 | unsigned elapsed = 0; |
| 194 | while (elapsed < max_ms && !g_state.regDone) { |
| 195 | pjsua_handle_events(50); |
| 196 | elapsed += 50; |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | static void init_state(TestAction action) |
| 201 | { |
| 202 | g_state.action = action; |
| 203 | g_state.challengeReceived = false; |
| 204 | g_state.regDone = false; |
| 205 | g_state.regCode = 0; |
| 206 | g_state.deferEnabled = true; |
| 207 | g_state.deferred.reset(); |
| 208 | reset_mock_registrar(); |
| 209 | } |
| 210 | |
| 211 | static AccountConfig make_acc_config(int port, bool with_creds) |
| 212 | { |
| 213 | AccountConfig cfg; |
| 214 | cfg.idUri = "sip:" TEST_USER "@pjsip.org"; |
| 215 | cfg.regConfig.registrarUri = "sip:127.0.0.1:" + std::to_string(port); |
| 216 | cfg.regConfig.registerOnAdd = false; |
| 217 | |
| 218 | if (with_creds) { |
| 219 | AuthCredInfo cred("digest", "*", TEST_USER, 0, "secret"); |
| 220 | cfg.sipConfig.authCreds.push_back(PJSUA2_MOVE(cred)); |
| 221 | } |
| 222 | |
| 223 | cfg.natConfig.contactRewriteUse = 0; |
| 224 | |
| 225 | return cfg; |
| 226 | } |
| 227 | |
| 228 | |
| 229 | /***************************************************************************** |
| 230 | * AuthChallengeTests implementation |
| 231 | *****************************************************************************/ |
| 232 | |
| 233 | AuthChallengeTests::AuthChallengeTests() |
| 234 | : port(0) |
| 235 | { |
| 236 | ep.libCreate(); |
| 237 | |
| 238 | EpConfig epCfg; |
| 239 | epCfg.logConfig.level = 3; |
| 240 | epCfg.logConfig.consoleLevel = 3; |
| 241 | epCfg.uaConfig.userAgent = "pjsua2-auth-test"; |
| 242 | epCfg.uaConfig.threadCnt = 0; /* Single-threaded: drive events manually */ |
| 243 | ep.libInit(epCfg); |
| 244 | |
| 245 | TransportConfig tcfg; |
| 246 | tcfg.port = 0; /* ephemeral */ |
| 247 | TransportId tpId = ep.transportCreate(PJSIP_TRANSPORT_UDP, tcfg); |
| 248 | |
| 249 | ep.libStart(); |
| 250 | |
| 251 | /* Get ephemeral port via C API */ |
| 252 | { |
| 253 | pjsua_transport_info ti; |
| 254 | pjsua_transport_get_info(tpId, &ti); |
| 255 | port = pj_sockaddr_get_port(&ti.local_addr); |
| 256 | } |
| 257 | |
| 258 | /* Initialize and register mock registrar module */ |
| 259 | { |
| 260 | pj_status_t status; |
| 261 | pj_bzero(&g_mock_reg_mod, sizeof(g_mock_reg_mod)); |
| 262 | pj_str_t name = pj_str((char*)"mod-pjsua2-auth-reg"); |
| 263 | g_mock_reg_mod.name = name; |
| 264 | g_mock_reg_mod.id = -1; |
| 265 | g_mock_reg_mod.priority = PJSIP_MOD_PRIORITY_APPLICATION; |
| 266 | g_mock_reg_mod.on_rx_request = &mock_registrar_on_rx_request; |
| 267 | |
| 268 | status = pjsip_endpt_register_module(pjsua_get_pjsip_endpt(), |
| 269 | &g_mock_reg_mod); |
| 270 | TEST_ASSERT(status == PJ_SUCCESS); |
| 271 | (void)status; |
| 272 | } |
| 273 | |
| 274 | std::cout << "*** AuthChallengeTests started on port " << port << std::endl; |
| 275 | } |
| 276 | |
| 277 | AuthChallengeTests::~AuthChallengeTests() |
| 278 | { |
| 279 | g_state.deferred.reset(); |
| 280 | |
| 281 | if (g_mock_reg_mod.id != -1) { |
| 282 | pjsip_endpt_unregister_module(pjsua_get_pjsip_endpt(), |
| 283 | &g_mock_reg_mod); |
| 284 | } |
| 285 | |
| 286 | try { |
| 287 | ep.libDestroy(); |
| 288 | } catch (const Error &e) { |
| 289 | std::cerr << "Error during libDestroy: " << e.reason << std::endl; |
| 290 | } |
| 291 | } |
| 292 | |
| 293 | |
| 294 | /***************************************************************************** |
| 295 | * Test 1: immediateResponse |
| 296 | * |
| 297 | * Account has credentials. 401 -> onAuthChallenge calls respond() |
| 298 | * synchronously. Expect 200 OK. |
| 299 | *****************************************************************************/ |
| 300 | void AuthChallengeTests::immediateResponse() |
| 301 | { |
| 302 | std::cout << "\n=== AUTH TEST: immediateResponse ===" << std::endl; |
| 303 | init_state(ACTION_SYNC_RESPOND); |
| 304 | |
| 305 | AccountConfig cfg = make_acc_config(port, true); |
| 306 | std::unique_ptr<TestAccount> acc(new TestAccount); |
| 307 | acc->create(cfg); |
| 308 | acc->setRegistration(true); |
| 309 | |
| 310 | poll_events(30000); |
| 311 | |
| 312 | TEST_ASSERT(g_state.challengeReceived == true); |
| 313 | TEST_ASSERT(g_state.regDone == true); |
| 314 | TEST_ASSERT(g_state.regCode == 200); |
| 315 | TEST_ASSERT(g_mock_req_count >= 2); |
| 316 | TEST_ASSERT(g_mock_auth_count >= 1); |
| 317 | |
| 318 | /* Disable mock registrar before destroying account so the |
| 319 | * unregister doesn't trigger a 401 on a deleted account. |
| 320 | */ |
| 321 | g_mock_enabled = PJ_FALSE; |
| 322 | g_state.deferEnabled = false; |
| 323 | acc.reset(); |
| 324 | pjsua_handle_events(500); |
| 325 | |
| 326 | std::cout << " immediateResponse: PASSED\n"; |
| 327 | } |
| 328 | |
| 329 | |
| 330 | /***************************************************************************** |
| 331 | * Test 2: deferredResponse |
| 332 | * |
| 333 | * Account has credentials. 401 -> onAuthChallenge calls defer(). |
| 334 | * Event loop later calls respond(). Expect 200 OK. |
| 335 | *****************************************************************************/ |
| 336 | void AuthChallengeTests::deferredResponse() |
| 337 | { |
| 338 | std::cout << "\n=== AUTH TEST: deferredResponse ===\n"; |
| 339 | init_state(ACTION_DEFER_RESPOND); |
| 340 | |
| 341 | AccountConfig cfg = make_acc_config(port, true); |
| 342 | std::unique_ptr<TestAccount> acc(new TestAccount); |
| 343 | acc->create(cfg); |
| 344 | acc->setRegistration(true); |
| 345 | |
| 346 | /* Wait for the deferred state to be captured */ |
| 347 | { |
| 348 | unsigned elapsed = 0; |
| 349 | while (elapsed < 10000 && !g_state.deferred) { |
| 350 | pjsua_handle_events(50); |
| 351 | elapsed += 50; |
| 352 | } |
| 353 | } |
| 354 | TEST_ASSERT(g_state.deferred != nullptr); |
| 355 | TEST_ASSERT(g_state.deferred->isValid() == true); |
| 356 | |
| 357 | /* Now respond */ |
| 358 | pj_status_t status = g_state.deferred->respond(); |
| 359 | TEST_ASSERT(status == PJ_SUCCESS); |
| 360 | TEST_ASSERT(g_state.deferred->isValid() == false); |
| 361 | g_state.deferred.reset(); |
| 362 | |
| 363 | poll_events(10000); |
| 364 | |
| 365 | TEST_ASSERT(g_state.regDone == true); |
| 366 | TEST_ASSERT(g_state.regCode == 200); |
| 367 | TEST_ASSERT(g_mock_auth_count >= 1); |
| 368 | |
| 369 | g_mock_enabled = PJ_FALSE; |
| 370 | g_state.deferEnabled = false; |
| 371 | acc.reset(); |
| 372 | pjsua_handle_events(500); |
| 373 | |
| 374 | std::cout << " deferredResponse: PASSED\n"; |
| 375 | } |
| 376 | |
| 377 | |
| 378 | /***************************************************************************** |
| 379 | * Test 3: deferredRespondWithCreds |
| 380 | * |
| 381 | * Account has NO credentials. 401 -> onAuthChallenge calls defer(). |
| 382 | * Event loop calls respond(creds) with credentials. Expect 200 OK. |
| 383 | *****************************************************************************/ |
| 384 | void AuthChallengeTests::deferredRespondWithCreds() |
| 385 | { |
| 386 | std::cout << "\n=== AUTH TEST: deferredRespondWithCreds ===\n"; |
| 387 | init_state(ACTION_DEFER_RESPOND_CREDS); |
| 388 | |
| 389 | AccountConfig cfg = make_acc_config(port, false /* no creds */); |
| 390 | std::unique_ptr<TestAccount> acc(new TestAccount); |
| 391 | acc->create(cfg); |
| 392 | acc->setRegistration(true); |
| 393 | |
| 394 | /* Wait for deferred state */ |
| 395 | { |
| 396 | unsigned elapsed = 0; |
| 397 | while (elapsed < 10000 && !g_state.deferred) { |
| 398 | pjsua_handle_events(50); |
| 399 | elapsed += 50; |
| 400 | } |
| 401 | } |
| 402 | TEST_ASSERT(g_state.deferred != nullptr); |
| 403 | TEST_ASSERT(g_state.deferred->isValid() == true); |
| 404 | |
| 405 | /* Respond with credentials */ |
| 406 | AuthCredInfoVector creds; |
| 407 | creds.push_back(AuthCredInfo("digest", "*", TEST_USER, 0, "secret")); |
| 408 | pj_status_t status = g_state.deferred->respond(creds); |
| 409 | TEST_ASSERT(status == PJ_SUCCESS); |
| 410 | g_state.deferred.reset(); |
| 411 | |
| 412 | poll_events(10000); |
| 413 | |
| 414 | TEST_ASSERT(g_state.regDone == true); |
| 415 | TEST_ASSERT(g_state.regCode == 200); |
| 416 | TEST_ASSERT(g_mock_auth_count >= 1); |
| 417 | |
| 418 | g_mock_enabled = PJ_FALSE; |
| 419 | g_state.deferEnabled = false; |
| 420 | acc.reset(); |
| 421 | pjsua_handle_events(500); |
| 422 | |
| 423 | std::cout << " deferredRespondWithCreds: PASSED\n"; |
| 424 | } |
| 425 | |
| 426 | |
| 427 | /***************************************************************************** |
| 428 | * Test 4: deferredAbandon |
| 429 | * |
| 430 | * Account has credentials. 401 -> onAuthChallenge calls defer(). |
| 431 | * Event loop calls abandon(). No authenticated REGISTER should be sent |
| 432 | * for this challenge. |
| 433 | *****************************************************************************/ |
| 434 | void AuthChallengeTests::deferredAbandon() |
| 435 | { |
| 436 | std::cout << "\n=== AUTH TEST: deferredAbandon ===\n"; |
| 437 | init_state(ACTION_DEFER_ABANDON); |
| 438 | |
| 439 | AccountConfig cfg = make_acc_config(port, true); |
| 440 | /* Disable auto-registration so we control the flow */ |
| 441 | cfg.regConfig.registerOnAdd = false; |
| 442 | std::unique_ptr<TestAccount> acc(new TestAccount); |
| 443 | acc->create(cfg); |
| 444 | |
| 445 | /* Manually trigger registration */ |
| 446 | acc->setRegistration(true); |
| 447 | |
| 448 | /* Wait for deferred state */ |
| 449 | { |
| 450 | unsigned elapsed = 0; |
| 451 | while (elapsed < 10000 && !g_state.deferred) { |
| 452 | pjsua_handle_events(50); |
| 453 | elapsed += 50; |
| 454 | } |
| 455 | } |
| 456 | TEST_ASSERT(g_state.deferred != nullptr); |
| 457 | |
| 458 | /* To abandon without crashing: delete the account first (which |
| 459 | * invalidates it and destroys the regc/auth token), then destroy |
| 460 | * the deferred AuthChallenge. The destructor's TRY_LOCK + is_valid |
| 461 | * guard will see the account is gone and skip the C-level abandon. |
| 462 | * |
| 463 | * We must NOT call pjsip_auth_clt_async_abandon directly because |
| 464 | * it can crash when called from outside the auth callback chain. |
| 465 | */ |
| 466 | g_mock_enabled = PJ_FALSE; |
| 467 | g_state.deferEnabled = false; |
| 468 | |
| 469 | TEST_ASSERT(g_state.challengeReceived == true); |
| 470 | |
| 471 | acc.reset(); |
| 472 | pjsua_handle_events(500); |
| 473 | |
| 474 | /* Now safe to destroy deferred state — account is already gone */ |
| 475 | g_state.deferred.reset(); |
| 476 | |
| 477 | std::cout << " deferredAbandon: PASSED" << std::endl; |
| 478 | } |
| 479 | |
| 480 | |
| 481 | /***************************************************************************** |
| 482 | * Test 5: accountDeleteWithPending |
| 483 | * |
| 484 | * Account has credentials. 401 -> onAuthChallenge calls defer(). |
| 485 | * Account is deleted while deferred state is outstanding. The |
| 486 | * AuthChallenge destructor must handle the invalid account gracefully. |
| 487 | *****************************************************************************/ |
| 488 | void AuthChallengeTests::accountDeleteWithPending() |
| 489 | { |
| 490 | std::cout << "\n=== AUTH TEST: accountDeleteWithPending ===\n"; |
| 491 | init_state(ACTION_DEFER_DELETE_ACC); |
| 492 | |
| 493 | AccountConfig cfg = make_acc_config(port, true); |
| 494 | cfg.regConfig.registerOnAdd = false; |
| 495 | std::unique_ptr<TestAccount> acc(new TestAccount); |
| 496 | acc->create(cfg); |
| 497 | |
| 498 | /* Manually trigger registration */ |
| 499 | acc->setRegistration(true); |
| 500 | |
| 501 | /* Wait for deferred state */ |
| 502 | { |
| 503 | unsigned elapsed = 0; |
| 504 | while (elapsed < 10000 && !g_state.deferred) { |
| 505 | pjsua_handle_events(50); |
| 506 | elapsed += 50; |
| 507 | } |
| 508 | } |
| 509 | TEST_ASSERT(g_state.deferred != nullptr); |
| 510 | TEST_ASSERT(g_state.deferred->isValid() == true); |
| 511 | |
| 512 | /* Delete the account while deferred state is outstanding. |
| 513 | * Disable mock registrar to prevent 401 on unregister (which would |
| 514 | * trigger on_auth_challenge on a deleted account). |
| 515 | */ |
| 516 | g_mock_enabled = PJ_FALSE; |
| 517 | g_state.deferEnabled = false; |
| 518 | acc.reset(); |
| 519 | |
| 520 | /* Let transactions settle */ |
| 521 | pjsua_handle_events(500); |
| 522 | |
| 523 | /* The deferred AuthChallenge should still exist but its account |
| 524 | * is gone. isValid() should return false because the account |
| 525 | * has been deleted. |
| 526 | */ |
| 527 | TEST_ASSERT(g_state.deferred->isValid() == false); |
| 528 | |
| 529 | /* Destroy the deferred state — this exercises the destructor's |
| 530 | * TRY_LOCK + is_valid guard path. Must not crash. |
| 531 | */ |
| 532 | g_state.deferred.reset(); |
| 533 | |
| 534 | pjsua_handle_events(500); |
| 535 | |
| 536 | std::cout << " accountDeleteWithPending: PASSED\n"; |
| 537 | } |