Skip to main content

opendal_service_obs/
backend.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;
20use std::sync::Arc;
21
22use http::StatusCode;
23use http::Uri;
24use log::debug;
25use opendal_core::raw::*;
26use opendal_core::*;
27use reqsign_core::Context;
28use reqsign_core::OsEnv;
29use reqsign_file_read_tokio::TokioFileRead;
30use reqsign_huaweicloud_obs::DefaultCredentialProvider;
31use reqsign_huaweicloud_obs::RequestSigner;
32use reqsign_huaweicloud_obs::StaticCredentialProvider;
33
34use super::OBS_SCHEME;
35use super::config::ObsConfig;
36use super::core::constants;
37use super::core::parse_error;
38use super::core::{ErrorContext, ObsCore};
39use super::deleter::ObsDeleter;
40use super::lister::ObsLister;
41use super::reader::*;
42use super::writer::ObsWriter;
43use super::writer::ObsWriters;
44
45/// Huawei-Cloud Object Storage Service (OBS) support
46#[doc = include_str!("docs.md")]
47#[derive(Default)]
48pub struct ObsBuilder {
49    pub(super) config: ObsConfig,
50}
51
52impl Debug for ObsBuilder {
53    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        f.debug_struct("ObsBuilder")
55            .field("config", &self.config)
56            .finish_non_exhaustive()
57    }
58}
59
60impl ObsBuilder {
61    /// Set root of this backend.
62    ///
63    /// All operations will happen under this root.
64    pub fn root(mut self, root: &str) -> Self {
65        self.config.root = if root.is_empty() {
66            None
67        } else {
68            Some(root.to_string())
69        };
70
71        self
72    }
73
74    /// Set endpoint of this backend.
75    ///
76    /// Both huaweicloud default domain and user domain endpoints are allowed.
77    /// Please DO NOT add the bucket name to the endpoint.
78    ///
79    /// - `https://obs.cn-north-4.myhuaweicloud.com`
80    /// - `obs.cn-north-4.myhuaweicloud.com` (https by default)
81    /// - `https://custom.obs.com` (port should not be set)
82    pub fn endpoint(mut self, endpoint: &str) -> Self {
83        if !endpoint.is_empty() {
84            self.config.endpoint = Some(endpoint.trim_end_matches('/').to_string());
85        }
86
87        self
88    }
89
90    /// Set access_key_id of this backend.
91    /// - If it is set, we will take user's input first.
92    /// - If not, we will try to load it from environment.
93    pub fn access_key_id(mut self, access_key_id: &str) -> Self {
94        if !access_key_id.is_empty() {
95            self.config.access_key_id = Some(access_key_id.to_string());
96        }
97
98        self
99    }
100
101    /// Set secret_access_key of this backend.
102    /// - If it is set, we will take user's input first.
103    /// - If not, we will try to load it from environment.
104    pub fn secret_access_key(mut self, secret_access_key: &str) -> Self {
105        if !secret_access_key.is_empty() {
106            self.config.secret_access_key = Some(secret_access_key.to_string());
107        }
108
109        self
110    }
111
112    /// Set security_token of this backend.
113    ///
114    /// Use this together with `access_key_id` and `secret_access_key` when the
115    /// credentials are temporary. The signer attaches the token as the
116    /// `x-obs-security-token` header.
117    ///
118    /// - If it is set, we will take user's input first.
119    /// - If not, we will try to load it from environment (unless
120    ///   `disable_config_load` is enabled).
121    pub fn security_token(mut self, security_token: &str) -> Self {
122        if !security_token.is_empty() {
123            self.config.security_token = Some(security_token.to_string());
124        }
125
126        self
127    }
128
129    /// Set bucket of this backend.
130    /// The param is required.
131    pub fn bucket(mut self, bucket: &str) -> Self {
132        if !bucket.is_empty() {
133            self.config.bucket = Some(bucket.to_string());
134        }
135
136        self
137    }
138
139    /// Disable config load so that opendal will not load config from
140    /// environment.
141    ///
142    /// For examples:
143    ///
144    /// - envs like `HUAWEI_CLOUD_ACCESS_KEY_ID`
145    pub fn disable_config_load(mut self) -> Self {
146        self.config.disable_config_load = true;
147        self
148    }
149
150    /// Skip signature will skip loading credentials and signing requests.
151    pub fn skip_signature(mut self) -> Self {
152        self.config.skip_signature = true;
153        self
154    }
155
156    /// Deprecated: OBS versioning capability is not controlled by service config.
157    #[deprecated(
158        since = "0.57.0",
159        note = "OBS versioning capability is not controlled by this option and this option is no longer needed."
160    )]
161    pub fn enable_versioning(self, _enabled: bool) -> Self {
162        self
163    }
164}
165
166impl Builder for ObsBuilder {
167    type Config = ObsConfig;
168
169    fn build(self) -> Result<impl Service> {
170        debug!("backend build started: {:?}", self);
171
172        let root = normalize_root(&self.config.root.clone().unwrap_or_default());
173        debug!("backend use root {root}");
174
175        let bucket = match &self.config.bucket {
176            Some(bucket) => Ok(bucket.to_string()),
177            None => Err(
178                Error::new(ErrorKind::ConfigInvalid, "The bucket is misconfigured")
179                    .with_context("service", OBS_SCHEME),
180            ),
181        }?;
182        debug!("backend use bucket {}", bucket);
183
184        let uri = match &self.config.endpoint {
185            Some(endpoint) => endpoint.parse::<Uri>().map_err(|err| {
186                Error::new(ErrorKind::ConfigInvalid, "endpoint is invalid")
187                    .with_context("service", OBS_SCHEME)
188                    .set_source(err)
189            }),
190            None => Err(Error::new(ErrorKind::ConfigInvalid, "endpoint is empty")
191                .with_context("service", OBS_SCHEME)),
192        }?;
193
194        let scheme = match uri.scheme_str() {
195            Some(scheme) => scheme.to_string(),
196            None => "https".to_string(),
197        };
198
199        let (endpoint, is_obs_default) = {
200            let host = uri.host().unwrap_or_default().to_string();
201            if host.starts_with("obs.")
202                && (host.ends_with(".myhuaweicloud.com") || host.ends_with(".huawei.com"))
203            {
204                (format!("{bucket}.{host}"), true)
205            } else {
206                (host, false)
207            }
208        };
209        debug!("backend use endpoint {}", endpoint);
210
211        let ctx = Context::new().with_file_read(TokioFileRead).with_env(OsEnv);
212
213        let provider = credential_provider(&self.config);
214
215        // Set the bucket name in CanonicalizedResource.
216        // 1. If the bucket is bound to a user domain name, use the user domain name as the bucket name,
217        // for example, `/obs.ccc.com/object`. `obs.ccc.com` is the user domain name bound to the bucket.
218        // 2. If you do not access OBS using a user domain name, this field is in the format of `/bucket/object`.
219        //
220        // Please refer to this doc for more details:
221        // https://support.huaweicloud.com/intl/en-us/api-obs/obs_04_0010.html
222        let credential_provider = Arc::new(provider);
223        let request_signer = Arc::new(RequestSigner::new(if is_obs_default {
224            &bucket
225        } else {
226            &endpoint
227        }));
228
229        let info = ServiceInfo::new(OBS_SCHEME, &root, &bucket);
230        let capability = Capability {
231            stat: true,
232            stat_with_if_match: true,
233            stat_with_if_none_match: true,
234
235            read: true,
236            read_with_suffix: true,
237
238            read_with_if_match: true,
239            read_with_if_none_match: true,
240            read_with_if_modified_since: true,
241            read_with_if_unmodified_since: true,
242
243            write: true,
244            write_can_empty: true,
245            write_can_append: true,
246            write_can_multi: true,
247            write_with_content_type: true,
248            write_with_cache_control: true,
249            // The min multipart size of OBS is 5 MiB.
250            //
251            // ref: <https://support.huaweicloud.com/intl/en-us/ugobs-obs/obs_41_0021.html>
252            write_multi_min_size: Some(5 * 1024 * 1024),
253            // The max multipart size of OBS is 5 GiB.
254            //
255            // ref: <https://support.huaweicloud.com/intl/en-us/ugobs-obs/obs_41_0021.html>
256            write_multi_max_size: if cfg!(target_pointer_width = "64") {
257                Some(5 * 1024 * 1024 * 1024)
258            } else {
259                Some(usize::MAX)
260            },
261            write_with_user_metadata: true,
262
263            delete: true,
264            copy: true,
265
266            list: true,
267            list_with_recursive: true,
268
269            presign: true,
270            presign_stat: true,
271            presign_read: true,
272            presign_write: true,
273
274            shared: true,
275
276            ..Default::default()
277        };
278
279        debug!("backend build finished");
280        Ok(ObsBackend {
281            core: Arc::new(ObsCore {
282                info,
283                capability,
284                bucket,
285                root,
286                endpoint: format!("{}://{}", scheme, endpoint),
287                skip_signature: self.config.skip_signature,
288                sign_ctx: ctx,
289                credential_provider,
290                request_signer,
291                signers: HttpTransportCache::new(),
292            }),
293        })
294    }
295}
296
297/// Build the credential chain used by the signer.
298///
299/// Explicit static credentials always take precedence over the environment.
300/// `disable_config_load` drops the environment provider so that ambient
301/// credentials are never loaded.
302pub(super) fn credential_provider(config: &ObsConfig) -> DefaultCredentialProvider {
303    let provider = if config.disable_config_load {
304        DefaultCredentialProvider::builder().no_env().build()
305    } else {
306        DefaultCredentialProvider::builder().build()
307    };
308
309    match (&config.access_key_id, &config.secret_access_key) {
310        (Some(ak), Some(sk)) => {
311            let static_provider = match config.security_token.as_deref() {
312                Some(token) => StaticCredentialProvider::with_security_token(ak, sk, token),
313                None => StaticCredentialProvider::new(ak, sk),
314            };
315
316            provider.push_front(static_provider)
317        }
318        _ => provider,
319    }
320}
321
322/// Backend for Huaweicloud OBS services.
323#[derive(Debug, Clone)]
324pub struct ObsBackend {
325    pub(crate) core: Arc<ObsCore>,
326}
327
328impl Service for ObsBackend {
329    type Reader = oio::StreamReader<ObsReader>;
330    type Writer = ObsWriters;
331    type Lister = oio::PageLister<ObsLister>;
332    type Deleter = oio::OneShotDeleter<ObsDeleter>;
333    type Copier = oio::OneShotCopier;
334    type Composer = ();
335
336    fn info(&self) -> ServiceInfo {
337        self.core.info.clone()
338    }
339
340    fn capability(&self) -> Capability {
341        self.core.capability
342    }
343
344    async fn create_dir(
345        &self,
346        _ctx: &OperationContext,
347        _path: &str,
348        _args: OpCreateDir,
349    ) -> Result<RpCreateDir> {
350        Err(Error::new(
351            ErrorKind::Unsupported,
352            "operation is not supported",
353        ))
354    }
355
356    async fn stat(&self, ctx: &OperationContext, path: &str, args: OpStat) -> Result<RpStat> {
357        let resp = self.core.obs_head_object(ctx, path, &args).await?;
358        let headers = resp.headers();
359
360        let status = resp.status();
361
362        // The response is very similar to azblob.
363        match status {
364            StatusCode::OK => {
365                let meta = parse_into_metadata(path, headers)?;
366                let user_meta = headers
367                    .iter()
368                    .filter_map(|(name, _)| {
369                        name.as_str()
370                            .strip_prefix(constants::X_OBS_META_PREFIX)
371                            .and_then(|stripped_key| {
372                                parse_header_to_str(headers, name)
373                                    .unwrap_or(None)
374                                    .map(|val| (stripped_key.to_string(), val.to_string()))
375                            })
376                    })
377                    .collect::<HashMap<_, _>>();
378
379                let mut meta = meta.into_builder();
380                if !user_meta.is_empty() {
381                    meta.user_metadata(user_meta);
382                }
383
384                if let Some(v) = parse_header_to_str(headers, constants::X_OBS_VERSION_ID)? {
385                    meta.version(v);
386                }
387
388                Ok(RpStat::new(meta.build()))
389            }
390            StatusCode::NOT_FOUND if path.ends_with('/') => {
391                Ok(RpStat::new(MetadataBuilder::dir().build()))
392            }
393            _ => Err(parse_error(
394                ErrorContext::new(ServiceOperation("HeadObject")),
395                resp,
396            )),
397        }
398    }
399    fn read(&self, ctx: &OperationContext, path: &str, args: OpRead) -> Result<Self::Reader> {
400        let output: oio::StreamReader<ObsReader> = {
401            Ok(oio::StreamReader::new(ObsReader::new(
402                self.clone(),
403                ctx.clone(),
404                path,
405                args,
406            )))
407        }?;
408
409        Ok(output)
410    }
411
412    fn write(&self, ctx: &OperationContext, path: &str, args: OpWrite) -> Result<Self::Writer> {
413        let output: ObsWriters = {
414            let writer = ObsWriter::new(self.core.clone(), ctx.clone(), path, args.clone());
415
416            let w = if args.append() {
417                ObsWriters::Two(oio::AppendWriter::new(writer))
418            } else {
419                ObsWriters::One(oio::MultipartWriter::new(
420                    ctx.executor().clone(),
421                    writer,
422                    args.concurrent(),
423                ))
424            };
425
426            Ok(w)
427        }?;
428
429        Ok(output)
430    }
431
432    fn delete(&self, ctx: &OperationContext) -> Result<Self::Deleter> {
433        let output: oio::OneShotDeleter<ObsDeleter> = {
434            Ok(oio::OneShotDeleter::new(ObsDeleter::new(
435                self.core.clone(),
436                ctx.clone(),
437            )))
438        }?;
439
440        Ok(output)
441    }
442
443    fn list(&self, ctx: &OperationContext, path: &str, args: OpList) -> Result<Self::Lister> {
444        let output: oio::PageLister<ObsLister> = {
445            let l = ObsLister::new(
446                self.core.clone(),
447                ctx.clone(),
448                path,
449                args.recursive(),
450                args.limit(),
451            );
452            Ok(oio::PageLister::new(l))
453        }?;
454
455        Ok(output)
456    }
457
458    fn copy(
459        &self,
460        ctx: &OperationContext,
461        from: &str,
462        to: &str,
463        args: OpCopy,
464    ) -> Result<Self::Copier> {
465        let backend = self.clone();
466        let core = self.core.clone();
467        let ctx = ctx.clone();
468        let from = from.to_string();
469        let to = to.to_string();
470        let source_content_length_hint = args.source_content_length_hint();
471        Ok(oio::OneShotCopier::new(async move {
472            let source_size = match source_content_length_hint {
473                Some(size) => size,
474                None => backend
475                    .stat(&ctx, &from, OpStat::default())
476                    .await?
477                    .into_metadata()
478                    .content_length(),
479            };
480
481            let resp = core.obs_copy_object(&ctx, &from, &to).await?;
482
483            let status = resp.status();
484
485            match status {
486                StatusCode::OK => Ok(MetadataBuilder::file(source_size).build()),
487                _ => Err(parse_error(
488                    ErrorContext::new(ServiceOperation("CopyObject")),
489                    resp,
490                )),
491            }
492        }))
493    }
494
495    async fn rename(
496        &self,
497        _ctx: &OperationContext,
498        _from: &str,
499        _to: &str,
500        _args: OpRename,
501    ) -> Result<RpRename> {
502        Err(Error::new(
503            ErrorKind::Unsupported,
504            "operation is not supported",
505        ))
506    }
507
508    async fn presign(
509        &self,
510        ctx: &OperationContext,
511        path: &str,
512        args: OpPresign,
513    ) -> Result<RpPresign> {
514        let req = match args.operation() {
515            PresignOperation::Stat(v) => self.core.obs_head_object_request(path, v),
516            PresignOperation::Read(range, v) => self.core.obs_get_object_request(path, *range, v),
517            PresignOperation::Write(v) => {
518                self.core
519                    .obs_put_object_request(path, None, v, Buffer::new())
520            }
521            PresignOperation::Delete(_) => Err(Error::new(
522                ErrorKind::Unsupported,
523                "operation is not supported",
524            )),
525            _ => Err(Error::new(
526                ErrorKind::Unsupported,
527                "operation is not supported",
528            )),
529        };
530        let req = req?;
531        let req = self.core.sign_query(ctx, req, args.expire()).await?;
532
533        // We don't need this request anymore, consume it directly.
534        let (parts, _) = req.into_parts();
535
536        Ok(RpPresign::new(PresignedRequest::new(
537            parts.method,
538            parts.uri,
539            parts.headers,
540        )))
541    }
542}
543
544#[cfg(test)]
545mod tests {
546    use std::collections::HashMap;
547
548    use reqsign_core::Context;
549    use reqsign_core::ProvideCredential;
550    use reqsign_core::Signer;
551    use reqsign_core::StaticEnv;
552
553    use super::*;
554
555    const AMBIENT_ENVS: [(&str, &str); 3] = [
556        ("HUAWEI_CLOUD_ACCESS_KEY_ID", "env-access-key-id"),
557        ("HUAWEI_CLOUD_SECRET_ACCESS_KEY", "env-secret-access-key"),
558        ("HUAWEI_CLOUD_SECURITY_TOKEN", "env-security-token"),
559    ];
560
561    fn ambient_context() -> Context {
562        Context::new().with_env(StaticEnv {
563            home_dir: None,
564            envs: AMBIENT_ENVS
565                .into_iter()
566                .map(|(key, value)| (key.to_string(), value.to_string()))
567                .collect::<HashMap<_, _>>(),
568        })
569    }
570
571    fn static_config() -> ObsConfig {
572        ObsConfig {
573            access_key_id: Some("static-access-key-id".to_string()),
574            secret_access_key: Some("static-secret-access-key".to_string()),
575            security_token: Some("static-security-token".to_string()),
576            ..Default::default()
577        }
578    }
579
580    #[tokio::test]
581    async fn default_provider_loads_ambient_credentials() {
582        let provider = credential_provider(&ObsConfig::default());
583
584        let credential = provider
585            .provide_credential(&ambient_context())
586            .await
587            .unwrap()
588            .expect("ambient credentials must be loaded");
589
590        assert_eq!(credential.access_key_id, "env-access-key-id");
591        assert_eq!(
592            credential.security_token.as_deref(),
593            Some("env-security-token")
594        );
595    }
596
597    #[tokio::test]
598    async fn disable_config_load_ignores_ambient_credentials() {
599        let provider = credential_provider(&ObsConfig {
600            disable_config_load: true,
601            ..Default::default()
602        });
603
604        let credential = provider
605            .provide_credential(&ambient_context())
606            .await
607            .unwrap();
608
609        assert!(credential.is_none());
610    }
611
612    #[tokio::test]
613    async fn disable_config_load_keeps_explicit_credentials() {
614        let provider = credential_provider(&ObsConfig {
615            disable_config_load: true,
616            ..static_config()
617        });
618
619        let credential = provider
620            .provide_credential(&ambient_context())
621            .await
622            .unwrap()
623            .expect("explicit static credentials must be used");
624
625        assert_eq!(credential.access_key_id, "static-access-key-id");
626        assert_eq!(credential.secret_access_key, "static-secret-access-key");
627        assert_eq!(
628            credential.security_token.as_deref(),
629            Some("static-security-token")
630        );
631    }
632
633    #[tokio::test]
634    async fn security_token_is_signed_into_request_headers() {
635        let config = ObsConfig {
636            disable_config_load: true,
637            ..static_config()
638        };
639        let signer = Signer::new(
640            ambient_context(),
641            credential_provider(&config),
642            RequestSigner::new("example-bucket"),
643        );
644        let (mut parts, _) =
645            http::Request::get("https://example-bucket.obs.cn-north-4.myhuaweicloud.com/test.txt")
646                .body(())
647                .unwrap()
648                .into_parts();
649
650        signer.sign(&mut parts, None).await.unwrap();
651
652        assert_eq!(
653            parts.headers["x-obs-security-token"],
654            "static-security-token"
655        );
656        assert!(
657            parts.headers[http::header::AUTHORIZATION]
658                .to_str()
659                .unwrap()
660                .starts_with("OBS static-access-key-id:")
661        );
662    }
663}