opendal_service_s3/config.rs
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
18use std::collections::HashMap;
19use std::fmt::Debug;
20
21use opendal_core::Configurator;
22use opendal_core::OperatorUri;
23use opendal_core::Result;
24use serde::Deserialize;
25use serde::Serialize;
26
27use crate::backend::S3Builder;
28
29/// Config for Aws S3 and compatible services (including minio, digitalocean space,
30/// Tencent Cloud Object Storage(COS) and so on) support.
31#[derive(Default, Serialize, Deserialize, Clone, PartialEq, Eq)]
32#[serde(default)]
33#[non_exhaustive]
34pub struct S3Config {
35 /// root of this backend.
36 ///
37 /// All operations will happen under this root.
38 ///
39 /// default to `/` if not set.
40 ///
41 /// <!-- @group General -->
42 /// <!-- @default / -->
43 pub root: Option<String>,
44 /// bucket name of this backend.
45 ///
46 /// required.
47 ///
48 /// <!-- @group General -->
49 /// <!-- @example my-bucket -->
50 #[serde(alias = "aws_bucket", alias = "aws_bucket_name", alias = "bucket_name")]
51 pub bucket: String,
52 /// Deprecated: S3 versioning capability is enabled by default.
53 ///
54 /// <!-- @group Deprecated -->
55 #[deprecated(
56 since = "0.57.0",
57 note = "S3 versioning capability is enabled by default and this option is no longer needed."
58 )]
59 pub enable_versioning: bool,
60 /// endpoint of this backend.
61 ///
62 /// Endpoint must be full uri, e.g.
63 ///
64 /// - AWS S3: `https://s3.amazonaws.com` or `https://s3.{region}.amazonaws.com`
65 /// - Cloudflare R2: `https://<ACCOUNT_ID>.r2.cloudflarestorage.com`
66 /// - Aliyun OSS: `https://{region}.aliyuncs.com`
67 /// - Tencent COS: `https://cos.{region}.myqcloud.com`
68 /// - Minio: `http://127.0.0.1:9000`
69 ///
70 /// If user inputs endpoint without scheme like "s3.amazonaws.com", we
71 /// will prepend "https://" before it.
72 ///
73 /// - If endpoint is set, we will take user's input first.
74 /// - If not, we will try to load it from environment.
75 /// - If still not set, default to `https://s3.amazonaws.com`.
76 ///
77 /// <!-- @group General -->
78 /// <!-- @default https://s3.amazonaws.com -->
79 #[serde(
80 alias = "aws_endpoint",
81 alias = "aws_endpoint_url",
82 alias = "endpoint_url"
83 )]
84 pub endpoint: Option<String>,
85 /// Region represent the signing region of this endpoint. This is required
86 /// if you are using the default AWS S3 endpoint.
87 ///
88 /// If using a custom endpoint,
89 /// - If region is set, we will take user's input first.
90 /// - If not, we will try to load it from environment.
91 ///
92 /// <!-- @group General -->
93 /// <!-- @example us-east-1 -->
94 #[serde(alias = "aws_region")]
95 pub region: Option<String>,
96
97 /// AWS profile.
98 ///
99 /// By default, reqsign which is the default credential provider, supplies profile in order:
100 /// - explicit option
101 /// - `AWS_PROFILE` environment variable, from which reqsign reads profile from:
102 /// - `~/.aws/credentials` (or the path specified by `AWS_SHARED_CREDENTIALS_FILE`)
103 /// - `~/.aws/config` (or the path specified by `AWS_CONFIG_FILE`)
104 /// <!-- @group Credentials -->
105 /// <!-- @example development -->
106 #[serde(alias = "aws_profile")]
107 pub profile: Option<String>,
108
109 /// access_key_id of this backend.
110 ///
111 /// - If access_key_id is set, we will take user's input first.
112 /// - If not, we will try to load it from environment.
113 ///
114 /// <!-- @group Credentials -->
115 #[serde(alias = "aws_access_key_id")]
116 pub access_key_id: Option<String>,
117 /// secret_access_key of this backend.
118 ///
119 /// - If secret_access_key is set, we will take user's input first.
120 /// - If not, we will try to load it from environment.
121 ///
122 /// <!-- @group Credentials -->
123 #[serde(alias = "aws_secret_access_key")]
124 pub secret_access_key: Option<String>,
125 /// session_token (aka, security token) of this backend.
126 ///
127 /// This token will expire after sometime, it's recommended to set session_token
128 /// by hand.
129 ///
130 /// <!-- @group Credentials -->
131 #[serde(alias = "aws_session_token", alias = "aws_token", alias = "token")]
132 pub session_token: Option<String>,
133 /// role_arn for this backend.
134 ///
135 /// If `role_arn` is set, we will use already known config as source
136 /// credential to assume role with `role_arn`.
137 ///
138 /// <!-- @group Assume role -->
139 pub role_arn: Option<String>,
140 /// external_id for this backend.
141 ///
142 /// <!-- @group Assume role -->
143 pub external_id: Option<String>,
144 /// role_session_name for this backend.
145 ///
146 /// <!-- @group Assume role -->
147 pub role_session_name: Option<String>,
148 /// assume_role_duration_seconds for this backend.
149 ///
150 /// <!-- @group Assume role -->
151 pub assume_role_duration_seconds: Option<u32>,
152 /// assume_role_session_tags for this backend.
153 ///
154 /// <!-- @group Assume role -->
155 pub assume_role_session_tags: Option<HashMap<String, String>>,
156 /// Disable config load so that opendal will not load config from
157 /// environment.
158 ///
159 /// For examples:
160 ///
161 /// - envs like `AWS_ACCESS_KEY_ID`
162 /// - files like `~/.aws/config`
163 ///
164 /// <!-- @group Credentials -->
165 pub disable_config_load: bool,
166 /// Disable load credential from ec2 metadata.
167 ///
168 /// This option is used to disable the default behavior of opendal
169 /// to load credential from ec2 metadata, a.k.a., IMDSv2
170 ///
171 /// <!-- @group Credentials -->
172 pub disable_ec2_metadata: bool,
173 /// Skip signature will skip loading credentials and signing requests.
174 ///
175 /// <!-- @group Credentials -->
176 pub skip_signature: bool,
177 /// Allow anonymous will allow opendal to send request without signing
178 /// when credential is not loaded.
179 ///
180 /// <!-- @group Deprecated -->
181 #[deprecated(
182 since = "0.57.0",
183 note = "Please use `skip_signature` instead of `allow_anonymous`"
184 )]
185 pub allow_anonymous: bool,
186 /// server_side_encryption for this backend.
187 ///
188 /// Available values: `AES256`, `aws:kms`.
189 ///
190 /// <!-- @group Encryption -->
191 #[serde(alias = "aws_server_side_encryption")]
192 pub server_side_encryption: Option<String>,
193 /// server_side_encryption_aws_kms_key_id for this backend
194 ///
195 /// - If `server_side_encryption` set to `aws:kms`, and `server_side_encryption_aws_kms_key_id`
196 /// is not set, S3 will use aws managed kms key to encrypt data.
197 /// - If `server_side_encryption` set to `aws:kms`, and `server_side_encryption_aws_kms_key_id`
198 /// is a valid kms key id, S3 will use the provided kms key to encrypt data.
199 /// - If the `server_side_encryption_aws_kms_key_id` is invalid or not found, an error will be
200 /// returned.
201 /// - If `server_side_encryption` is not `aws:kms`, setting `server_side_encryption_aws_kms_key_id`
202 /// is a noop.
203 ///
204 /// <!-- @group Encryption -->
205 #[serde(alias = "aws_sse_kms_key_id")]
206 pub server_side_encryption_aws_kms_key_id: Option<String>,
207 /// server_side_encryption_customer_algorithm for this backend.
208 ///
209 /// Available values: `AES256`.
210 ///
211 /// <!-- @group Encryption -->
212 pub server_side_encryption_customer_algorithm: Option<String>,
213 /// server_side_encryption_customer_key for this backend.
214 ///
215 /// Value: BASE64-encoded key that matches algorithm specified in
216 /// `server_side_encryption_customer_algorithm`.
217 ///
218 /// <!-- @group Encryption -->
219 #[serde(alias = "aws_sse_customer_key_base64")]
220 pub server_side_encryption_customer_key: Option<String>,
221 /// Set server_side_encryption_customer_key_md5 for this backend.
222 ///
223 /// Value: MD5 digest of key specified in `server_side_encryption_customer_key`.
224 ///
225 /// <!-- @group Encryption -->
226 pub server_side_encryption_customer_key_md5: Option<String>,
227 /// default storage_class for this backend.
228 ///
229 /// Available values:
230 /// - `DEEP_ARCHIVE`
231 /// - `GLACIER`
232 /// - `GLACIER_IR`
233 /// - `INTELLIGENT_TIERING`
234 /// - `ONEZONE_IA`
235 /// - `EXPRESS_ONEZONE`
236 /// - `OUTPOSTS`
237 /// - `REDUCED_REDUNDANCY`
238 /// - `STANDARD`
239 /// - `STANDARD_IA`
240 ///
241 /// S3 compatible services don't support all of them
242 ///
243 /// <!-- @group Behavior -->
244 pub default_storage_class: Option<String>,
245 /// Enable virtual host style so that opendal will send API requests
246 /// in virtual host style instead of path style.
247 ///
248 /// - By default, opendal will send API to `https://s3.us-east-1.amazonaws.com/bucket_name`
249 /// - Enabled, opendal will send API to `https://bucket_name.s3.us-east-1.amazonaws.com`
250 ///
251 /// <!-- @group Behavior -->
252 #[serde(
253 alias = "aws_virtual_hosted_style_request",
254 alias = "virtual_hosted_style_request"
255 )]
256 pub enable_virtual_host_style: bool,
257 /// Deprecated: S3 delete batch capability is enabled by default.
258 ///
259 /// <!-- @group Deprecated -->
260 #[deprecated(
261 since = "0.57.0",
262 note = "S3 delete batch capability is enabled by default. Use CapabilityOverrideLayer to override delete_max_size for specific endpoints."
263 )]
264 pub batch_max_operations: Option<usize>,
265 /// Deprecated: S3 delete batch capability is enabled by default.
266 ///
267 /// <!-- @group Deprecated -->
268 #[deprecated(
269 since = "0.57.0",
270 note = "S3 delete batch capability is enabled by default. Use CapabilityOverrideLayer to override delete_max_size for specific endpoints."
271 )]
272 pub delete_max_size: Option<usize>,
273 /// Deprecated: S3 stat override capabilities are enabled by default.
274 ///
275 /// <!-- @group Deprecated -->
276 #[deprecated(
277 since = "0.57.0",
278 note = "S3 stat override capabilities are enabled by default. Use CapabilityOverrideLayer to override them for specific endpoints."
279 )]
280 pub disable_stat_with_override: bool,
281 /// Checksum Algorithm to use when sending checksums in HTTP headers.
282 /// This is necessary when writing to AWS S3 Buckets with Object Lock enabled for example.
283 ///
284 /// Available options:
285 /// - "crc32c"
286 /// - "md5"
287 ///
288 /// <!-- @group Behavior -->
289 #[serde(alias = "aws_checksum_algorithm")]
290 pub checksum_algorithm: Option<String>,
291 /// Deprecated: S3 write with If-Match capability is enabled by default.
292 ///
293 /// <!-- @group Deprecated -->
294 #[deprecated(
295 since = "0.57.0",
296 note = "S3 write with If-Match capability is enabled by default and this option is no longer needed."
297 )]
298 pub disable_write_with_if_match: bool,
299
300 /// Deprecated: S3 append capability is enabled by default.
301 ///
302 /// <!-- @group Deprecated -->
303 #[deprecated(
304 since = "0.57.0",
305 note = "S3 append capability is enabled by default and this option is no longer needed."
306 )]
307 pub enable_write_with_append: bool,
308
309 /// OpenDAL uses List Objects V2 by default to list objects.
310 /// However, some legacy services do not yet support V2.
311 /// This option allows users to switch back to the older List Objects V1.
312 ///
313 /// <!-- @group Behavior -->
314 pub disable_list_objects_v2: bool,
315
316 /// Indicates whether the client agrees to pay for the requests made to the S3 bucket.
317 ///
318 /// <!-- @group Behavior -->
319 #[serde(alias = "aws_request_payer", alias = "request_payer")]
320 pub enable_request_payer: bool,
321
322 /// Default ACL for new objects.
323 /// Note that some s3 services like minio do not support this option.
324 ///
325 /// <!-- @group Behavior -->
326 pub default_acl: Option<String>,
327}
328
329impl Debug for S3Config {
330 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
331 f.debug_struct("S3Config")
332 .field("root", &self.root)
333 .field("bucket", &self.bucket)
334 .field("endpoint", &self.endpoint)
335 .field("region", &self.region)
336 .finish_non_exhaustive()
337 }
338}
339
340impl Configurator for S3Config {
341 type Builder = S3Builder;
342
343 fn from_uri(uri: &OperatorUri) -> Result<Self> {
344 let mut map = uri.options().clone();
345
346 if let Some(name) = uri.name() {
347 map.insert("bucket".to_string(), name.to_string());
348 }
349
350 if let Some(root) = uri.root() {
351 map.insert("root".to_string(), root.to_string());
352 }
353
354 Self::from_iter(map)
355 }
356
357 #[allow(deprecated)]
358 fn into_builder(self) -> Self::Builder {
359 S3Builder {
360 config: self,
361 credential_providers: None,
362 }
363 }
364}
365
366#[cfg(test)]
367mod tests {
368 use std::iter;
369
370 use super::*;
371 use opendal_core::Configurator;
372 use opendal_core::OperatorUri;
373
374 #[test]
375 fn test_s3_config_original_field_names() {
376 let json = r#"{
377 "bucket": "test-bucket",
378 "access_key_id": "test-key",
379 "secret_access_key": "test-secret",
380 "region": "us-west-2",
381 "endpoint": "https://s3.amazonaws.com",
382 "profile": "development",
383 "session_token": "test-token"
384 }"#;
385
386 let config: S3Config = serde_json::from_str(json).unwrap();
387 assert_eq!(config.bucket, "test-bucket");
388 assert_eq!(config.access_key_id, Some("test-key".to_string()));
389 assert_eq!(config.secret_access_key, Some("test-secret".to_string()));
390 assert_eq!(config.region, Some("us-west-2".to_string()));
391 assert_eq!(
392 config.endpoint,
393 Some("https://s3.amazonaws.com".to_string())
394 );
395 assert_eq!(config.profile, Some("development".to_string()));
396 assert_eq!(config.session_token, Some("test-token".to_string()));
397 }
398
399 #[test]
400 fn test_s3_config_aws_prefixed_aliases() {
401 let json = r#"{
402 "aws_bucket": "test-bucket",
403 "aws_access_key_id": "test-key",
404 "aws_secret_access_key": "test-secret",
405 "aws_region": "us-west-2",
406 "aws_endpoint": "https://s3.amazonaws.com",
407 "aws_profile": "staging",
408 "aws_session_token": "test-token"
409 }"#;
410
411 let config: S3Config = serde_json::from_str(json).unwrap();
412 assert_eq!(config.bucket, "test-bucket");
413 assert_eq!(config.access_key_id, Some("test-key".to_string()));
414 assert_eq!(config.secret_access_key, Some("test-secret".to_string()));
415 assert_eq!(config.region, Some("us-west-2".to_string()));
416 assert_eq!(
417 config.endpoint,
418 Some("https://s3.amazonaws.com".to_string())
419 );
420 assert_eq!(config.profile, Some("staging".to_string()));
421 assert_eq!(config.session_token, Some("test-token".to_string()));
422 }
423
424 #[test]
425 fn test_s3_config_additional_aliases() {
426 let json = r#"{
427 "bucket_name": "test-bucket",
428 "token": "test-token",
429 "endpoint_url": "https://s3.amazonaws.com",
430 "virtual_hosted_style_request": true,
431 "aws_checksum_algorithm": "crc32c",
432 "request_payer": true
433 }"#;
434
435 let config: S3Config = serde_json::from_str(json).unwrap();
436 assert_eq!(config.bucket, "test-bucket");
437 assert_eq!(config.session_token, Some("test-token".to_string()));
438 assert_eq!(
439 config.endpoint,
440 Some("https://s3.amazonaws.com".to_string())
441 );
442 assert!(config.enable_virtual_host_style);
443 assert_eq!(config.checksum_algorithm, Some("crc32c".to_string()));
444 assert!(config.enable_request_payer);
445 }
446
447 #[test]
448 fn test_s3_config_encryption_aliases() {
449 let json = r#"{
450 "bucket": "test-bucket",
451 "aws_server_side_encryption": "aws:kms",
452 "aws_sse_kms_key_id": "test-kms-key",
453 "aws_sse_customer_key_base64": "dGVzdC1jdXN0b21lci1rZXk="
454 }"#;
455
456 let config: S3Config = serde_json::from_str(json).unwrap();
457 assert_eq!(config.bucket, "test-bucket");
458 assert_eq!(config.server_side_encryption, Some("aws:kms".to_string()));
459 assert_eq!(
460 config.server_side_encryption_aws_kms_key_id,
461 Some("test-kms-key".to_string())
462 );
463 assert_eq!(
464 config.server_side_encryption_customer_key,
465 Some("dGVzdC1jdXN0b21lci1rZXk=".to_string())
466 );
467 }
468
469 #[test]
470 fn from_uri_extracts_bucket_and_root() {
471 let uri = OperatorUri::new("s3://example-bucket/path/to/root", iter::empty()).unwrap();
472 let cfg = S3Config::from_uri(&uri).unwrap();
473 assert_eq!(cfg.bucket, "example-bucket");
474 assert_eq!(cfg.root.as_deref(), Some("path/to/root"));
475 }
476
477 #[test]
478 fn from_uri_extracts_endpoint() {
479 let uri = OperatorUri::new(
480 "s3://example-bucket/path/to/root?endpoint=https%3A%2F%2Fcustom-s3-endpoint.com",
481 iter::empty(),
482 )
483 .unwrap();
484 let cfg = S3Config::from_uri(&uri).unwrap();
485 assert_eq!(cfg.bucket, "example-bucket");
486 assert_eq!(cfg.root.as_deref(), Some("path/to/root"));
487 assert_eq!(
488 cfg.endpoint.as_deref(),
489 Some("https://custom-s3-endpoint.com")
490 );
491 }
492}