|
| 1 | +#include "nix/store/aws-creds.hh" |
| 2 | + |
| 3 | +#if NIX_WITH_S3_SUPPORT |
| 4 | + |
| 5 | +# include <aws/crt/Types.h> |
| 6 | +# include "nix/store/s3-url.hh" |
| 7 | +# include "nix/util/finally.hh" |
| 8 | +# include "nix/util/logging.hh" |
| 9 | +# include "nix/util/sync.hh" |
| 10 | +# include "nix/util/url.hh" |
| 11 | +# include "nix/util/util.hh" |
| 12 | + |
| 13 | +# include <aws/crt/Api.h> |
| 14 | +# include <aws/crt/auth/Credentials.h> |
| 15 | +# include <aws/crt/io/Bootstrap.h> |
| 16 | + |
| 17 | +# include <boost/unordered/concurrent_flat_map.hpp> |
| 18 | + |
| 19 | +# include <chrono> |
| 20 | +# include <condition_variable> |
| 21 | +# include <mutex> |
| 22 | +# include <unistd.h> |
| 23 | + |
| 24 | +namespace nix { |
| 25 | + |
| 26 | +namespace { |
| 27 | + |
| 28 | +static void initAwsCrt() |
| 29 | +{ |
| 30 | + struct CrtWrapper |
| 31 | + { |
| 32 | + Aws::Crt::ApiHandle apiHandle; |
| 33 | + |
| 34 | + CrtWrapper() |
| 35 | + { |
| 36 | + apiHandle.InitializeLogging(Aws::Crt::LogLevel::Warn, static_cast<FILE *>(nullptr)); |
| 37 | + } |
| 38 | + |
| 39 | + ~CrtWrapper() |
| 40 | + { |
| 41 | + try { |
| 42 | + // CRITICAL: Clear credential provider cache BEFORE AWS CRT shuts down |
| 43 | + // This ensures all providers (which hold references to ClientBootstrap) |
| 44 | + // are destroyed while AWS CRT is still valid |
| 45 | + clearAwsCredentialsCache(); |
| 46 | + // Now it's safe for ApiHandle destructor to run |
| 47 | + } catch (...) { |
| 48 | + ignoreExceptionInDestructor(); |
| 49 | + } |
| 50 | + } |
| 51 | + }; |
| 52 | + |
| 53 | + static CrtWrapper crt; |
| 54 | +} |
| 55 | + |
| 56 | +static AwsCredentials getCredentialsFromProvider(std::shared_ptr<Aws::Crt::Auth::ICredentialsProvider> provider) |
| 57 | +{ |
| 58 | + if (!provider || !provider->IsValid()) { |
| 59 | + throw AwsAuthError("AWS credential provider is invalid"); |
| 60 | + } |
| 61 | + |
| 62 | + struct State |
| 63 | + { |
| 64 | + std::optional<AwsCredentials> result; |
| 65 | + int resolvedErrorCode = 0; |
| 66 | + bool resolved = false; |
| 67 | + }; |
| 68 | + |
| 69 | + Sync<State> state; |
| 70 | + std::condition_variable cv; |
| 71 | + |
| 72 | + provider->GetCredentials([&](std::shared_ptr<Aws::Crt::Auth::Credentials> credentials, int errorCode) { |
| 73 | + auto state_ = state.lock(); |
| 74 | + |
| 75 | + if (errorCode != 0 || !credentials) { |
| 76 | + state_->resolvedErrorCode = errorCode; |
| 77 | + } else { |
| 78 | + auto accessKeyId = Aws::Crt::ByteCursorToStringView(credentials->GetAccessKeyId()); |
| 79 | + auto secretAccessKey = Aws::Crt::ByteCursorToStringView(credentials->GetSecretAccessKey()); |
| 80 | + auto sessionToken = Aws::Crt::ByteCursorToStringView(credentials->GetSessionToken()); |
| 81 | + |
| 82 | + std::optional<std::string> sessionTokenStr; |
| 83 | + if (!sessionToken.empty()) { |
| 84 | + sessionTokenStr = std::string(sessionToken.data(), sessionToken.size()); |
| 85 | + } |
| 86 | + |
| 87 | + state_->result = AwsCredentials( |
| 88 | + std::string(accessKeyId.data(), accessKeyId.size()), |
| 89 | + std::string(secretAccessKey.data(), secretAccessKey.size()), |
| 90 | + sessionTokenStr); |
| 91 | + } |
| 92 | + |
| 93 | + state_->resolved = true; |
| 94 | + cv.notify_one(); |
| 95 | + }); |
| 96 | + |
| 97 | + { |
| 98 | + auto state_ = state.lock(); |
| 99 | + // AWS CRT GetCredentials is asynchronous and only guarantees the callback will be |
| 100 | + // invoked if the initial call returns success. There's no documented timeout mechanism, |
| 101 | + // so we add a timeout to prevent indefinite hanging if the callback is never called. |
| 102 | + // Use an absolute deadline to handle spurious wakeups correctly. |
| 103 | + auto timeout = std::chrono::seconds(30); |
| 104 | + auto deadline = std::chrono::steady_clock::now() + timeout; |
| 105 | + |
| 106 | + while (!state_->resolved) { |
| 107 | + if (state_.wait_until(cv, deadline) == std::cv_status::timeout) { |
| 108 | + // Double-check the condition after timeout to avoid race |
| 109 | + if (!state_->resolved) { |
| 110 | + throw AwsAuthError( |
| 111 | + "Timeout waiting for AWS credentials (%d seconds)", |
| 112 | + std::chrono::duration_cast<std::chrono::seconds>(timeout).count()); |
| 113 | + } |
| 114 | + break; |
| 115 | + } |
| 116 | + } |
| 117 | + } |
| 118 | + |
| 119 | + auto state_ = state.lock(); |
| 120 | + if (!state_->result) { |
| 121 | + throw AwsAuthError("Failed to resolve AWS credentials: error code %d", state_->resolvedErrorCode); |
| 122 | + } |
| 123 | + |
| 124 | + return *state_->result; |
| 125 | +} |
| 126 | + |
| 127 | +// Global credential provider cache using boost's concurrent map |
| 128 | +// Key: profile name (empty string for default profile) |
| 129 | +using CredentialProviderCache = |
| 130 | + boost::concurrent_flat_map<std::string, std::shared_ptr<Aws::Crt::Auth::ICredentialsProvider>>; |
| 131 | + |
| 132 | +static CredentialProviderCache credentialProviderCache; |
| 133 | + |
| 134 | +} // anonymous namespace |
| 135 | + |
| 136 | +AwsCredentials getAwsCredentials(const std::string & profile) |
| 137 | +{ |
| 138 | + // Get or create credential provider with caching |
| 139 | + std::shared_ptr<Aws::Crt::Auth::ICredentialsProvider> provider; |
| 140 | + |
| 141 | + // Try to find existing provider |
| 142 | + credentialProviderCache.visit(profile, [&](const auto & pair) { provider = pair.second; }); |
| 143 | + |
| 144 | + if (!provider) { |
| 145 | + // Create new provider if not found |
| 146 | + debug( |
| 147 | + "[pid=%d] creating new AWS credential provider for profile '%s'", |
| 148 | + getpid(), |
| 149 | + profile.empty() ? "(default)" : profile.c_str()); |
| 150 | + |
| 151 | + try { |
| 152 | + initAwsCrt(); |
| 153 | + |
| 154 | + if (profile.empty()) { |
| 155 | + Aws::Crt::Auth::CredentialsProviderChainDefaultConfig config; |
| 156 | + config.Bootstrap = Aws::Crt::ApiHandle::GetOrCreateStaticDefaultClientBootstrap(); |
| 157 | + provider = Aws::Crt::Auth::CredentialsProvider::CreateCredentialsProviderChainDefault(config); |
| 158 | + } else { |
| 159 | + Aws::Crt::Auth::CredentialsProviderProfileConfig config; |
| 160 | + config.Bootstrap = Aws::Crt::ApiHandle::GetOrCreateStaticDefaultClientBootstrap(); |
| 161 | + config.ProfileNameOverride = Aws::Crt::ByteCursorFromCString(profile.c_str()); |
| 162 | + provider = Aws::Crt::Auth::CredentialsProvider::CreateCredentialsProviderProfile(config); |
| 163 | + } |
| 164 | + } catch (Error & e) { |
| 165 | + e.addTrace( |
| 166 | + {}, |
| 167 | + "while creating AWS credentials provider for %s", |
| 168 | + profile.empty() ? "default profile" : fmt("profile '%s'", profile)); |
| 169 | + throw; |
| 170 | + } |
| 171 | + |
| 172 | + if (!provider) { |
| 173 | + throw AwsAuthError( |
| 174 | + "Failed to create AWS credentials provider for %s", |
| 175 | + profile.empty() ? "default profile" : fmt("profile '%s'", profile)); |
| 176 | + } |
| 177 | + |
| 178 | + // Insert into cache (try_emplace is thread-safe and won't overwrite if another thread added it) |
| 179 | + credentialProviderCache.try_emplace(profile, provider); |
| 180 | + } |
| 181 | + |
| 182 | + return getCredentialsFromProvider(provider); |
| 183 | +} |
| 184 | + |
| 185 | +void invalidateAwsCredentials(const std::string & profile) |
| 186 | +{ |
| 187 | + credentialProviderCache.erase(profile); |
| 188 | +} |
| 189 | + |
| 190 | +void clearAwsCredentialsCache() |
| 191 | +{ |
| 192 | + credentialProviderCache.clear(); |
| 193 | +} |
| 194 | + |
| 195 | +std::optional<AwsCredentials> preResolveAwsCredentials(const std::string & url) |
| 196 | +{ |
| 197 | + try { |
| 198 | + auto parsedUrl = parseURL(url); |
| 199 | + if (parsedUrl.scheme != "s3") { |
| 200 | + return std::nullopt; |
| 201 | + } |
| 202 | + |
| 203 | + auto s3Url = ParsedS3URL::parse(parsedUrl); |
| 204 | + std::string profile = s3Url.profile.value_or(""); |
| 205 | + |
| 206 | + // Get credentials (automatically cached) |
| 207 | + return getAwsCredentials(profile); |
| 208 | + } catch (const AwsAuthError & e) { |
| 209 | + debug("Failed to pre-resolve AWS credentials: %s", e.what()); |
| 210 | + return std::nullopt; |
| 211 | + } catch (const std::exception & e) { |
| 212 | + debug("Failed to pre-resolve AWS credentials: %s", e.what()); |
| 213 | + return std::nullopt; |
| 214 | + } |
| 215 | +} |
| 216 | + |
| 217 | +} // namespace nix |
| 218 | + |
| 219 | +#endif |
0 commit comments