|
| 1 | +// Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +// or more contributor license agreements. See the NOTICE file |
| 3 | +// distributed with this work for additional information |
| 4 | +// regarding copyright ownership. The ASF licenses this file |
| 5 | +// to you under the Apache License, Version 2.0 (the |
| 6 | +// "License"); you may not use this file except in compliance |
| 7 | +// with the License. You may obtain a copy of the License at |
| 8 | +// |
| 9 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +// |
| 11 | +// Unless required by applicable law or agreed to in writing, |
| 12 | +// software distributed under the License is distributed on an |
| 13 | +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +// KIND, either express or implied. See the License for the |
| 15 | +// specific language governing permissions and limitations |
| 16 | +// under the License. |
| 17 | + |
| 18 | +#include "http_client_base.h" |
| 19 | + |
| 20 | +#include <chrono> |
| 21 | + |
| 22 | +#include "json_request.h" |
| 23 | + |
| 24 | +HttpClientBase::HeaderList HttpClientBase::DefaultJsonGetHeaders() { |
| 25 | + HeaderList headers; |
| 26 | + headers.insert({"Accept", kJsonContentType}); |
| 27 | + headers.insert({"User-Agent", kDefaultUserAgent}); |
| 28 | + return headers; |
| 29 | +} |
| 30 | + |
| 31 | +HttpClientBase::HeaderList HttpClientBase::DefaultJsonPostHeaders() { |
| 32 | + HeaderList headers; |
| 33 | + headers.insert({"Content-Type", kJsonContentType}); |
| 34 | + headers.insert({"Accept", kJsonContentType}); |
| 35 | + headers.insert({"User-Agent", kDefaultUserAgent}); |
| 36 | + return headers; |
| 37 | +} |
| 38 | + |
| 39 | +HttpClientBase::HttpResponse HttpClientBase::Get(const std::string& endpoint, bool auth_required) { |
| 40 | + // Lambda to build the request and make the actual call. |
| 41 | + const auto attempt = [&]() -> HttpResponse { |
| 42 | + auto headers = DefaultJsonGetHeaders(); |
| 43 | + if (auth_required) { |
| 44 | + auto auth_error = AddAuthorizationHeader(headers); |
| 45 | + if (!auth_error.empty()) { |
| 46 | + return HttpResponse(0, "", auth_error); |
| 47 | + } |
| 48 | + } |
| 49 | + return DoGet(endpoint, headers); |
| 50 | + }; |
| 51 | + |
| 52 | + // First attempt |
| 53 | + auto result = attempt(); |
| 54 | + |
| 55 | + // If we got 401 Unauthorized and auth was required, invalidate token and retry once |
| 56 | + // This handles cases where the cached token expired between validation and use |
| 57 | + if (auth_required && result.status_code == 401) { |
| 58 | + InvalidateCachedToken(); |
| 59 | + result = attempt(); // Second (final) attempt with fresh token |
| 60 | + } |
| 61 | + return result; |
| 62 | +} |
| 63 | + |
| 64 | +HttpClientBase::HttpResponse HttpClientBase::Post(const std::string& endpoint, |
| 65 | + const std::string& json_body, |
| 66 | + bool auth_required) { |
| 67 | + // Lambda to build the request and make the actual call. |
| 68 | + const auto attempt = [&]() -> HttpResponse { |
| 69 | + auto headers = DefaultJsonPostHeaders(); |
| 70 | + if (auth_required) { |
| 71 | + auto auth_error = AddAuthorizationHeader(headers); |
| 72 | + if (!auth_error.empty()) { |
| 73 | + return HttpResponse(0, "", auth_error); |
| 74 | + } |
| 75 | + } |
| 76 | + return DoPost(endpoint, json_body, headers); |
| 77 | + }; |
| 78 | + |
| 79 | + // First attempt |
| 80 | + auto result = attempt(); |
| 81 | + |
| 82 | + // If we got 401 Unauthorized and auth was required, invalidate token and retry once |
| 83 | + // This handles cases where the cached token expired between validation and use |
| 84 | + if (auth_required && result.status_code == 401) { |
| 85 | + InvalidateCachedToken(); |
| 86 | + result = attempt(); // Second (final) attempt with fresh token |
| 87 | + } |
| 88 | + return result; |
| 89 | +} |
| 90 | + |
| 91 | +std::string HttpClientBase::AddAuthorizationHeader(HeaderList& headers) { |
| 92 | + // Get the valid token or an error message. |
| 93 | + std::string token_or_error; |
| 94 | + auto token_opt = EnsureValidToken(token_or_error); |
| 95 | + if (!token_opt.has_value()) { |
| 96 | + return token_or_error; |
| 97 | + } |
| 98 | + |
| 99 | + // Replace any existing Authorization header with: "<token_type> <token>". |
| 100 | + // Return an empty string if successful, otherwise return the error message. |
| 101 | + headers.erase(kAuthorizationHeader); |
| 102 | + std::string auth_value = token_opt->token_type; |
| 103 | + if (auth_value.back() != ' ') { |
| 104 | + auth_value.push_back(' '); |
| 105 | + } |
| 106 | + auth_value += token_opt->token; |
| 107 | + headers.insert({kAuthorizationHeader, auth_value}); |
| 108 | + return ""; |
| 109 | +} |
| 110 | + |
| 111 | +std::optional<HttpClientBase::TokenWithExpiration> HttpClientBase::EnsureValidToken(std::string& error) { |
| 112 | + |
| 113 | + const auto now_epoch_seconds = []() -> std::int64_t { |
| 114 | + const auto now = std::chrono::system_clock::now(); |
| 115 | + const auto secs = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count(); |
| 116 | + return static_cast<std::int64_t>(secs); |
| 117 | + }; |
| 118 | + |
| 119 | + // Adds padding to the expiration time to "expire" the token early and prevent going too close to the expiration time. |
| 120 | + const auto is_token_valid_at = [&](std::int64_t now) -> bool { |
| 121 | + return cached_token_.has_value() && |
| 122 | + !cached_token_->token.empty() && |
| 123 | + cached_token_->expires_at > (now + kTokenExpirySkewSeconds); |
| 124 | + }; |
| 125 | + |
| 126 | + error.clear(); |
| 127 | + const auto now = now_epoch_seconds(); |
| 128 | + |
| 129 | + { |
| 130 | + std::unique_lock<std::mutex> lock(token_mutex_); |
| 131 | + if (is_token_valid_at(now)) { |
| 132 | + return cached_token_; |
| 133 | + } |
| 134 | + while (token_fetch_in_progress_) { |
| 135 | + token_cv_.wait(lock); |
| 136 | + if (is_token_valid_at(now_epoch_seconds())) { |
| 137 | + return cached_token_; |
| 138 | + } |
| 139 | + } |
| 140 | + token_fetch_in_progress_ = true; |
| 141 | + } // Release token_mutex_ here |
| 142 | + |
| 143 | + // Fetch token without holding token_mutex_ |
| 144 | + // - avoids blocking other threads from entering EnsureValidToken() and waiting on token_cv_ |
| 145 | + // - keeps the critical section small (network I/O can be slow) |
| 146 | + // We re-acquire token_mutex_ below to update cached_token_, clear token_fetch_in_progress_, and notify waiters. |
| 147 | + |
| 148 | + std::optional<TokenWithExpiration> fetched = FetchToken(error); |
| 149 | + |
| 150 | + { |
| 151 | + std::lock_guard<std::mutex> lock(token_mutex_); |
| 152 | + token_fetch_in_progress_ = false; |
| 153 | + if (fetched.has_value()) { |
| 154 | + cached_token_ = fetched; |
| 155 | + } |
| 156 | + } |
| 157 | + token_cv_.notify_all(); |
| 158 | + return fetched; |
| 159 | +} |
| 160 | + |
| 161 | +std::optional<HttpClientBase::TokenWithExpiration> HttpClientBase::FetchToken(std::string& error) { |
| 162 | + error.clear(); |
| 163 | + TokenRequest token_req; |
| 164 | + token_req.credential_values_ = credentials_; |
| 165 | + |
| 166 | + // IMPORTANT: call DoPost directly (authless) to avoid recursion. |
| 167 | + auto http_resp = DoPost("/token", token_req.ToJson(), DefaultJsonPostHeaders()); |
| 168 | + if (!http_resp.error_message.empty() || http_resp.status_code != 200) { |
| 169 | + error = http_resp.error_message + " (status code: " + std::to_string(http_resp.status_code) + ")"; |
| 170 | + return std::nullopt; |
| 171 | + } |
| 172 | + |
| 173 | + TokenResponse token_resp; |
| 174 | + token_resp.Parse(http_resp.result); |
| 175 | + if (!token_resp.IsValid()) { |
| 176 | + error = token_resp.GetValidationError(); |
| 177 | + if (error.empty()) { |
| 178 | + error = "While reading token response, found an invalid token response: " + http_resp.result; |
| 179 | + } |
| 180 | + return std::nullopt; |
| 181 | + } |
| 182 | + |
| 183 | + TokenWithExpiration result; |
| 184 | + result.token = token_resp.token_.value(); |
| 185 | + result.token_type = token_resp.token_type_.value(); |
| 186 | + result.expires_at = token_resp.expires_at_.value(); |
| 187 | + return result; |
| 188 | +} |
| 189 | + |
| 190 | +void HttpClientBase::InvalidateCachedToken() { |
| 191 | + std::lock_guard<std::mutex> lock(token_mutex_); |
| 192 | + cached_token_ = std::nullopt; |
| 193 | +} |
0 commit comments