|
| 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_interface.h" |
| 19 | + |
| 20 | +#include <chrono> |
| 21 | + |
| 22 | +#include "json_request.h" |
| 23 | + |
| 24 | +HttpClientInterface::HeaderList HttpClientInterface::DefaultJsonGetHeaders() { |
| 25 | + HeaderList headers; |
| 26 | + headers.insert({"Accept", kJsonContentType}); |
| 27 | + headers.insert({"User-Agent", kDefaultUserAgent}); |
| 28 | + return headers; |
| 29 | +} |
| 30 | + |
| 31 | +HttpClientInterface::HeaderList HttpClientInterface::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 | +HttpClientInterface::HttpResponse HttpClientInterface::Get(const std::string& endpoint, bool auth_required) { |
| 40 | + const auto attempt = [&]() -> HttpResponse { |
| 41 | + auto headers = DefaultJsonGetHeaders(); |
| 42 | + if (auth_required) { |
| 43 | + auto auth_error = AddAuthorizationHeader(headers); |
| 44 | + if (!auth_error.empty()) { |
| 45 | + return HttpResponse(0, "", auth_error); |
| 46 | + } |
| 47 | + } |
| 48 | + return DoGet(endpoint, headers); |
| 49 | + }; |
| 50 | + |
| 51 | + auto result = attempt(); |
| 52 | + if (auth_required && result.status_code == 401) { |
| 53 | + InvalidateCachedToken(); |
| 54 | + result = attempt(); |
| 55 | + } |
| 56 | + return result; |
| 57 | +} |
| 58 | + |
| 59 | +HttpClientInterface::HttpResponse HttpClientInterface::Post(const std::string& endpoint, |
| 60 | + const std::string& json_body, |
| 61 | + bool auth_required) { |
| 62 | + const auto attempt = [&]() -> HttpResponse { |
| 63 | + auto headers = DefaultJsonPostHeaders(); |
| 64 | + if (auth_required) { |
| 65 | + auto auth_error = AddAuthorizationHeader(headers); |
| 66 | + if (!auth_error.empty()) { |
| 67 | + return HttpResponse(0, "", auth_error); |
| 68 | + } |
| 69 | + } |
| 70 | + return DoPost(endpoint, json_body, headers); |
| 71 | + }; |
| 72 | + |
| 73 | + auto result = attempt(); |
| 74 | + if (auth_required && result.status_code == 401) { |
| 75 | + InvalidateCachedToken(); |
| 76 | + result = attempt(); |
| 77 | + } |
| 78 | + return result; |
| 79 | +} |
| 80 | + |
| 81 | +std::string HttpClientInterface::AddAuthorizationHeader(HeaderList& headers) { |
| 82 | + std::string token_or_error; |
| 83 | + auto token_opt = EnsureValidToken(token_or_error); |
| 84 | + if (!token_opt.has_value()) { |
| 85 | + return token_or_error; |
| 86 | + } |
| 87 | + |
| 88 | + headers.erase(kAuthorizationHeader); |
| 89 | + std::string auth_value = token_opt->token_type; |
| 90 | + if (auth_value.back() != ' ') { |
| 91 | + auth_value.push_back(' '); |
| 92 | + } |
| 93 | + auth_value += token_opt->token; |
| 94 | + headers.insert({kAuthorizationHeader, auth_value}); |
| 95 | + return ""; |
| 96 | +} |
| 97 | + |
| 98 | +std::optional<HttpClientInterface::CachedToken> HttpClientInterface::EnsureValidToken(std::string& error) { |
| 99 | + |
| 100 | + const auto now_epoch_seconds = []() -> std::int64_t { |
| 101 | + const auto now = std::chrono::system_clock::now(); |
| 102 | + const auto secs = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count(); |
| 103 | + return static_cast<std::int64_t>(secs); |
| 104 | + }; |
| 105 | + |
| 106 | + const auto is_token_valid_at = [&](std::int64_t now) -> bool { |
| 107 | + return cached_token_.has_value() && |
| 108 | + !cached_token_->token.empty() && |
| 109 | + cached_token_->expires_at > (now + kTokenExpirySkewSeconds); |
| 110 | + }; |
| 111 | + |
| 112 | + error.clear(); |
| 113 | + const auto now = now_epoch_seconds(); |
| 114 | + |
| 115 | + { |
| 116 | + std::unique_lock<std::mutex> lock(token_mutex_); |
| 117 | + if (is_token_valid_at(now)) { |
| 118 | + return cached_token_; |
| 119 | + } |
| 120 | + while (token_fetch_in_progress_) { |
| 121 | + token_cv_.wait(lock); |
| 122 | + if (is_token_valid_at(now_epoch_seconds())) { |
| 123 | + return cached_token_; |
| 124 | + } |
| 125 | + } |
| 126 | + token_fetch_in_progress_ = true; |
| 127 | + } |
| 128 | + |
| 129 | + // Fetch token without holding token_mutex_. |
| 130 | + std::optional<CachedToken> fetched = FetchToken(error); |
| 131 | + |
| 132 | + { |
| 133 | + std::lock_guard<std::mutex> lock(token_mutex_); |
| 134 | + token_fetch_in_progress_ = false; |
| 135 | + if (fetched.has_value()) { |
| 136 | + cached_token_ = fetched; |
| 137 | + } |
| 138 | + } |
| 139 | + token_cv_.notify_all(); |
| 140 | + return fetched; |
| 141 | +} |
| 142 | + |
| 143 | +std::optional<HttpClientInterface::CachedToken> HttpClientInterface::FetchToken(std::string& error) { |
| 144 | + error.clear(); |
| 145 | + TokenRequest token_req; |
| 146 | + token_req.credential_values_ = credentials_; |
| 147 | + |
| 148 | + // IMPORTANT: call DoPost directly (authless) to avoid recursion. |
| 149 | + auto http_resp = DoPost("/token", token_req.ToJson(), DefaultJsonPostHeaders()); |
| 150 | + if (!http_resp.error_message.empty() || http_resp.status_code != 200) { |
| 151 | + error = http_resp.error_message + " (status code: " + std::to_string(http_resp.status_code) + ")"; |
| 152 | + return std::nullopt; |
| 153 | + } |
| 154 | + |
| 155 | + TokenResponse token_resp; |
| 156 | + token_resp.Parse(http_resp.result); |
| 157 | + if (!token_resp.IsValid()) { |
| 158 | + error = token_resp.GetValidationError(); |
| 159 | + if (error.empty()) { |
| 160 | + error = "While reading token response, found an invalid token response: " + http_resp.result; |
| 161 | + } |
| 162 | + return std::nullopt; |
| 163 | + } |
| 164 | + |
| 165 | + CachedToken result; |
| 166 | + result.token = token_resp.token_.value(); |
| 167 | + result.token_type = token_resp.token_type_.value(); |
| 168 | + result.expires_at = token_resp.expires_at_.value(); |
| 169 | + return result; |
| 170 | +} |
| 171 | + |
| 172 | +void HttpClientInterface::InvalidateCachedToken() { |
| 173 | + std::lock_guard<std::mutex> lock(token_mutex_); |
| 174 | + cached_token_ = std::nullopt; |
| 175 | +} |
0 commit comments