object_store 0.14.0

A generic object store interface for uniformly interacting with AWS S3, Google Cloud Storage, Azure Blob Storage and local files.
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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

use crate::Result;

/// Algorithm for computing digests
#[derive(Debug, Ord, PartialOrd, Eq, PartialEq)]
#[non_exhaustive]
pub enum DigestAlgorithm {
    /// SHA-256
    Sha256,
}

/// Algorithm for signing payloads
#[derive(Debug, Ord, PartialOrd, Eq, PartialEq)]
#[non_exhaustive]
pub enum SigningAlgorithm {
    /// RSASSA-PKCS1-v1_5 using SHA-256
    RS256,
}

/// Provides cryptographic primitives
pub trait CryptoProvider: std::fmt::Debug + Send + Sync {
    /// Compute a digest
    fn digest(&self, algorithm: DigestAlgorithm) -> Result<Box<dyn DigestContext>>;

    /// Compute an HMAC with the provided `secret`
    fn hmac(&self, algorithm: DigestAlgorithm, secret: &[u8]) -> Result<Box<dyn HmacContext>>;

    /// Sign a payload with the provided PEM-encoded secret
    fn sign(&self, algorithm: SigningAlgorithm, pem: &[u8]) -> Result<Box<dyn Signer>>;
}

/// Incrementally compute a digest, see [`CryptoProvider::digest`]
pub trait DigestContext: Send {
    /// Updates the digest with all the data in data.
    ///
    /// It is implementation-defined behaviour to call this after calling [`Self::finish`]
    fn update(&mut self, data: &[u8]);

    /// Finalizes the digest calculation and returns the digest value.
    ///
    /// It is implementation-defined behaviour to call this after calling [`Self::finish`]
    fn finish(&mut self) -> Result<&[u8]>;
}

/// Incrementally compute a HMAC, see [`CryptoProvider::hmac`]
pub trait HmacContext: Send {
    /// Updates the HMAC with all the data in data.
    ///
    /// It is implementation-defined behaviour to call this after calling [`Self::finish`]
    fn update(&mut self, data: &[u8]);

    /// Finalizes the HMAC calculation and returns the HMAC value.
    ///
    /// It is implementation-defined behaviour to call this after calling [`Self::finish`]
    fn finish(&mut self) -> Result<&[u8]>;
}

/// Sign a payload, see [`CryptoProvider::sign`]
pub trait Signer: Send + Sync {
    /// Sign the provided payload
    fn sign(&self, string_to_sign: &[u8]) -> Result<Vec<u8>>;
}

/// Attempts to find a [`CryptoProvider`]
///
/// If `custom` is `Some(v)` returns `v` otherwise returns the compile-time default
///
/// If both `ring` and `aws-lc-rs` are enabled, the `aws-lc-rs` provider is used.
pub(crate) fn crypto_provider(custom: Option<&dyn CryptoProvider>) -> Result<&dyn CryptoProvider> {
    if let Some(x) = custom {
        return Ok(x);
    }

    #[cfg(feature = "aws-lc-rs")]
    {
        Ok(&aws_lc_rs::PROVIDER)
    }

    #[cfg(all(feature = "ring", not(feature = "aws-lc-rs")))]
    {
        Ok(&ring::PROVIDER)
    }

    #[cfg(not(any(feature = "ring", feature = "aws-lc-rs")))]
    {
        Err(crate::Error::NotSupported {
            source: "Must enable aws-lc-rs, ring, or specify custom CryptoProvider"
                .to_string()
                .into(),
        })
    }
}

#[cfg(all(feature = "ring", not(feature = "aws-lc-rs")))]
pub(crate) mod ring {
    use super::*;
    use ::ring::{digest, hmac, rand, signature};
    use thiserror::Error;

    #[derive(Debug, Error)]
    pub(crate) enum RingError {
        #[error("No RSA key found in pem file")]
        MissingKey,

        #[error("Invalid RSA key: {}", source)]
        InvalidKey {
            #[from]
            source: ::ring::error::KeyRejected,
        },

        #[error("Error reading pem file: {}", source)]
        ReadPem {
            source: rustls_pki_types::pem::Error,
        },

        #[error("Error signing: {}", source)]
        Sign { source: ::ring::error::Unspecified },
    }

    impl From<RingError> for crate::Error {
        fn from(value: RingError) -> Self {
            Self::Generic {
                store: "RingCryptoProvider",
                source: Box::new(value),
            }
        }
    }

    pub(crate) const PROVIDER: RingCryptoProvider = RingCryptoProvider { _private: () };

    #[derive(Debug, Default)]
    pub(crate) struct RingCryptoProvider {
        _private: (),
    }

    impl CryptoProvider for RingCryptoProvider {
        fn digest(&self, algorithm: DigestAlgorithm) -> Result<Box<dyn DigestContext>> {
            let algorithm = match algorithm {
                DigestAlgorithm::Sha256 => &digest::SHA256,
            };
            let ctx = digest::Context::new(algorithm);
            Ok(Box::new(RingDigestContext {
                ctx: Some(ctx),
                out: None,
            }))
        }

        fn hmac(&self, algorithm: DigestAlgorithm, secret: &[u8]) -> Result<Box<dyn HmacContext>> {
            let algorithm = match algorithm {
                DigestAlgorithm::Sha256 => hmac::HMAC_SHA256,
            };
            let ctx = hmac::Context::with_key(&hmac::Key::new(algorithm, secret));
            Ok(Box::new(RingHmacContext {
                ctx: Some(ctx),
                out: None,
            }))
        }

        fn sign(&self, algorithm: SigningAlgorithm, pem: &[u8]) -> Result<Box<dyn Signer>> {
            match algorithm {
                SigningAlgorithm::RS256 => Ok(Box::new(RsaKeyPair::from_pem(pem)?)),
            }
        }
    }

    struct RingDigestContext {
        ctx: Option<digest::Context>,
        out: Option<digest::Digest>,
    }

    impl DigestContext for RingDigestContext {
        fn update(&mut self, data: &[u8]) {
            self.ctx.as_mut().unwrap().update(data);
        }

        fn finish(&mut self) -> Result<&[u8]> {
            let digest = self.ctx.take().unwrap().finish();
            Ok(digest::Digest::as_ref(self.out.insert(digest)))
        }
    }

    struct RingHmacContext {
        ctx: Option<hmac::Context>,
        out: Option<hmac::Tag>,
    }

    impl HmacContext for RingHmacContext {
        fn update(&mut self, data: &[u8]) {
            self.ctx.as_mut().unwrap().update(data);
        }

        fn finish(&mut self) -> Result<&[u8]> {
            let tag = self.ctx.take().unwrap().sign();
            Ok(hmac::Tag::as_ref(self.out.insert(tag)))
        }
    }

    /// A private RSA key for a service account
    #[derive(Debug)]
    pub(crate) struct RsaKeyPair(signature::RsaKeyPair);

    impl RsaKeyPair {
        /// Parses a pem-encoded RSA key
        pub(crate) fn from_pem(encoded: &[u8]) -> Result<Self, RingError> {
            use rustls_pki_types::PrivateKeyDer;
            use rustls_pki_types::pem::PemObject;

            match PrivateKeyDer::from_pem_slice(encoded) {
                Ok(PrivateKeyDer::Pkcs8(key)) => Self::from_pkcs8(key.secret_pkcs8_der()),
                Ok(PrivateKeyDer::Pkcs1(key)) => Self::from_der(key.secret_pkcs1_der()),
                Ok(_) => Err(RingError::MissingKey),
                Err(source) => Err(RingError::ReadPem { source }),
            }
        }

        /// Parses an unencrypted PKCS#8-encoded RSA private key.
        pub(crate) fn from_pkcs8(key: &[u8]) -> Result<Self, RingError> {
            Ok(Self(signature::RsaKeyPair::from_pkcs8(key)?))
        }

        /// Parses an unencrypted PKCS#8-encoded RSA private key.
        pub(crate) fn from_der(key: &[u8]) -> Result<Self, RingError> {
            Ok(Self(signature::RsaKeyPair::from_der(key)?))
        }
    }

    impl Signer for RsaKeyPair {
        fn sign(&self, string_to_sign: &[u8]) -> Result<Vec<u8>> {
            let mut signature = vec![0; self.0.public().modulus_len()];
            self.0
                .sign(
                    &signature::RSA_PKCS1_SHA256,
                    &rand::SystemRandom::new(),
                    string_to_sign,
                    &mut signature,
                )
                .map_err(|source| RingError::Sign { source })?;

            Ok(signature)
        }
    }
}

#[cfg(feature = "aws-lc-rs")]
pub(crate) mod aws_lc_rs {
    use super::*;
    use ::aws_lc_rs::{digest, hmac, rand, signature};
    use thiserror::Error;

    #[derive(Debug, Error)]
    pub(crate) enum AwsLcError {
        #[error("No RSA key found in pem file")]
        MissingKey,

        #[error("Invalid RSA key: {}", source)]
        InvalidKey {
            #[from]
            source: ::aws_lc_rs::error::KeyRejected,
        },

        #[error("Error reading pem file: {}", source)]
        ReadPem {
            source: rustls_pki_types::pem::Error,
        },

        #[error("Error signing: {}", source)]
        Sign {
            source: ::aws_lc_rs::error::Unspecified,
        },
    }

    impl From<AwsLcError> for crate::Error {
        fn from(value: AwsLcError) -> Self {
            Self::Generic {
                store: "AwsLcCryptoProvider",
                source: Box::new(value),
            }
        }
    }

    pub(crate) const PROVIDER: AwsLcCryptoProvider = AwsLcCryptoProvider { _private: () };

    #[derive(Debug, Default)]
    pub(crate) struct AwsLcCryptoProvider {
        _private: (),
    }

    impl CryptoProvider for AwsLcCryptoProvider {
        fn digest(&self, algorithm: DigestAlgorithm) -> Result<Box<dyn DigestContext>> {
            let algorithm = match algorithm {
                DigestAlgorithm::Sha256 => &digest::SHA256,
            };
            let ctx = digest::Context::new(algorithm);
            Ok(Box::new(AwsLcDigestContext {
                ctx: Some(ctx),
                out: None,
            }))
        }

        fn hmac(&self, algorithm: DigestAlgorithm, secret: &[u8]) -> Result<Box<dyn HmacContext>> {
            let algorithm = match algorithm {
                DigestAlgorithm::Sha256 => hmac::HMAC_SHA256,
            };
            let ctx = hmac::Context::with_key(&hmac::Key::new(algorithm, secret));
            Ok(Box::new(AwsLcHmacContext {
                ctx: Some(ctx),
                out: None,
            }))
        }

        fn sign(&self, algorithm: SigningAlgorithm, pem: &[u8]) -> Result<Box<dyn Signer>> {
            match algorithm {
                SigningAlgorithm::RS256 => Ok(Box::new(RsaKeyPair::from_pem(pem)?)),
            }
        }
    }

    struct AwsLcDigestContext {
        ctx: Option<digest::Context>,
        out: Option<digest::Digest>,
    }

    impl DigestContext for AwsLcDigestContext {
        fn update(&mut self, data: &[u8]) {
            self.ctx.as_mut().unwrap().update(data);
        }

        fn finish(&mut self) -> Result<&[u8]> {
            let digest = self.ctx.take().unwrap().finish();
            Ok(digest::Digest::as_ref(self.out.insert(digest)))
        }
    }

    struct AwsLcHmacContext {
        ctx: Option<hmac::Context>,
        out: Option<hmac::Tag>,
    }

    impl HmacContext for AwsLcHmacContext {
        fn update(&mut self, data: &[u8]) {
            self.ctx.as_mut().unwrap().update(data);
        }

        fn finish(&mut self) -> Result<&[u8]> {
            let tag = self.ctx.take().unwrap().sign();
            Ok(hmac::Tag::as_ref(self.out.insert(tag)))
        }
    }

    /// A private RSA key for a service account
    #[derive(Debug)]
    pub(crate) struct RsaKeyPair(signature::RsaKeyPair);

    impl RsaKeyPair {
        /// Parses a pem-encoded RSA key
        pub(crate) fn from_pem(encoded: &[u8]) -> Result<Self, AwsLcError> {
            use rustls_pki_types::PrivateKeyDer;
            use rustls_pki_types::pem::PemObject;

            match PrivateKeyDer::from_pem_slice(encoded) {
                Ok(PrivateKeyDer::Pkcs8(key)) => Self::from_pkcs8(key.secret_pkcs8_der()),
                Ok(PrivateKeyDer::Pkcs1(key)) => Self::from_der(key.secret_pkcs1_der()),
                Ok(_) => Err(AwsLcError::MissingKey),
                Err(source) => Err(AwsLcError::ReadPem { source }),
            }
        }

        /// Parses an unencrypted PKCS#8-encoded RSA private key.
        pub(crate) fn from_pkcs8(key: &[u8]) -> Result<Self, AwsLcError> {
            Ok(Self(signature::RsaKeyPair::from_pkcs8(key)?))
        }

        /// Parses an unencrypted PKCS#8-encoded RSA private key.
        pub(crate) fn from_der(key: &[u8]) -> Result<Self, AwsLcError> {
            Ok(Self(signature::RsaKeyPair::from_der(key)?))
        }
    }

    impl Signer for RsaKeyPair {
        fn sign(&self, string_to_sign: &[u8]) -> Result<Vec<u8>> {
            let mut signature = vec![0; self.0.public_modulus_len()];
            self.0
                .sign(
                    &signature::RSA_PKCS1_SHA256,
                    &rand::SystemRandom::new(),
                    string_to_sign,
                    &mut signature,
                )
                .map_err(|source| AwsLcError::Sign { source })?;

            Ok(signature)
        }
    }
}