aliyun-oss 0.2.0

aliyun oss sdk
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
//! Credential types and provider trait for OSS authentication.

use std::fmt;

use async_trait::async_trait;

use crate::error::{OssError, OssErrorKind, Result};

#[derive(Clone)]
/// An Alibaba Cloud AccessKey ID.
pub struct AccessKeyId(String);

impl AccessKeyId {
    /// Creates a new `AccessKeyId` from a string.
    pub fn new(id: impl Into<String>) -> Self {
        Self(id.into())
    }

    /// Returns the inner key ID as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl From<String> for AccessKeyId {
    fn from(s: String) -> Self {
        Self(s)
    }
}

impl From<&str> for AccessKeyId {
    fn from(s: &str) -> Self {
        Self(s.to_string())
    }
}

impl fmt::Display for AccessKeyId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl fmt::Debug for AccessKeyId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("AccessKeyId")
            .field(&mask_string(&self.0))
            .finish()
    }
}

#[derive(Clone)]
/// An Alibaba Cloud AccessKey Secret with debug masking.
pub struct AccessKeySecret(String);

impl AccessKeySecret {
    /// Creates a new `AccessKeySecret` from a string.
    pub fn new(secret: impl Into<String>) -> Self {
        Self(secret.into())
    }

    /// Returns the inner secret as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl From<String> for AccessKeySecret {
    fn from(s: String) -> Self {
        Self(s)
    }
}

impl From<&str> for AccessKeySecret {
    fn from(s: &str) -> Self {
        Self(s.to_string())
    }
}

impl fmt::Debug for AccessKeySecret {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("AccessKeySecret").field(&"***").finish()
    }
}

fn mask_string(s: &str) -> String {
    if s.len() <= 8 {
        return "***".to_string();
    }
    let mut masked = String::with_capacity(s.len());
    masked.push_str(&s[..4]);
    masked.push_str("***");
    masked.push_str(&s[s.len() - 4..]);
    masked
}

/// OSS access credentials: AccessKey ID, AccessKey Secret, and optional security token.
pub struct Credentials {
    access_key_id: AccessKeyId,
    access_key_secret: AccessKeySecret,
    security_token: Option<String>,
}

impl Credentials {
    /// Creates a new `CredentialsBuilder`.
    pub fn builder() -> CredentialsBuilder {
        CredentialsBuilder::default()
    }

    /// Returns the AccessKey ID.
    pub fn access_key_id(&self) -> &str {
        self.access_key_id.as_str()
    }

    /// Returns the AccessKey Secret.
    pub fn access_key_secret(&self) -> &str {
        self.access_key_secret.as_str()
    }

    /// Returns the optional security token.
    pub fn security_token(&self) -> Option<&str> {
        self.security_token.as_deref()
    }
}

impl fmt::Debug for Credentials {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Credentials")
            .field("access_key_id", &self.access_key_id)
            .field("access_key_secret", &self.access_key_secret)
            .field(
                "security_token",
                &self.security_token.as_ref().map(|_| "***"),
            )
            .finish()
    }
}

/// Builder for constructing `Credentials`.
#[derive(Default)]
pub struct CredentialsBuilder {
    access_key_id: Option<AccessKeyId>,
    access_key_secret: Option<AccessKeySecret>,
    security_token: Option<String>,
}

impl CredentialsBuilder {
    /// Sets the AccessKey ID.
    pub fn access_key_id(mut self, id: impl Into<AccessKeyId>) -> Self {
        self.access_key_id = Some(id.into());
        self
    }

    /// Sets the AccessKey Secret.
    pub fn access_key_secret(mut self, secret: impl Into<AccessKeySecret>) -> Self {
        self.access_key_secret = Some(secret.into());
        self
    }

    /// Sets the optional security token (for STS credentials).
    pub fn security_token(mut self, token: impl Into<String>) -> Self {
        self.security_token = Some(token.into());
        self
    }

    /// Builds the `Credentials`, returning an error if required fields are missing.
    pub fn build(self) -> Result<Credentials> {
        Ok(Credentials {
            access_key_id: self.access_key_id.ok_or_else(|| OssError {
                kind: OssErrorKind::CredentialsError,
                context: Box::new(crate::error::ErrorContext {
                    operation: Some("build Credentials".into()),
                    ..Default::default()
                }),
                source: None,
            })?,
            access_key_secret: self.access_key_secret.ok_or_else(|| OssError {
                kind: OssErrorKind::CredentialsError,
                context: Box::new(crate::error::ErrorContext {
                    operation: Some("build Credentials".into()),
                    ..Default::default()
                }),
                source: None,
            })?,
            security_token: self.security_token,
        })
    }
}

/// Trait for providing OSS credentials asynchronously.
#[async_trait]
pub trait CredentialsProvider: Send + Sync {
    /// Returns the current credentials.
    async fn credentials(&self) -> Result<Credentials>;
}

/// A `CredentialsProvider` that returns statically configured credentials.
pub struct StaticCredentialsProvider {
    credentials: Credentials,
}

impl StaticCredentialsProvider {
    /// Creates a new `StaticCredentialsProvider` with the given credentials.
    pub fn new(credentials: Credentials) -> Self {
        Self { credentials }
    }
}

#[async_trait]
impl CredentialsProvider for StaticCredentialsProvider {
    async fn credentials(&self) -> Result<Credentials> {
        Ok(Credentials {
            access_key_id: self.credentials.access_key_id.clone(),
            access_key_secret: self.credentials.access_key_secret.clone(),
            security_token: self.credentials.security_token.clone(),
        })
    }
}

/// A `CredentialsProvider` that reads credentials from environment variables.
pub struct EnvironmentCredentialsProvider;

impl EnvironmentCredentialsProvider {
    const ENV_ACCESS_KEY_ID: &'static str = "OSS_ACCESS_KEY_ID";
    const ENV_ACCESS_KEY_SECRET: &'static str = "OSS_ACCESS_KEY_SECRET";
    const ENV_SECURITY_TOKEN: &'static str = "OSS_SECURITY_TOKEN";
}

#[async_trait]
impl CredentialsProvider for EnvironmentCredentialsProvider {
    async fn credentials(&self) -> Result<Credentials> {
        let access_key_id = std::env::var(Self::ENV_ACCESS_KEY_ID).map_err(|_| OssError {
            kind: OssErrorKind::CredentialsError,
            context: Box::new(crate::error::ErrorContext {
                operation: Some(format!("read {} from environment", Self::ENV_ACCESS_KEY_ID)),
                ..Default::default()
            }),
            source: None,
        })?;

        let access_key_secret =
            std::env::var(Self::ENV_ACCESS_KEY_SECRET).map_err(|_| OssError {
                kind: OssErrorKind::CredentialsError,
                context: Box::new(crate::error::ErrorContext {
                    operation: Some(format!(
                        "read {} from environment",
                        Self::ENV_ACCESS_KEY_SECRET
                    )),
                    ..Default::default()
                }),
                source: None,
            })?;

        let security_token = std::env::var(Self::ENV_SECURITY_TOKEN).ok();

        Credentials::builder()
            .access_key_id(access_key_id)
            .access_key_secret(access_key_secret)
            .security_token(security_token.unwrap_or_default())
            .build()
    }
}

/// A credentials provider chain that tries multiple providers in order.
pub struct CredentialsChain {
    providers: Vec<Box<dyn CredentialsProvider>>,
}

impl CredentialsChain {
    /// Creates a new `CredentialsChain` from a list of providers.
    pub fn new(providers: Vec<Box<dyn CredentialsProvider>>) -> Self {
        Self { providers }
    }

    /// Creates a new `CredentialsChainBuilder`.
    pub fn builder() -> CredentialsChainBuilder {
        CredentialsChainBuilder::default()
    }
}

/// Builder for constructing a `CredentialsChain`.
#[derive(Default)]
pub struct CredentialsChainBuilder {
    providers: Vec<Box<dyn CredentialsProvider>>,
}

impl CredentialsChainBuilder {
    /// Adds a provider to the chain.
    pub fn with(mut self, provider: impl CredentialsProvider + 'static) -> Self {
        self.providers.push(Box::new(provider));
        self
    }

    /// Builds the `CredentialsChain`.
    pub fn build(self) -> CredentialsChain {
        CredentialsChain::new(self.providers)
    }
}

#[async_trait]
impl CredentialsProvider for CredentialsChain {
    async fn credentials(&self) -> Result<Credentials> {
        for provider in &self.providers {
            if let Ok(creds) = provider.credentials().await {
                return Ok(creds);
            }
        }
        Err(OssError {
            kind: OssErrorKind::CredentialsError,
            context: Box::new(crate::error::ErrorContext {
                operation: Some("CredentialsChain".into()),
                ..Default::default()
            }),
            source: None,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn credentials_builder_creates_valid_credentials() {
        let creds = Credentials::builder()
            .access_key_id("test-ak")
            .access_key_secret("test-sk")
            .build()
            .unwrap();
        assert_eq!(creds.access_key_id(), "test-ak");
        assert_eq!(creds.access_key_secret(), "test-sk");
        assert!(creds.security_token().is_none());
    }

    #[test]
    fn credentials_with_security_token() {
        let creds = Credentials::builder()
            .access_key_id("ak")
            .access_key_secret("sk")
            .security_token("token123")
            .build()
            .unwrap();
        assert_eq!(creds.security_token().unwrap(), "token123");
    }

    #[test]
    fn credentials_builder_missing_access_key_id_returns_error() {
        let result = Credentials::builder().access_key_secret("sk").build();
        assert!(result.is_err());
    }

    #[test]
    fn credentials_builder_missing_access_key_secret_returns_error() {
        let result = Credentials::builder().access_key_id("ak").build();
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn static_credentials_provider_returns_same_credentials() {
        let creds = Credentials::builder()
            .access_key_id("ak")
            .access_key_secret("sk")
            .build()
            .unwrap();

        let provider = StaticCredentialsProvider::new(creds);
        let retrieved = provider.credentials().await.unwrap();
        assert_eq!(retrieved.access_key_id(), "ak");
        assert_eq!(retrieved.access_key_secret(), "sk");
    }

    #[test]
    fn access_key_secret_debug_does_not_leak_value() {
        let secret = "super-secret-key-12345";
        let ak_secret = AccessKeySecret::from(secret);
        let debug_str = format!("{:?}", ak_secret);
        assert!(!debug_str.contains("super-secret-key-12345"));
        assert!(debug_str.contains("***"));
    }

    #[test]
    fn access_key_id_debug_masks_short_value() {
        let id = AccessKeyId::from("short");
        let debug_str = format!("{:?}", id);
        assert!(debug_str.contains("***"));
    }

    #[test]
    fn access_key_id_debug_masks_long_value() {
        let id = AccessKeyId::from("LTAI5tVeryLongAccessKeyId");
        let debug_str = format!("{:?}", id);
        assert!(!debug_str.contains("VeryLongAccess"));
        assert!(debug_str.starts_with("AccessKeyId"));
        assert!(debug_str.contains("***"));
    }

    #[test]
    fn credentials_debug_does_not_leak_secret() {
        let creds = Credentials::builder()
            .access_key_id("my-ak")
            .access_key_secret("my-secret-sk")
            .security_token("my-token")
            .build()
            .unwrap();
        let debug_str = format!("{:?}", creds);
        assert!(!debug_str.contains("my-secret-sk"));
        assert!(debug_str.contains("***"));
    }

    #[test]
    fn environment_credentials_provider_reads_from_env() {
        let rt = tokio::runtime::Runtime::new().unwrap();

        let provider = EnvironmentCredentialsProvider;
        let result = rt.block_on(provider.credentials());
        assert!(result.is_err());

        unsafe {
            std::env::set_var("OSS_ACCESS_KEY_ID", "env-ak");
            std::env::set_var("OSS_ACCESS_KEY_SECRET", "env-sk");
            std::env::set_var("OSS_SECURITY_TOKEN", "env-token");
        }

        let creds = rt.block_on(provider.credentials()).unwrap();
        assert_eq!(creds.access_key_id(), "env-ak");
        assert_eq!(creds.access_key_secret(), "env-sk");

        unsafe {
            std::env::remove_var("OSS_ACCESS_KEY_ID");
            std::env::remove_var("OSS_ACCESS_KEY_SECRET");
            std::env::remove_var("OSS_SECURITY_TOKEN");
        }
    }

    #[tokio::test]
    async fn credentials_chain_falls_back_to_next_provider() {
        let good_creds = Credentials::builder()
            .access_key_id("good")
            .access_key_secret("good")
            .build()
            .unwrap();

        let provider = StaticCredentialsProvider::new(good_creds);
        let chain = CredentialsChain::new(vec![Box::new(provider)]);

        let retrieved = chain.credentials().await.unwrap();
        assert_eq!(retrieved.access_key_id(), "good");
    }

    #[test]
    fn credentials_chain_exhausted_returns_error() {
        let chain = CredentialsChain::new(vec![]);
        let rt = tokio::runtime::Runtime::new().unwrap();
        let result = rt.block_on(chain.credentials());
        assert!(result.is_err());
    }

    #[test]
    fn credentials_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<Credentials>();
        assert_send_sync::<AccessKeyId>();
        assert_send_sync::<AccessKeySecret>();
        assert_send_sync::<StaticCredentialsProvider>();
        assert_send_sync::<EnvironmentCredentialsProvider>();
    }
}