aliyun_oss_rs/bucket/
put_bucket_encryption.rs

1use crate::{
2    Error,
3    error::normal_error,
4    request::{Oss, OssRequest},
5};
6use bytes::Bytes;
7use http::Method;
8use http_body_util::Full;
9
10use super::BucketEncryption;
11
12/// Configure default server-side encryption for the bucket.
13///
14/// See the [Alibaba Cloud documentation](https://help.aliyun.com/zh/oss/developer-reference/putbucketencryption) for details.
15pub struct PutBucketEncryption {
16    req: OssRequest,
17    encryption: BucketEncryption,
18}
19
20impl PutBucketEncryption {
21    pub(super) fn new(oss: Oss) -> Self {
22        let mut req = OssRequest::new(oss, Method::PUT);
23        req.insert_query("encryption", "");
24        PutBucketEncryption {
25            req,
26            encryption: BucketEncryption::default(),
27        }
28    }
29
30    /// Set the encryption algorithm (for example, `AES256`, `KMS`).
31    pub fn set_algorithm(mut self, algorithm: impl ToString) -> Self {
32        self.encryption.rule.default_sse.sse_algorithm = algorithm.to_string();
33        self
34    }
35
36    /// Set the KMS master key ID. Only valid when the algorithm is `KMS`.
37    pub fn set_kms_master_key_id(mut self, key_id: impl ToString) -> Self {
38        self.encryption.rule.default_sse.kms_master_key_id = Some(key_id.to_string());
39        self
40    }
41
42    /// Replace the entire encryption document.
43    pub fn set_encryption(mut self, encryption: BucketEncryption) -> Self {
44        self.encryption = encryption;
45        self
46    }
47
48    /// Send the request.
49    pub async fn send(mut self) -> Result<(), Error> {
50        let body =
51            serde_xml_rs::to_string(&self.encryption).map_err(|_| Error::InvalidCharacter)?;
52        self.req.set_body(Full::new(Bytes::from(body)));
53        let response = self.req.send_to_oss()?.await?;
54        match response.status() {
55            code if code.is_success() => Ok(()),
56            _ => Err(normal_error(response).await),
57        }
58    }
59}
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64
65    #[test]
66    fn test_encryption_serialization() {
67        let xml = serde_xml_rs::to_string(&BucketEncryption::default()).unwrap();
68        assert!(xml.contains("<ServerSideEncryptionConfiguration>"));
69        assert!(xml.contains("<SSEAlgorithm>AES256</SSEAlgorithm>"));
70    }
71}