Coverage Report

Created: 2026-10-29 13:21

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/doris/be/src/util/s3_util.cpp
Line
Count
Source
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 "util/s3_util.h"
19
20
#include <aws/core/auth/AWSAuthSigner.h>
21
#include <aws/core/auth/AWSCredentials.h>
22
#include <aws/core/auth/AWSCredentialsProviderChain.h>
23
#include <aws/core/client/DefaultRetryStrategy.h>
24
#include <aws/core/utils/logging/LogLevel.h>
25
#include <aws/core/utils/logging/LogSystemInterface.h>
26
#include <aws/core/utils/memory/stl/AWSStringStream.h>
27
#include <aws/s3/S3Client.h>
28
29
#include "util/string_util.h"
30
31
#ifdef USE_AZURE
32
#include <azure/core/diagnostics/logger.hpp>
33
#include <azure/core/http/curl_transport.hpp>
34
#include <azure/storage/blobs/blob_container_client.hpp>
35
#endif
36
#include <cstdlib>
37
#include <filesystem>
38
#include <fstream>
39
#include <functional>
40
#include <memory>
41
#include <ostream>
42
#include <utility>
43
44
#include "common/config.h"
45
#include "common/logging.h"
46
#include "common/status.h"
47
#include "cpp/obj-client/auth/aws_credential_factory.h"
48
#ifdef USE_AZURE
49
#include "cpp/obj-client/auth/azure_auth_factory.h"
50
#include "cpp/obj-client/azure_obj_storage_client.h"
51
#endif
52
#include "cloud/config.h"
53
#include "cpp/aws_logger.h"
54
#include "cpp/obj-client/auth/gcp/gcp_token_provider.h"
55
#include "cpp/obj-client/auth/obj_credential.h"
56
#include "cpp/obj-client/auth/obj_s3_client_factory.h"
57
#include "cpp/obj-client/rate_limited_obj_storage_client.h"
58
#include "cpp/obj-client/s3_obj_storage_client.h"
59
#include "cpp/obj_retry_strategy.h"
60
#include "cpp/sync_point.h"
61
#include "cpp/util.h"
62
#include "exec/scan/scanner_scheduler.h"
63
#include "io/fs/gcs_signed_url_provider.h"
64
#include "runtime/exec_env.h"
65
#include "util/s3_rate_limiter_manager.h"
66
#include "util/s3_uri.h"
67
68
namespace doris {
69
namespace {
70
71
// Adapter between the IO storage-domain enum and the credential layer. Keep it
72
// local: neither layer should own or depend on the other's enum definition.
73
58
ObjCredentialProvider to_obj_credential_provider(io::ObjStorageProvider provider) {
74
58
    switch (provider) {
75
39
    case io::ObjStorageProvider::AWS:
76
39
        return ObjCredentialProvider::Aws;
77
0
    case io::ObjStorageProvider::AZURE:
78
0
        return ObjCredentialProvider::Azure;
79
0
    case io::ObjStorageProvider::BOS:
80
0
        return ObjCredentialProvider::Bos;
81
0
    case io::ObjStorageProvider::COS:
82
0
        return ObjCredentialProvider::Cos;
83
19
    case io::ObjStorageProvider::GCP:
84
19
        return ObjCredentialProvider::Gcp;
85
0
    case io::ObjStorageProvider::OBS:
86
0
        return ObjCredentialProvider::Obs;
87
0
    case io::ObjStorageProvider::OSS:
88
0
        return ObjCredentialProvider::Oss;
89
0
    case io::ObjStorageProvider::TOS:
90
0
        return ObjCredentialProvider::Tos;
91
0
    case io::ObjStorageProvider::UNKNOWN:
92
0
        return ObjCredentialProvider::Unknown;
93
58
    }
94
0
    return ObjCredentialProvider::Unknown;
95
58
}
96
97
58
doris::Status is_s3_conf_valid(const S3ClientConf& conf) {
98
58
    if (conf.endpoint.empty()) {
99
0
        return Status::InvalidArgument<false>("Invalid s3 conf, empty endpoint");
100
0
    }
101
58
    if (conf.region.empty()) {
102
0
        return Status::InvalidArgument<false>("Invalid s3 conf, empty region");
103
0
    }
104
105
58
    ObjCredentialValidationContext credential_context {
106
58
            .provider = to_obj_credential_provider(conf.provider),
107
58
            .ak = conf.ak,
108
58
            .sk = conf.sk,
109
58
            .token = conf.token,
110
58
            .has_aws_role_arn = !conf.role_arn.empty(),
111
58
            .has_aws_external_id = !conf.external_id.empty(),
112
58
            .has_aws_credential_provider = conf.cred_provider_type != CredProviderType::Default,
113
58
    };
114
58
    if (auto error = validate_obj_credential_config(conf.credential, credential_context);
115
58
        error.has_value()) {
116
8
        return Status::InvalidArgument<false>(*error);
117
8
    }
118
119
50
    if (conf.role_arn.empty()) {
120
        // Allow anonymous access when both ak and sk are empty
121
44
        bool hasAk = !conf.ak.empty();
122
44
        bool hasSk = !conf.sk.empty();
123
124
        // Either both credentials are provided or both are empty (anonymous access)
125
44
        if (hasAk && conf.sk.empty()) {
126
1
            return Status::InvalidArgument<false>("Invalid s3 conf, empty sk");
127
1
        }
128
43
        if (hasSk && conf.ak.empty()) {
129
1
            return Status::InvalidArgument<false>("Invalid s3 conf, empty ak");
130
1
        }
131
43
    }
132
48
    return Status::OK();
133
50
}
134
135
ObjStorageResponse make_be_rate_limit_response(S3RateLimitType type,
136
3
                                               S3RateLimitRejectReason reason) {
137
3
    const auto* limit_type = reason == S3RateLimitRejectReason::QPS ? "QPS" : "bytes";
138
    // A local admission rejection is not an S3 HTTP 429. Keep the merged #65420 behavior so S3
139
    // readers do not retry it as provider throttling.
140
3
    return ObjStorageResponse::rate_limit(
141
3
            ErrorCode::EXCEEDED_LIMIT, 0,
142
3
            fmt::format("s3 {} request exceeds {} limit, rejected by BE rate limiter",
143
3
                        to_string(type), limit_type));
144
3
}
145
146
class BeObjStorageRateLimitPolicy final : public ObjStorageRateLimitPolicy {
147
public:
148
36
    ObjStorageAdmission acquire(S3RateLimitType type, size_t estimated_bytes) const override {
149
36
        auto guard = std::make_shared<S3RateLimitGuard>(type, estimated_bytes);
150
36
        if (!guard->ok()) {
151
3
            return ObjStorageAdmission {
152
3
                    .resp = make_be_rate_limit_response(type, guard->reject_reason()),
153
3
            };
154
3
        }
155
33
        return ObjStorageAdmission {
156
33
                .settle = [guard = std::move(guard)](
157
33
                                  size_t actual_bytes) { guard->settle(actual_bytes); },
158
33
        };
159
36
    }
160
};
161
162
// Return true is convert `str` to int successfully
163
0
bool to_int(std::string_view str, int& res) {
164
0
    auto [_, ec] = std::from_chars(str.data(), str.data() + str.size(), res);
165
0
    return ec == std::errc {};
166
0
}
167
168
#ifdef USE_AZURE
169
0
std::string env_or_empty(const char* env_name) {
170
0
    if (const char* value = std::getenv(env_name); value != nullptr) {
171
0
        return value;
172
0
    }
173
0
    return "";
174
0
}
175
176
0
std::string build_azure_tls_debug_context(const std::string& selected_ca_file) {
177
0
    bool selected_ca_exists = false;
178
0
    bool selected_ca_readable = false;
179
0
    if (!selected_ca_file.empty()) {
180
0
        std::error_code ec;
181
0
        selected_ca_exists = std::filesystem::exists(selected_ca_file, ec) && !ec;
182
0
        std::ifstream input(selected_ca_file);
183
0
        selected_ca_readable = input.good();
184
0
    }
185
186
0
    return fmt::format(
187
0
            "tls_debug(ca_cert_file_paths='{}', selected_ca_file='{}', selected_ca_exists={}, "
188
0
            "selected_ca_readable={}, SSL_CERT_FILE='{}', CURL_CA_BUNDLE='{}', SSL_CERT_DIR='{}')",
189
0
            config::ca_cert_file_paths, selected_ca_file, selected_ca_exists, selected_ca_readable,
190
0
            env_or_empty("SSL_CERT_FILE"), env_or_empty("CURL_CA_BUNDLE"),
191
0
            env_or_empty("SSL_CERT_DIR"));
192
0
}
193
#endif
194
195
constexpr char USE_PATH_STYLE[] = "use_path_style";
196
197
constexpr char AZURE_PROVIDER_STRING[] = "AZURE";
198
constexpr char GCP_PROVIDER_STRING[] = "GCP";
199
constexpr char S3_PROVIDER[] = "provider";
200
constexpr char S3_AK[] = "AWS_ACCESS_KEY";
201
constexpr char S3_SK[] = "AWS_SECRET_KEY";
202
constexpr char S3_ENDPOINT[] = "AWS_ENDPOINT";
203
constexpr char S3_REGION[] = "AWS_REGION";
204
constexpr char S3_TOKEN[] = "AWS_TOKEN";
205
constexpr char S3_MAX_CONN_SIZE[] = "AWS_MAX_CONNECTIONS";
206
constexpr char S3_REQUEST_TIMEOUT_MS[] = "AWS_REQUEST_TIMEOUT_MS";
207
constexpr char S3_CONN_TIMEOUT_MS[] = "AWS_CONNECTION_TIMEOUT_MS";
208
constexpr char S3_NEED_OVERRIDE_ENDPOINT[] = "AWS_NEED_OVERRIDE_ENDPOINT";
209
210
constexpr char S3_ROLE_ARN[] = "AWS_ROLE_ARN";
211
constexpr char S3_EXTERNAL_ID[] = "AWS_EXTERNAL_ID";
212
constexpr char S3_CREDENTIALS_PROVIDER_TYPE[] = "AWS_CREDENTIALS_PROVIDER_TYPE";
213
} // namespace
214
215
1
S3ClientFactory::S3ClientFactory() {
216
1
    _aws_options = Aws::SDKOptions {};
217
1
    auto logLevel = static_cast<Aws::Utils::Logging::LogLevel>(config::aws_log_level);
218
1
    _aws_options.loggingOptions.logLevel = logLevel;
219
1
    _aws_options.loggingOptions.logger_create_fn = [logLevel] {
220
1
        return std::make_shared<DorisAWSLogger>(logLevel);
221
1
    };
222
1
    Aws::InitAPI(_aws_options);
223
1
    _get_ca_cert_file_path();
224
225
1
#ifdef USE_AZURE
226
1
    auto azureLogLevel =
227
1
            static_cast<Azure::Core::Diagnostics::Logger::Level>(config::azure_log_level);
228
1
    Azure::Core::Diagnostics::Logger::SetLevel(azureLogLevel);
229
1
    Azure::Core::Diagnostics::Logger::SetListener(
230
1
            [&](Azure::Core::Diagnostics::Logger::Level level, const std::string& message) {
231
0
                switch (level) {
232
0
                case Azure::Core::Diagnostics::Logger::Level::Verbose:
233
0
                    LOG(INFO) << message;
234
0
                    break;
235
0
                case Azure::Core::Diagnostics::Logger::Level::Informational:
236
0
                    LOG(INFO) << message;
237
0
                    break;
238
0
                case Azure::Core::Diagnostics::Logger::Level::Warning:
239
0
                    LOG(WARNING) << message;
240
0
                    break;
241
0
                case Azure::Core::Diagnostics::Logger::Level::Error:
242
0
                    LOG(ERROR) << message;
243
0
                    break;
244
0
                default:
245
0
                    LOG(WARNING) << "Unknown level: " << static_cast<int>(level)
246
0
                                 << ", message: " << message;
247
0
                    break;
248
0
                }
249
0
            });
250
1
#endif
251
1
}
252
253
1
S3ClientFactory::~S3ClientFactory() {
254
1
    Aws::ShutdownAPI(_aws_options);
255
1
}
256
257
80
S3ClientFactory& S3ClientFactory::instance() {
258
80
    static S3ClientFactory ret;
259
80
    return ret;
260
80
}
261
262
27
Result<std::shared_ptr<io::ObjStorageClient>> S3ClientFactory::create(const S3ClientConf& s3_conf) {
263
27
    RETURN_IF_ERROR_RESULT(is_s3_conf_valid(s3_conf));
264
265
27
#ifdef BE_TEST
266
27
    {
267
27
        std::lock_guard l(_lock);
268
27
        if (_test_client_creator) {
269
9
            return _test_client_creator(s3_conf);
270
9
        }
271
27
    }
272
18
#endif
273
274
18
    {
275
18
        std::lock_guard l(_lock);
276
18
        auto it = _cache.find(s3_conf);
277
18
        if (it != _cache.end()) {
278
9
            return it->second;
279
9
        }
280
18
    }
281
282
9
    auto client_result = (s3_conf.provider == io::ObjStorageProvider::AZURE)
283
9
                                 ? _create_azure_client(s3_conf)
284
9
                                 : _create_s3_client(s3_conf);
285
9
    if (!client_result.has_value()) {
286
0
        return ResultError(std::move(client_result).error());
287
0
    }
288
9
    auto obj_client = std::move(client_result).value();
289
9
    if (!config::is_cloud_mode() || s3_conf.is_internal_bucket) {
290
8
        obj_client = std::make_shared<io::RateLimitedObjStorageClient>(
291
8
                std::move(obj_client), std::make_shared<BeObjStorageRateLimitPolicy>());
292
8
    }
293
294
9
    {
295
9
        std::lock_guard l(_lock);
296
9
        auto [it, _] = _cache.emplace(s3_conf, std::move(obj_client));
297
9
        return it->second;
298
9
    }
299
9
}
300
301
#ifdef BE_TEST
302
void S3ClientFactory::set_client_creator_for_test(
303
5
        std::function<std::shared_ptr<io::ObjStorageClient>(const S3ClientConf&)> creator) {
304
5
    std::lock_guard l(_lock);
305
5
    _test_client_creator = std::move(creator);
306
5
}
307
308
34
void S3ClientFactory::clear_client_creator_for_test() {
309
34
    std::lock_guard l(_lock);
310
34
    _test_client_creator = nullptr;
311
34
}
312
#endif
313
314
Result<std::shared_ptr<io::ObjStorageClient>> S3ClientFactory::_create_azure_client(
315
0
        const S3ClientConf& s3_conf) {
316
0
#ifdef USE_AZURE
317
0
    const std::string container_name = s3_conf.bucket;
318
0
    std::string uri = fmt::format("{}/{}", s3_conf.endpoint, container_name);
319
0
    if (s3_conf.endpoint.find("://") == std::string::npos) {
320
0
        uri = "https://" + uri;
321
0
    }
322
323
0
    Azure::Storage::Blobs::BlobClientOptions options;
324
0
    options.Retry.StatusCodes.insert(Azure::Core::Http::HttpStatusCode::TooManyRequests);
325
0
    options.Retry.MaxRetries = config::max_s3_client_retry;
326
0
    options.PerRetryPolicies.emplace_back(std::make_unique<AzureRetryRecordPolicy>());
327
0
    auto ca_cert_file_path = _get_ca_cert_file_path();
328
0
    if (!ca_cert_file_path.empty()) {
329
0
        Azure::Core::Http::CurlTransportOptions curl_options;
330
0
        curl_options.CAInfo = ca_cert_file_path;
331
0
        options.Transport.Transport =
332
0
                std::make_shared<Azure::Core::Http::CurlTransport>(std::move(curl_options));
333
0
    }
334
335
0
    std::string normalized_uri = normalize_http_uri(uri);
336
0
    VLOG_DEBUG << "uri:" << uri << ", normalized_uri:" << normalized_uri;
337
0
    std::string tls_debug_context = build_azure_tls_debug_context(ca_cert_file_path);
338
339
0
    auto built = AzureAuthFactory::create(uri,
340
0
                                          {
341
0
                                                  .type = AzureCredentialType::SHARED_KEY,
342
0
                                                  .account_name = s3_conf.ak,
343
0
                                                  .account_key = s3_conf.sk,
344
0
                                          },
345
0
                                          std::move(options));
346
0
    if (!built) {
347
0
        return ResultError(
348
0
                Status::InvalidArgument("failed to create Azure client: {}", built.error));
349
0
    }
350
0
    LOG_INFO("create one azure client with {}", s3_conf.to_string());
351
0
    return std::make_shared<io::AzureObjStorageClient>(
352
0
            std::move(built.container_client),
353
0
            ObjStorageEndpointInfo {
354
0
                    .endpoint = s3_conf.endpoint,
355
0
                    .ak = s3_conf.ak,
356
0
                    .sk = s3_conf.sk,
357
0
                    .tls_debug_context = std::move(tls_debug_context),
358
0
            },
359
0
            std::move(built.shared_key_credential));
360
#else
361
    return ResultError(Status::NotSupported(
362
            "BE is not compiled with azure support, export BUILD_AZURE=ON before building"));
363
#endif
364
0
}
365
366
45
std::string S3ClientFactory::_get_ca_cert_file_path() {
367
45
    std::lock_guard lock(_ca_cert_lock);
368
45
    if (_ca_cert_file_path.empty()) {
369
3
        _ca_cert_file_path = get_valid_ca_cert_path(doris::split(config::ca_cert_file_paths, ";"));
370
3
    }
371
45
    return _ca_cert_file_path;
372
45
}
373
374
40
AwsCredentialResult S3ClientFactory::create_aws_credentials_provider(const S3ClientConf& s3_conf) {
375
40
    auto sts_config = S3ClientFactory::getClientConfiguration();
376
40
    auto ca_cert_file_path = _get_ca_cert_file_path();
377
40
    if (!ca_cert_file_path.empty()) {
378
39
        sts_config.caFile = ca_cert_file_path;
379
39
    }
380
40
    return AwsCredentialFactory::create({
381
40
            .version = config::aws_credentials_provider_version == "v2"
382
40
                               ? AwsCredentialProviderVersion::V2
383
40
                               : AwsCredentialProviderVersion::V1,
384
40
            .access_key = s3_conf.ak,
385
40
            .secret_key = s3_conf.sk,
386
40
            .session_token = s3_conf.token,
387
40
            .provider_type = s3_conf.cred_provider_type,
388
40
            .role_arn = s3_conf.role_arn,
389
40
            .external_id = s3_conf.external_id,
390
40
            .empty_credentials = EmptyCredentialsBehavior::ANONYMOUS,
391
40
            .sts_client_config = std::move(sts_config),
392
40
    });
393
40
}
394
395
Result<std::shared_ptr<io::ObjStorageClient>> S3ClientFactory::_create_s3_client(
396
9
        const S3ClientConf& s3_conf) {
397
9
    TEST_SYNC_POINT_RETURN_WITH_VALUE(
398
4
            "s3_client_factory::create",
399
4
            std::make_shared<io::S3ObjStorageClient>(std::make_shared<Aws::S3::S3Client>(),
400
4
                                                     ObjStorageEndpointInfo {}));
401
4
    Aws::Client::ClientConfiguration aws_config = S3ClientFactory::getClientConfiguration();
402
4
    if (s3_conf.need_override_endpoint) {
403
4
        aws_config.endpointOverride = s3_conf.endpoint;
404
4
    }
405
4
    aws_config.region = s3_conf.region;
406
407
4
    auto ca_cert_file_path = _get_ca_cert_file_path();
408
4
    if (!ca_cert_file_path.empty()) {
409
4
        aws_config.caFile = ca_cert_file_path;
410
4
    }
411
412
4
    if (s3_conf.max_connections > 0) {
413
0
        aws_config.maxConnections = s3_conf.max_connections;
414
4
    } else {
415
4
        aws_config.maxConnections = 102400;
416
4
    }
417
418
4
    aws_config.requestTimeoutMs = 30000;
419
4
    if (s3_conf.request_timeout_ms > 0) {
420
0
        aws_config.requestTimeoutMs = s3_conf.request_timeout_ms;
421
0
    }
422
423
4
    if (s3_conf.connect_timeout_ms > 0) {
424
0
        aws_config.connectTimeoutMs = s3_conf.connect_timeout_ms;
425
0
    }
426
427
4
    set_s3_client_default_http_scheme(aws_config, config::s3_client_http_scheme);
428
429
4
    aws_config.retryStrategy = std::make_shared<S3CustomRetryStrategy>(
430
4
            config::max_s3_client_retry /*scaleFactor = 25*/, /*retry_slow_down=*/true);
431
432
4
    auto credentials = create_aws_credentials_provider(s3_conf);
433
4
    if (!credentials) {
434
0
        return ResultError(Status::InvalidArgument("failed to create AWS credential provider: {}",
435
0
                                                   credentials.error));
436
0
    }
437
4
    auto new_client = make_s3_client(
438
4
            s3_conf.credential,
439
4
            S3ClientBuildContext {
440
4
                    .fallback_provider = std::move(credentials.provider),
441
4
                    .config = std::move(aws_config),
442
4
                    .payload_signing_policy =
443
4
                            Aws::Client::AWSAuthV4Signer::PayloadSigningPolicy::Never,
444
4
                    .use_virtual_addressing = s3_conf.use_virtual_addressing,
445
4
                    .ca_cert_path = ca_cert_file_path,
446
4
            });
447
4
    S3ObjStorageClient::PresignedUrlGenerator presigned_url_generator;
448
4
    if (const auto* gcp_credential = std::get_if<GcpCredentialConfig>(&s3_conf.credential)) {
449
0
        auto signing_caller_credential = *gcp_credential;
450
0
        signing_caller_credential.impersonation_service_account.clear();
451
0
        auto token_provider = std::make_shared<GcpTokenProvider>(
452
0
                signing_caller_credential, ca_cert_file_path, GcpTokenScope::CloudPlatform);
453
0
        presigned_url_generator = [credential = *gcp_credential,
454
0
                                   token_provider = std::move(token_provider),
455
0
                                   endpoint = s3_conf.endpoint,
456
0
                                   timeout_ms = s3_conf.request_timeout_ms](
457
0
                                          const ObjStoragePath& path, int64_t expiration_secs) {
458
0
            std::string signed_url;
459
0
            auto status = io::generate_gcs_v4_signed_url({.endpoint = endpoint,
460
0
                                                          .bucket = path.bucket,
461
0
                                                          .key = path.key,
462
0
                                                          .expiration_secs = expiration_secs,
463
0
                                                          .request_timeout_ms = timeout_ms},
464
0
                                                         credential, token_provider, &signed_url);
465
0
            if (!status.ok()) {
466
0
                LOG(WARNING) << "failed to generate GCS V4 signed URL: " << status;
467
0
                return std::string {};
468
0
            }
469
0
            return signed_url;
470
0
        };
471
0
    }
472
4
    auto provider_client = std::make_shared<io::S3ObjStorageClient>(
473
4
            std::move(new_client),
474
4
            ObjStorageEndpointInfo {
475
4
                    .endpoint = s3_conf.endpoint, .ak = s3_conf.ak, .sk = s3_conf.sk},
476
4
            std::move(presigned_url_generator));
477
4
    LOG_INFO("create one s3 client with {}", s3_conf.to_string());
478
4
    return provider_client;
479
4
}
480
481
Status S3ClientFactory::convert_properties_to_s3_conf(
482
36
        const std::map<std::string, std::string>& prop, const S3URI& s3_uri, S3Conf* s3_conf) {
483
36
    StringCaseMap<std::string> properties(prop.begin(), prop.end());
484
36
    if (auto it = properties.find(S3_AK); it != properties.end()) {
485
3
        s3_conf->client_conf.ak = it->second;
486
3
    }
487
36
    if (auto it = properties.find(S3_SK); it != properties.end()) {
488
3
        s3_conf->client_conf.sk = it->second;
489
3
    }
490
36
    if (auto it = properties.find(S3_TOKEN); it != properties.end()) {
491
1
        s3_conf->client_conf.token = it->second;
492
1
    }
493
36
    if (auto it = properties.find(S3_ENDPOINT); it != properties.end()) {
494
36
        s3_conf->client_conf.endpoint = it->second;
495
36
    }
496
36
    if (auto it = properties.find(S3_NEED_OVERRIDE_ENDPOINT); it != properties.end()) {
497
0
        s3_conf->client_conf.need_override_endpoint = (it->second == "true");
498
0
    }
499
36
    if (auto it = properties.find(S3_REGION); it != properties.end()) {
500
36
        s3_conf->client_conf.region = it->second;
501
36
    }
502
36
    if (auto it = properties.find(S3_MAX_CONN_SIZE); it != properties.end()) {
503
0
        if (!to_int(it->second, s3_conf->client_conf.max_connections)) {
504
0
            return Status::InvalidArgument("invalid {} value \"{}\"", S3_MAX_CONN_SIZE, it->second);
505
0
        }
506
0
    }
507
36
    if (auto it = properties.find(S3_REQUEST_TIMEOUT_MS); it != properties.end()) {
508
0
        if (!to_int(it->second, s3_conf->client_conf.request_timeout_ms)) {
509
0
            return Status::InvalidArgument("invalid {} value \"{}\"", S3_REQUEST_TIMEOUT_MS,
510
0
                                           it->second);
511
0
        }
512
0
    }
513
36
    if (auto it = properties.find(S3_CONN_TIMEOUT_MS); it != properties.end()) {
514
0
        if (!to_int(it->second, s3_conf->client_conf.connect_timeout_ms)) {
515
0
            return Status::InvalidArgument("invalid {} value \"{}\"", S3_CONN_TIMEOUT_MS,
516
0
                                           it->second);
517
0
        }
518
0
    }
519
36
    if (auto it = properties.find(S3_PROVIDER); it != properties.end()) {
520
        // S3 Provider properties should be case insensitive.
521
21
        if (0 == strcasecmp(it->second.c_str(), AZURE_PROVIDER_STRING)) {
522
0
            s3_conf->client_conf.provider = io::ObjStorageProvider::AZURE;
523
21
        } else if (0 == strcasecmp(it->second.c_str(), GCP_PROVIDER_STRING)) {
524
19
            s3_conf->client_conf.provider = io::ObjStorageProvider::GCP;
525
19
        }
526
21
    }
527
528
36
    if (s3_uri.get_bucket().empty()) {
529
0
        return Status::InvalidArgument("Invalid S3 URI {}, bucket is not specified",
530
0
                                       s3_uri.to_string());
531
0
    }
532
36
    s3_conf->bucket = s3_uri.get_bucket();
533
    // For azure's compatibility
534
36
    s3_conf->client_conf.bucket = s3_uri.get_bucket();
535
36
    s3_conf->prefix = "";
536
537
    // See https://sdk.amazonaws.com/cpp/api/LATEST/class_aws_1_1_s3_1_1_s3_client.html
538
36
    s3_conf->client_conf.use_virtual_addressing = true;
539
36
    if (auto it = properties.find(USE_PATH_STYLE); it != properties.end()) {
540
0
        s3_conf->client_conf.use_virtual_addressing = it->second != "true";
541
0
    }
542
543
36
    if (auto it = properties.find(S3_ROLE_ARN); it != properties.end()) {
544
        // Keep provider type as Default unless explicitly configured by
545
        // AWS_CREDENTIALS_PROVIDER_TYPE, consistent with FE behavior.
546
6
        s3_conf->client_conf.role_arn = it->second;
547
6
    }
548
549
36
    if (auto it = properties.find(S3_EXTERNAL_ID); it != properties.end()) {
550
1
        s3_conf->client_conf.external_id = it->second;
551
1
    }
552
553
36
    if (auto it = properties.find(S3_CREDENTIALS_PROVIDER_TYPE); it != properties.end()) {
554
9
        s3_conf->client_conf.cred_provider_type = cred_provider_type_from_string(it->second);
555
9
    }
556
557
36
    if (auto error = parse_obj_credential_properties(properties, &s3_conf->client_conf.credential);
558
36
        error.has_value()) {
559
5
        return Status::InvalidArgument(*error);
560
5
    }
561
562
31
    if (auto st = is_s3_conf_valid(s3_conf->client_conf); !st.ok()) {
563
10
        return st;
564
10
    }
565
21
    return Status::OK();
566
31
}
567
568
0
static CredProviderType cred_provider_type_from_thrift(TCredProviderType::type cred_provider_type) {
569
0
    switch (cred_provider_type) {
570
0
    case TCredProviderType::DEFAULT:
571
0
        return CredProviderType::Default;
572
0
    case TCredProviderType::SIMPLE:
573
0
        return CredProviderType::Simple;
574
0
    case TCredProviderType::INSTANCE_PROFILE:
575
0
        return CredProviderType::InstanceProfile;
576
0
    case TCredProviderType::ENV:
577
0
        return CredProviderType::Env;
578
0
    case TCredProviderType::SYSTEM_PROPERTIES:
579
0
        return CredProviderType::SystemProperties;
580
0
    case TCredProviderType::WEB_IDENTITY:
581
0
        return CredProviderType::WebIdentity;
582
0
    case TCredProviderType::CONTAINER:
583
0
        return CredProviderType::Container;
584
0
    case TCredProviderType::ANONYMOUS:
585
0
        return CredProviderType::Anonymous;
586
0
    default:
587
0
        __builtin_unreachable();
588
0
        LOG(WARNING) << "Invalid TCredProviderType value: " << cred_provider_type
589
0
                     << ", use default instead.";
590
0
        return CredProviderType::Default;
591
0
    }
592
0
}
593
594
0
S3Conf S3Conf::get_s3_conf(const cloud::ObjectStoreInfoPB& info) {
595
0
    S3Conf ret {
596
0
            .bucket = info.bucket(),
597
0
            .prefix = info.prefix(),
598
0
            .client_conf {
599
0
                    .endpoint = info.endpoint(),
600
0
                    .region = info.region(),
601
0
                    .ak = info.ak(),
602
0
                    .sk = info.sk(),
603
0
                    .token = {},
604
0
                    .bucket = info.bucket(),
605
0
                    .provider = io::ObjStorageProvider::AWS,
606
0
                    .use_virtual_addressing =
607
0
                            info.has_use_path_style() ? !info.use_path_style() : true,
608
609
0
                    .role_arn = info.role_arn(),
610
0
                    .external_id = info.external_id(),
611
                    // ObjectStoreInfoPB always describes a storage vault, i.e. a Doris
612
                    // internal bucket in cloud mode.
613
0
                    .is_internal_bucket = true,
614
0
            },
615
0
            .sse_enabled = info.sse_enabled(),
616
0
    };
617
618
0
    if (info.has_cred_provider_type()) {
619
0
        ret.client_conf.cred_provider_type = cred_provider_type_from_pb(info.cred_provider_type());
620
0
    }
621
0
    convert_obj_credential(info, &ret.client_conf.credential);
622
623
0
    io::ObjStorageProvider type = io::ObjStorageProvider::AWS;
624
0
    switch (info.provider()) {
625
0
    case cloud::ObjectStoreInfoPB_Provider_OSS:
626
0
        type = io::ObjStorageProvider::OSS;
627
0
        break;
628
0
    case cloud::ObjectStoreInfoPB_Provider_S3:
629
0
        type = io::ObjStorageProvider::AWS;
630
0
        break;
631
0
    case cloud::ObjectStoreInfoPB_Provider_COS:
632
0
        type = io::ObjStorageProvider::COS;
633
0
        break;
634
0
    case cloud::ObjectStoreInfoPB_Provider_OBS:
635
0
        type = io::ObjStorageProvider::OBS;
636
0
        break;
637
0
    case cloud::ObjectStoreInfoPB_Provider_BOS:
638
0
        type = io::ObjStorageProvider::BOS;
639
0
        break;
640
0
    case cloud::ObjectStoreInfoPB_Provider_GCP:
641
0
        type = io::ObjStorageProvider::GCP;
642
0
        break;
643
0
    case cloud::ObjectStoreInfoPB_Provider_AZURE:
644
0
        type = io::ObjStorageProvider::AZURE;
645
0
        break;
646
0
    case cloud::ObjectStoreInfoPB_Provider_TOS:
647
0
        type = io::ObjStorageProvider::TOS;
648
0
        break;
649
0
    default:
650
0
        __builtin_unreachable();
651
0
        LOG_FATAL("unknown provider type {}, info {}", info.provider(), ret.to_string());
652
0
    }
653
0
    ret.client_conf.provider = type;
654
0
    return ret;
655
0
}
656
657
0
S3Conf S3Conf::get_s3_conf(const TS3StorageParam& param) {
658
0
    S3Conf ret {
659
0
            .bucket = param.bucket,
660
0
            .prefix = param.root_path,
661
0
            .client_conf = {
662
0
                    .endpoint = param.endpoint,
663
0
                    .region = param.region,
664
0
                    .ak = param.ak,
665
0
                    .sk = param.sk,
666
0
                    .token = param.token,
667
0
                    .bucket = param.bucket,
668
0
                    .provider = io::ObjStorageProvider::AWS,
669
0
                    .max_connections = param.max_conn,
670
0
                    .request_timeout_ms = param.request_timeout_ms,
671
0
                    .connect_timeout_ms = param.conn_timeout_ms,
672
                    // When using cold heat separation in minio, user might use ip address directly,
673
                    // which needs enable use_virtual_addressing to true
674
0
                    .use_virtual_addressing = !param.use_path_style,
675
0
                    .role_arn = param.role_arn,
676
0
                    .external_id = param.external_id,
677
0
            }};
678
679
0
    if (param.__isset.cred_provider_type) {
680
0
        ret.client_conf.cred_provider_type =
681
0
                cred_provider_type_from_thrift(param.cred_provider_type);
682
0
    }
683
0
    if (param.__isset.credential) {
684
0
        convert_obj_credential(param.credential, &ret.client_conf.credential);
685
0
    }
686
687
0
    io::ObjStorageProvider type = io::ObjStorageProvider::AWS;
688
0
    switch (param.provider) {
689
0
    case TObjStorageType::UNKNOWN:
690
0
        LOG_INFO("Receive one legal storage resource, set provider type to aws, param detail {}",
691
0
                 ret.to_string());
692
0
        type = io::ObjStorageProvider::AWS;
693
0
        break;
694
0
    case TObjStorageType::AWS:
695
0
        type = io::ObjStorageProvider::AWS;
696
0
        break;
697
0
    case TObjStorageType::AZURE:
698
0
        type = io::ObjStorageProvider::AZURE;
699
0
        break;
700
0
    case TObjStorageType::BOS:
701
0
        type = io::ObjStorageProvider::BOS;
702
0
        break;
703
0
    case TObjStorageType::COS:
704
0
        type = io::ObjStorageProvider::COS;
705
0
        break;
706
0
    case TObjStorageType::OBS:
707
0
        type = io::ObjStorageProvider::OBS;
708
0
        break;
709
0
    case TObjStorageType::OSS:
710
0
        type = io::ObjStorageProvider::OSS;
711
0
        break;
712
0
    case TObjStorageType::GCP:
713
0
        type = io::ObjStorageProvider::GCP;
714
0
        break;
715
0
    case TObjStorageType::TOS:
716
0
        type = io::ObjStorageProvider::TOS;
717
0
        break;
718
0
    default:
719
0
        LOG_FATAL("unknown provider type {}, info {}", param.provider, ret.to_string());
720
0
        __builtin_unreachable();
721
0
    }
722
0
    ret.client_conf.provider = type;
723
0
    return ret;
724
0
}
725
726
19
std::string hide_access_key(const std::string& ak) {
727
19
    std::string key = ak;
728
19
    size_t key_len = key.length();
729
19
    size_t reserved_count;
730
19
    if (key_len > 7) {
731
4
        reserved_count = 6;
732
15
    } else if (key_len > 2) {
733
6
        reserved_count = key_len - 2;
734
9
    } else {
735
9
        reserved_count = 0;
736
9
    }
737
738
19
    size_t x_count = key_len - reserved_count;
739
19
    size_t left_x_count = (x_count + 1) / 2;
740
741
19
    if (left_x_count > 0) {
742
13
        key.replace(0, left_x_count, left_x_count, 'x');
743
13
    }
744
745
19
    if (x_count - left_x_count > 0) {
746
12
        key.replace(key_len - (x_count - left_x_count), x_count - left_x_count,
747
12
                    x_count - left_x_count, 'x');
748
12
    }
749
19
    return key;
750
19
}
751
752
} // end namespace doris