Skip to content

Commit

Permalink
Add mutex around key refresh with get_public_keys_from_web()
Browse files Browse the repository at this point in the history
Limit key refresh to a single simultaneous request to avoid
overloading issuers.
  • Loading branch information
jthiltges committed Apr 29, 2024
1 parent 4f82163 commit f87b59c
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/scitokens_internal.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ struct CurlRaii {

CurlRaii myCurl;

std::mutex key_refresh_mutex;

} // namespace

namespace scitokens {
Expand Down Expand Up @@ -792,11 +794,15 @@ Validator::get_public_key_pem(const std::string &issuer, const std::string &kid,

if (get_public_keys_from_db(issuer, now, result->m_keys,
result->m_next_update)) {
if (now > result->m_next_update) {
std::unique_lock<std::mutex> lock(key_refresh_mutex, std::defer_lock);
// If refresh is due *and* the key refresh mutex is free, try to update
if (now > result->m_next_update && lock.try_lock()) {
try {
result->m_ignore_error = true;
result = get_public_keys_from_web(
issuer, internal::SimpleCurlGet::default_timeout);
// Hold refresh mutex in the new result
result->m_refresh_lock = std::move(lock);
} catch (std::runtime_error &) {
result->m_do_store = false;
// ignore the exception: we have a valid set of keys already
Expand Down
2 changes: 2 additions & 0 deletions src/scitokens_internal.h
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@

#include <memory>
#include <mutex>
#include <sstream>
#include <unordered_map>

Expand Down Expand Up @@ -212,6 +213,7 @@ class AsyncStatus {
bool m_has_metadata{false};
bool m_oauth_fallback{false};
AsyncState m_state{DOWNLOAD_METADATA};
std::unique_lock<std::mutex> m_refresh_lock;

int64_t m_next_update{-1};
int64_t m_expires{-1};
Expand Down

0 comments on commit f87b59c

Please sign in to comment.