Skip to content

Commit

Permalink
Handle the exception from the token supplier (apache#458)
Browse files Browse the repository at this point in the history
### Motivation

When a token supplier is passed to the `AuthToken`, if exceptions are
thrown from it, the application will crash immediately. A typical case
is the Python wrapper might raise an exception when trying to get token.

### Modifications

Catch the exception in `Commands::newConnect` because the token supplier
is called in it. Then convert it to `ResultAuthenticationError`. Add
`testTokenSupplierException` to verify it.
  • Loading branch information
BewareMyPower authored Nov 27, 2024
1 parent ce6c4bc commit e264cf7
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
11 changes: 9 additions & 2 deletions lib/ClientConnection.cc
Original file line number Diff line number Diff line change
Expand Up @@ -528,8 +528,15 @@ void ClientConnection::handleHandshake(const ASIO_ERROR& err) {

bool connectingThroughProxy = logicalAddress_ != physicalAddress_;
Result result = ResultOk;
SharedBuffer buffer = Commands::newConnect(authentication_, logicalAddress_, connectingThroughProxy,
clientVersion_, result);
SharedBuffer buffer;
try {
buffer = Commands::newConnect(authentication_, logicalAddress_, connectingThroughProxy,
clientVersion_, result);
} catch (const std::exception& e) {
LOG_ERROR(cnxString_ << "Failed to create Connect command: " << e.what());
close(ResultAuthenticationError);
return;
}
if (result != ResultOk) {
LOG_ERROR(cnxString_ << "Failed to establish connection: " << result);
close(result);
Expand Down
10 changes: 10 additions & 0 deletions tests/AuthTokenTest.cc
Original file line number Diff line number Diff line change
Expand Up @@ -200,3 +200,13 @@ TEST(AuthPluginToken, testNoAuthWithHttp) {
result = client.subscribe(topicName, subName, consumer);
ASSERT_EQ(ResultConnectError, result);
}

TEST(AuthPluginToken, testTokenSupplierException) {
ClientConfiguration config;
config.setAuth(
AuthToken::create([]() -> std::string { throw std::runtime_error("failed to generate token"); }));
Client client(serviceUrl, config);
Producer producer;
ASSERT_EQ(ResultAuthenticationError, client.createProducer("topic", producer));
ASSERT_EQ(ResultOk, client.close());
}

0 comments on commit e264cf7

Please sign in to comment.