You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@opendal.apache.org by xu...@apache.org on 2023/05/30 04:06:39 UTC

[incubator-opendal] branch main updated: feat: server side encryption support for azblob (#2347)

This is an automated email from the ASF dual-hosted git repository.

xuanwo pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/incubator-opendal.git


The following commit(s) were added to refs/heads/main by this push:
     new c5d5b565 feat: server side encryption support for azblob (#2347)
c5d5b565 is described below

commit c5d5b565a3c3a52cbd4145ccfc2be425ac3eeeca
Author: Morris Tai <mo...@gmail.com>
AuthorDate: Tue May 30 00:06:35 2023 -0400

    feat: server side encryption support for azblob (#2347)
    
    * feat(core): add server side encryption fields into azblob structs
    
    * feat(core): add server side encryption build methods in azblob backend
    
    * fix(core): fix document typo in method insert_sse_headers
    
    * feat(core): add insert_sse_headers suppport in azblob
    
    * chore(core): reformat with cargo fmt
    
    * feat(core): align header names and modify for the PR review
    
    * feat(core): add sha2 as optional and only enable in services-azblob
    
    * feat(core): add azblob backend SSE functions comments
---
 core/Cargo.toml                     |   2 +
 core/src/services/azblob/backend.rs | 127 ++++++++++++++++++++++++++++++++++++
 core/src/services/azblob/core.rs    |  57 +++++++++++++++-
 core/src/services/s3/core.rs        |   2 +-
 4 files changed, 186 insertions(+), 2 deletions(-)

diff --git a/core/Cargo.toml b/core/Cargo.toml
index 9571b90f..5521bedb 100644
--- a/core/Cargo.toml
+++ b/core/Cargo.toml
@@ -92,6 +92,7 @@ layers-tracing = ["dep:tracing"]
 layers-otel-trace = ["dep:opentelemetry"]
 
 services-azblob = [
+  "dep:sha2",
   "dep:reqsign",
   "reqsign?/services-azblob",
   "reqsign?/reqwest_request",
@@ -209,6 +210,7 @@ reqwest = { version = "0.11.13", features = [
 rocksdb = { version = "0.21.0", default-features = false, optional = true }
 serde = { version = "1", features = ["derive"] }
 serde_json = "1"
+sha2 = { version = "0.10", optional = true }
 sled = { version = "0.34.7", optional = true }
 suppaftp = { version = "4.5", default-features = false, features = [
   "async-secure",
diff --git a/core/src/services/azblob/backend.rs b/core/src/services/azblob/backend.rs
index 9e7811dd..6b52b535 100644
--- a/core/src/services/azblob/backend.rs
+++ b/core/src/services/azblob/backend.rs
@@ -21,12 +21,16 @@ use std::fmt::Formatter;
 use std::sync::Arc;
 
 use async_trait::async_trait;
+use base64::prelude::BASE64_STANDARD;
+use base64::Engine;
 use http::header::CONTENT_TYPE;
 use http::StatusCode;
 use log::debug;
 use reqsign::AzureStorageConfig;
 use reqsign::AzureStorageLoader;
 use reqsign::AzureStorageSigner;
+use sha2::Digest;
+use sha2::Sha256;
 
 use super::appender::AzblobAppender;
 use super::batch::parse_batch_delete_response;
@@ -59,6 +63,9 @@ pub struct AzblobBuilder {
     endpoint: Option<String>,
     account_name: Option<String>,
     account_key: Option<String>,
+    encryption_key: Option<String>,
+    encryption_key_sha256: Option<String>,
+    encryption_algorithm: Option<String>,
     sas_token: Option<String>,
     http_client: Option<HttpClient>,
 }
@@ -143,6 +150,87 @@ impl AzblobBuilder {
         self
     }
 
+    /// Set encryption_key of this backend.
+    ///
+    /// # Args
+    ///
+    /// `v`: Base64-encoded key that matches algorithm specified in `encryption_algorithm`.
+    ///
+    /// # Note
+    ///
+    /// This function is the low-level setting for SSE related features.
+    ///
+    /// SSE related options should be set carefully to make them works.
+    /// Please use `server_side_encryption_with_*` helpers if even possible.
+    pub fn encryption_key(&mut self, v: &str) -> &mut Self {
+        if !v.is_empty() {
+            self.encryption_key = Some(v.to_string());
+        }
+
+        self
+    }
+
+    /// Set encryption_key_sha256 of this backend.
+    ///
+    /// # Args
+    ///
+    /// `v`: Base64-encoded SHA256 digest of the key specified in encryption_key.
+    ///
+    /// # Note
+    ///
+    /// This function is the low-level setting for SSE related features.
+    ///
+    /// SSE related options should be set carefully to make them works.
+    /// Please use `server_side_encryption_with_*` helpers if even possible.
+    pub fn encryption_key_sha256(&mut self, v: &str) -> &mut Self {
+        if !v.is_empty() {
+            self.encryption_key_sha256 = Some(v.to_string());
+        }
+
+        self
+    }
+
+    /// Set encryption_algorithm of this backend.
+    ///
+    /// # Args
+    ///
+    /// `v`: server-side encryption algorithm. (Available values: `AES256`)
+    ///
+    /// # Note
+    ///
+    /// This function is the low-level setting for SSE related features.
+    ///
+    /// SSE related options should be set carefully to make them works.
+    /// Please use `server_side_encryption_with_*` helpers if even possible.
+    pub fn encryption_algorithm(&mut self, v: &str) -> &mut Self {
+        if !v.is_empty() {
+            self.encryption_algorithm = Some(v.to_string());
+        }
+
+        self
+    }
+
+    /// Enable server side encryption with customer key.
+    ///
+    /// As known as: CPK
+    ///
+    /// # Args
+    ///
+    /// `key`: Base64-encoded SHA256 digest of the key specified in encryption_key.
+    ///
+    /// # Note
+    ///
+    /// Function that helps the user to set the server-side customer-provided encryption key, the key's SHA256, and the algorithm.
+    /// See [Server-side encryption with customer-provided keys (CPK)](https://learn.microsoft.com/en-us/azure/storage/blobs/encryption-customer-provided-keys)
+    /// for more info.
+    pub fn server_side_encryption_with_customer_key(&mut self, key: &[u8]) -> &mut Self {
+        // Only AES256 is supported for now
+        self.encryption_algorithm = Some("AES256".to_string());
+        self.encryption_key = Some(BASE64_STANDARD.encode(key));
+        self.encryption_key_sha256 = Some(BASE64_STANDARD.encode(Sha256::digest(key).as_slice()));
+        self
+    }
+
     /// Set sas_token of this backend.
     ///
     /// - If sas_token is set, we will take user's input first.
@@ -266,6 +354,11 @@ impl Builder for AzblobBuilder {
         map.get("endpoint").map(|v| builder.endpoint(v));
         map.get("account_name").map(|v| builder.account_name(v));
         map.get("account_key").map(|v| builder.account_key(v));
+        map.get("encryption_key").map(|v| builder.encryption_key(v));
+        map.get("encryption_key_sha256")
+            .map(|v| builder.encryption_key_sha256(v));
+        map.get("encryption_algorithm")
+            .map(|v| builder.encryption_algorithm(v));
         map.get("sas_token").map(|v| builder.sas_token(v));
 
         builder
@@ -313,6 +406,37 @@ impl Builder for AzblobBuilder {
             ..Default::default()
         };
 
+        let encryption_key =
+            match &self.encryption_key {
+                None => None,
+                Some(v) => Some(build_header_value(v).map_err(|err| {
+                    err.with_context("key", "server_side_encryption_customer_key")
+                })?),
+            };
+
+        let encryption_key_sha256 = match &self.encryption_key_sha256 {
+            None => None,
+            Some(v) => Some(build_header_value(v).map_err(|err| {
+                err.with_context("key", "server_side_encryption_customer_key_sha256")
+            })?),
+        };
+
+        let encryption_algorithm = match &self.encryption_algorithm {
+            None => None,
+            Some(v) => {
+                if v == "AES256" {
+                    Some(build_header_value(v).map_err(|err| {
+                        err.with_context("key", "server_side_encryption_customer_algorithm")
+                    })?)
+                } else {
+                    return Err(Error::new(
+                        ErrorKind::ConfigInvalid,
+                        "encryption_algorithm value must be AES256",
+                    ));
+                }
+            }
+        };
+
         let cred_loader = AzureStorageLoader::new(config_loader);
 
         let signer = AzureStorageSigner::new();
@@ -323,6 +447,9 @@ impl Builder for AzblobBuilder {
             core: Arc::new(AzblobCore {
                 root,
                 endpoint,
+                encryption_key,
+                encryption_key_sha256,
+                encryption_algorithm,
                 container: self.container.clone(),
 
                 client,
diff --git a/core/src/services/azblob/core.rs b/core/src/services/azblob/core.rs
index 2b029597..f9f09b6a 100644
--- a/core/src/services/azblob/core.rs
+++ b/core/src/services/azblob/core.rs
@@ -26,6 +26,7 @@ use http::header::CONTENT_LENGTH;
 use http::header::CONTENT_TYPE;
 use http::header::IF_MATCH;
 use http::header::IF_NONE_MATCH;
+use http::HeaderValue;
 use http::Request;
 use http::Response;
 use reqsign::AzureStorageCredential;
@@ -40,13 +41,20 @@ mod constants {
     pub const X_MS_COPY_SOURCE: &str = "x-ms-copy-source";
     pub const X_MS_BLOB_CACHE_CONTROL: &str = "x-ms-blob-cache-control";
     pub const X_MS_BLOB_CONDITION_APPENDPOS: &str = "x-ms-blob-condition-appendpos";
+
+    // Server-side encryption with customer-provided headers
+    pub const X_MS_ENCRYPTION_KEY: &str = "x-ms-encryption-key";
+    pub const X_MS_ENCRYPTION_KEY_SHA256: &str = "x-ms-encryption-key-sha256";
+    pub const X_MS_ENCRYPTION_ALGORITHM: &str = "x-ms-encryption-algorithm";
 }
 
 pub struct AzblobCore {
     pub container: String,
     pub root: String,
     pub endpoint: String,
-
+    pub encryption_key: Option<HeaderValue>,
+    pub encryption_key_sha256: Option<HeaderValue>,
+    pub encryption_algorithm: Option<HeaderValue>,
     pub client: HttpClient,
     pub loader: AzureStorageLoader,
     pub signer: AzureStorageSigner,
@@ -105,6 +113,37 @@ impl AzblobCore {
     pub async fn send(&self, req: Request<AsyncBody>) -> Result<Response<IncomingAsyncBody>> {
         self.client.send(req).await
     }
+
+    pub fn insert_sse_headers(&self, mut req: http::request::Builder) -> http::request::Builder {
+        if let Some(v) = &self.encryption_key {
+            let mut v = v.clone();
+            v.set_sensitive(true);
+
+            req = req.header(HeaderName::from_static(constants::X_MS_ENCRYPTION_KEY), v)
+        }
+
+        if let Some(v) = &self.encryption_key_sha256 {
+            let mut v = v.clone();
+            v.set_sensitive(true);
+
+            req = req.header(
+                HeaderName::from_static(constants::X_MS_ENCRYPTION_KEY_SHA256),
+                v,
+            )
+        }
+
+        if let Some(v) = &self.encryption_algorithm {
+            let mut v = v.clone();
+            v.set_sensitive(true);
+
+            req = req.header(
+                HeaderName::from_static(constants::X_MS_ENCRYPTION_ALGORITHM),
+                v,
+            )
+        }
+
+        req
+    }
 }
 
 impl AzblobCore {
@@ -139,6 +178,9 @@ impl AzblobCore {
 
         let mut req = Request::get(&url);
 
+        // Set SSE headers.
+        req = self.insert_sse_headers(req);
+
         if !range.is_full() {
             // azblob doesn't support read with suffix range.
             //
@@ -207,6 +249,10 @@ impl AzblobCore {
         );
 
         let mut req = Request::put(&url);
+
+        // Set SSE headers.
+        req = self.insert_sse_headers(req);
+
         if let Some(cache_control) = cache_control {
             req = req.header(constants::X_MS_BLOB_CACHE_CONTROL, cache_control);
         }
@@ -263,6 +309,9 @@ impl AzblobCore {
 
         let mut req = Request::put(&url);
 
+        // Set SSE headers.
+        req = self.insert_sse_headers(req);
+
         // The content-length header must be set to zero
         // when creating an appendable blob.
         req = req.header(CONTENT_LENGTH, 0);
@@ -321,6 +370,9 @@ impl AzblobCore {
 
         let mut req = Request::put(&url);
 
+        // Set SSE headers.
+        req = self.insert_sse_headers(req);
+
         req = req.header(CONTENT_LENGTH, size);
 
         if let Some(pos) = position {
@@ -352,6 +404,9 @@ impl AzblobCore {
 
         let mut req = Request::head(&url);
 
+        // Set SSE headers.
+        req = self.insert_sse_headers(req);
+
         if let Some(if_none_match) = if_none_match {
             req = req.header(IF_NONE_MATCH, if_none_match);
         }
diff --git a/core/src/services/s3/core.rs b/core/src/services/s3/core.rs
index 0eca1266..bc38fe19 100644
--- a/core/src/services/s3/core.rs
+++ b/core/src/services/s3/core.rs
@@ -148,7 +148,7 @@ impl S3Core {
     /// # Note
     ///
     /// header like X_AMZ_SERVER_SIDE_ENCRYPTION doesn't need to set while
-    //  get or stat.
+    /// get or stat.
     pub fn insert_sse_headers(
         &self,
         mut req: http::request::Builder,