Skip to main content

google_cloud_storage/
model_ext.rs

1// Copyright 2025 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Extends [model][crate::model] with types that improve type safety and/or
16//! ergonomics.
17
18use crate::error::KeyAes256Error;
19use base64::{Engine, prelude::BASE64_STANDARD};
20use sha2::{Digest, Sha256};
21
22mod open_object_request;
23pub use open_object_request::OpenObjectRequest;
24
25#[cfg(google_cloud_unstable_storage_bidi)]
26mod open_appendable_object_request;
27#[cfg(google_cloud_unstable_storage_bidi)]
28#[cfg_attr(docsrs, doc(cfg(feature = "unstable-stream")))]
29pub use open_appendable_object_request::OpenAppendableObjectRequest;
30
31#[cfg(google_cloud_unstable_storage_bidi)]
32mod reopen_appendable_object_request;
33#[cfg(google_cloud_unstable_storage_bidi)]
34#[cfg_attr(docsrs, doc(cfg(feature = "unstable-stream")))]
35pub use reopen_appendable_object_request::ReopenAppendableObjectRequest;
36
37#[cfg(google_cloud_unstable_storage_parallel_upload)]
38mod parallel_upload;
39#[cfg(google_cloud_unstable_storage_parallel_upload)]
40#[cfg_attr(docsrs, doc(cfg(google_cloud_unstable_storage_parallel_upload)))]
41pub use parallel_upload::{CreateObjectWriteSessionRequest, Segment};
42
43/// ObjectHighlights contains select metadata from a [crate::model::Object].
44#[derive(Clone, Debug, Default, PartialEq)]
45#[non_exhaustive]
46pub struct ObjectHighlights {
47    /// The content generation of this object. Used for object versioning.
48    pub generation: i64,
49
50    /// The version of the metadata for this generation of this
51    /// object. Used for preconditions and for detecting changes in metadata. A
52    /// metageneration number is only meaningful in the context of a particular
53    /// generation of a particular object.
54    pub metageneration: i64,
55
56    /// Content-Length of the object data in bytes, matching [RFC 7230 §3.3.2].
57    ///
58    /// [rfc 7230 §3.3.2]: https://tools.ietf.org/html/rfc7230#section-3.3.2
59    pub size: i64,
60
61    /// Content-Encoding of the object data, matching [RFC 7231 §3.1.2.2].
62    ///
63    /// [rfc 7231 §3.1.2.2]: https://tools.ietf.org/html/rfc7231#section-3.1.2.2
64    pub content_encoding: String,
65
66    /// Hashes for the data part of this object. The checksums of the complete
67    /// object regardless of data range. If the object is read in full, the
68    /// client should compute one of these checksums over the read object and
69    /// compare it against the value provided here.
70    pub checksums: std::option::Option<crate::model::ObjectChecksums>,
71
72    /// Storage class of the object.
73    pub storage_class: String,
74
75    /// Content-Language of the object data, matching [RFC 7231 §3.1.3.2].
76    ///
77    /// [rfc 7231 §3.1.3.2]: https://tools.ietf.org/html/rfc7231#section-3.1.3.2
78    pub content_language: String,
79
80    /// Content-Type of the object data, matching [RFC 7231 §3.1.1.5]. If an
81    /// object is stored without a Content-Type, it is served as
82    /// `application/octet-stream`.
83    ///
84    /// [rfc 7231 §3.1.1.5]: https://tools.ietf.org/html/rfc7231#section-3.1.1.5
85    pub content_type: String,
86
87    /// Content-Disposition of the object data, matching [RFC 6266].
88    ///
89    /// [rfc 6266]: https://tools.ietf.org/html/rfc6266
90    pub content_disposition: String,
91
92    /// The etag of the object.
93    pub etag: String,
94
95    /// User-provided metadata, in key/value pairs.
96    ///
97    /// Populated from `x-goog-meta-*` response headers; keys have the
98    /// `x-goog-meta-` prefix stripped and are lowercased by the server.
99    pub metadata: std::collections::HashMap<String, String>,
100}
101
102#[derive(Debug, Clone)]
103/// KeyAes256 represents an AES-256 encryption key used with the
104/// Customer-Supplied Encryption Keys (CSEK) feature.
105///
106/// This key must be exactly 32 bytes in length and should be provided in its
107/// raw (unencoded) byte format.
108///
109/// # Examples
110///
111/// Creating a `KeyAes256` instance from a valid byte slice:
112/// ```
113/// # use google_cloud_storage::{model_ext::KeyAes256, error::KeyAes256Error};
114/// let raw_key_bytes: [u8; 32] = [0x42; 32]; // Example 32-byte key
115/// let key_aes_256 = KeyAes256::new(&raw_key_bytes)?;
116/// # Ok::<(), KeyAes256Error>(())
117/// ```
118///
119/// Handling an error for an invalid key length:
120/// ```
121/// # use google_cloud_storage::{model_ext::KeyAes256, error::KeyAes256Error};
122/// let invalid_key_bytes: &[u8] = b"too_short_key"; // Less than 32 bytes
123/// let result = KeyAes256::new(invalid_key_bytes);
124///
125/// assert!(matches!(result, Err(KeyAes256Error::InvalidLength)));
126/// ```
127pub struct KeyAes256 {
128    key: [u8; 32],
129}
130
131impl KeyAes256 {
132    /// Attempts to create a new [KeyAes256].
133    ///
134    /// This conversion will succeed only if the input slice is exactly 32 bytes long.
135    ///
136    /// # Example
137    /// ```
138    /// # use google_cloud_storage::{model_ext::KeyAes256, error::KeyAes256Error};
139    /// let raw_key_bytes: [u8; 32] = [0x42; 32]; // Example 32-byte key
140    /// let key_aes_256 = KeyAes256::new(&raw_key_bytes)?;
141    /// # Ok::<(), KeyAes256Error>(())
142    /// ```
143    pub fn new(key: &[u8]) -> std::result::Result<Self, KeyAes256Error> {
144        match key.len() {
145            32 => Ok(Self {
146                key: key[..32].try_into().unwrap(),
147            }),
148            _ => Err(KeyAes256Error::InvalidLength),
149        }
150    }
151}
152
153impl std::convert::From<KeyAes256> for crate::model::CommonObjectRequestParams {
154    fn from(value: KeyAes256) -> Self {
155        // sha2::digest::generic_array::GenericArray::<T, N>::as_slice is deprecated.
156        // Our dependencies need to update to generic_array 1.x.
157        // See https://github.com/RustCrypto/traits/issues/2036 for more info.
158        #[allow(deprecated)]
159        crate::model::CommonObjectRequestParams::new()
160            .set_encryption_algorithm("AES256")
161            .set_encryption_key_bytes(value.key.to_vec())
162            .set_encryption_key_sha256_bytes(Sha256::digest(value.key).as_slice().to_owned())
163    }
164}
165
166impl std::fmt::Display for KeyAes256 {
167    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
168        write!(f, "{}", BASE64_STANDARD.encode(self.key))
169    }
170}
171
172/// Define read ranges for use with [ReadObject].
173///
174/// # Example: read the first 100 bytes of an object
175/// ```
176/// # use google_cloud_storage::client::Storage;
177/// # use google_cloud_storage::model_ext::ReadRange;
178/// # async fn sample(client: &Storage) -> anyhow::Result<()> {
179/// let response = client
180///     .read_object("projects/_/buckets/my-bucket", "my-object")
181///     .set_read_range(ReadRange::head(100))
182///     .send()
183///     .await?;
184/// println!("response details={response:?}");
185/// # Ok(()) }
186/// ```
187///
188/// Cloud Storage supports reading a portion of an object. These portions can
189/// be specified as offsets from the beginning of the object, offsets from the
190/// end of the object, or as ranges with a starting and ending bytes. This type
191/// defines a type-safe interface to represent only valid ranges.
192///
193/// [ReadObject]: crate::builder::storage::ReadObject
194#[derive(Clone, Debug, PartialEq)]
195pub struct ReadRange(pub(crate) RequestedRange);
196
197impl ReadRange {
198    /// Returns a range representing all the bytes in the object.
199    ///
200    /// # Example
201    /// ```
202    /// # use google_cloud_storage::client::Storage;
203    /// # use google_cloud_storage::model_ext::ReadRange;
204    /// # async fn sample(client: &Storage) -> anyhow::Result<()> {
205    /// let response = client
206    ///     .read_object("projects/_/buckets/my-bucket", "my-object")
207    ///     .set_read_range(ReadRange::all())
208    ///     .send()
209    ///     .await?;
210    /// println!("response details={response:?}");
211    /// # Ok(()) }
212    pub fn all() -> Self {
213        Self::offset(0)
214    }
215
216    /// Returns a range representing the bytes starting at `offset`.
217    ///
218    /// # Example
219    /// ```
220    /// # use google_cloud_storage::client::Storage;
221    /// # use google_cloud_storage::model_ext::ReadRange;
222    /// # async fn sample(client: &Storage) -> anyhow::Result<()> {
223    /// let response = client
224    ///     .read_object("projects/_/buckets/my-bucket", "my-object")
225    ///     .set_read_range(ReadRange::offset(1_000_000))
226    ///     .send()
227    ///     .await?;
228    /// println!("response details={response:?}");
229    /// # Ok(()) }
230    pub fn offset(offset: u64) -> Self {
231        Self(RequestedRange::Offset(offset))
232    }
233
234    /// Returns a range representing the last `count` bytes of the object.
235    ///
236    /// # Example
237    /// ```
238    /// # use google_cloud_storage::client::Storage;
239    /// # use google_cloud_storage::model_ext::ReadRange;
240    /// # async fn sample(client: &Storage) -> anyhow::Result<()> {
241    /// let response = client
242    ///     .read_object("projects/_/buckets/my-bucket", "my-object")
243    ///     .set_read_range(ReadRange::tail(100))
244    ///     .send()
245    ///     .await?;
246    /// println!("response details={response:?}");
247    /// # Ok(()) }
248    pub fn tail(count: u64) -> Self {
249        Self(RequestedRange::Tail(count))
250    }
251
252    /// Returns a range representing the first `count` bytes of the object.
253    ///
254    /// # Example
255    /// ```
256    /// # use google_cloud_storage::client::Storage;
257    /// # use google_cloud_storage::model_ext::ReadRange;
258    /// # async fn sample(client: &Storage) -> anyhow::Result<()> {
259    /// let response = client
260    ///     .read_object("projects/_/buckets/my-bucket", "my-object")
261    ///     .set_read_range(ReadRange::head(100))
262    ///     .send()
263    ///     .await?;
264    /// println!("response details={response:?}");
265    /// # Ok(()) }
266    pub fn head(count: u64) -> Self {
267        Self::segment(0, count)
268    }
269
270    /// Returns a range representing the `count` bytes starting at `offset`.
271    ///
272    /// # Example
273    /// ```
274    /// # use google_cloud_storage::client::Storage;
275    /// # use google_cloud_storage::model_ext::ReadRange;
276    /// # async fn sample(client: &Storage) -> anyhow::Result<()> {
277    /// let response = client
278    ///     .read_object("projects/_/buckets/my-bucket", "my-object")
279    ///     .set_read_range(ReadRange::segment(1_000_000, 1_000))
280    ///     .send()
281    ///     .await?;
282    /// println!("response details={response:?}");
283    /// # Ok(()) }
284    pub fn segment(offset: u64, count: u64) -> Self {
285        Self(RequestedRange::Segment {
286            offset,
287            limit: count,
288        })
289    }
290}
291
292impl crate::model::ReadObjectRequest {
293    pub(crate) fn with_range(&mut self, range: ReadRange) {
294        // The limit for GCS objects is (currently) 5TiB, and the gRPC protocol
295        // uses i64 for the offset and limit. Clamping the values to the
296        // `[0, i64::MAX]`` range is safe, in that it does not lose any
297        // functionality.
298        match range.0 {
299            RequestedRange::Offset(o) => {
300                self.read_offset = o.clamp(0, i64::MAX as u64) as i64;
301            }
302            RequestedRange::Tail(t) => {
303                // Yes, -i64::MAX is different from i64::MIN, but both are
304                // safe in this context.
305                self.read_offset = -(t.clamp(0, i64::MAX as u64) as i64);
306            }
307            RequestedRange::Segment { offset, limit } => {
308                self.read_offset = offset.clamp(0, i64::MAX as u64) as i64;
309                self.read_limit = limit.clamp(0, i64::MAX as u64) as i64;
310            }
311        }
312    }
313}
314
315#[derive(Clone, Copy, Debug, PartialEq)]
316pub(crate) enum RequestedRange {
317    Offset(u64),
318    Tail(u64),
319    Segment { offset: u64, limit: u64 },
320}
321
322/// Represents the parameters of a [WriteObject] request.
323///
324/// This type is only used in mocks of the `Storage` client.
325///
326/// [WriteObject]: crate::builder::storage::WriteObject
327#[derive(Debug, PartialEq)]
328#[non_exhaustive]
329#[allow(dead_code)]
330pub struct WriteObjectRequest {
331    /// The object attributes and pre-conditions for the write operation.
332    pub spec: crate::model::WriteObjectSpec,
333    /// Additional request parameters that are not part of the object attributes.
334    pub params: Option<crate::model::CommonObjectRequestParams>,
335    /// Whether to precompute checksums for unbuffered resumable uploads.
336    pub checksum_precomputation: bool,
337}
338
339#[cfg(test)]
340pub(crate) mod tests {
341    use super::*;
342    use crate::model::ReadObjectRequest;
343    use base64::{Engine, prelude::BASE64_STANDARD};
344    use test_case::test_case;
345
346    type Result = anyhow::Result<()>;
347
348    /// This is used by the request builder tests.
349    pub(crate) fn create_key_helper() -> (Vec<u8>, String, Vec<u8>, String) {
350        // Make a 32-byte key.
351        let key = vec![b'a'; 32];
352        let key_base64 = BASE64_STANDARD.encode(key.clone());
353
354        let key_sha256 = Sha256::digest(key.clone());
355        let key_sha256_base64 = BASE64_STANDARD.encode(key_sha256);
356        (key, key_base64, key_sha256.to_vec(), key_sha256_base64)
357    }
358
359    #[test]
360    // This tests converting to KeyAes256 from some different types
361    // that can get converted to &[u8].
362    fn test_key_aes_256() -> Result {
363        let v_slice: &[u8] = &[b'c'; 32];
364        KeyAes256::new(v_slice)?;
365
366        let v_vec: Vec<u8> = vec![b'a'; 32];
367        KeyAes256::new(&v_vec)?;
368
369        let v_array: [u8; 32] = [b'a'; 32];
370        KeyAes256::new(&v_array)?;
371
372        let v_bytes: bytes::Bytes = bytes::Bytes::copy_from_slice(&v_array);
373        KeyAes256::new(&v_bytes)?;
374
375        Ok(())
376    }
377
378    #[test_case(&[b'a'; 0]; "no bytes")]
379    #[test_case(&[b'a'; 1]; "not enough bytes")]
380    #[test_case(&[b'a'; 33]; "too many bytes")]
381    fn test_key_aes_256_err(input: &[u8]) {
382        KeyAes256::new(input).unwrap_err();
383    }
384
385    #[test]
386    fn test_key_aes_256_to_control_model_object() -> Result {
387        let (key, _, key_sha256, _) = create_key_helper();
388        let key_aes_256 = KeyAes256::new(&key)?;
389        let params = crate::model::CommonObjectRequestParams::from(key_aes_256);
390        assert_eq!(params.encryption_algorithm, "AES256");
391        assert_eq!(params.encryption_key_bytes, key);
392        assert_eq!(params.encryption_key_sha256_bytes, key_sha256);
393        Ok(())
394    }
395
396    #[test_case(100, 100)]
397    #[test_case(u64::MAX, i64::MAX)]
398    #[test_case(0, 0)]
399    fn apply_offset(input: u64, want: i64) {
400        let range = ReadRange::offset(input);
401        let mut request = ReadObjectRequest::new();
402        request.with_range(range);
403        assert_eq!(request.read_offset, want);
404        assert_eq!(request.read_limit, 0);
405    }
406
407    #[test_case(100, 100)]
408    #[test_case(u64::MAX, i64::MAX)]
409    #[test_case(0, 0)]
410    fn apply_head(input: u64, want: i64) {
411        let range = ReadRange::head(input);
412        let mut request = ReadObjectRequest::new();
413        request.with_range(range);
414        assert_eq!(request.read_offset, 0);
415        assert_eq!(request.read_limit, want);
416    }
417
418    #[test_case(100, -100)]
419    #[test_case(u64::MAX, -i64::MAX)]
420    #[test_case(0, 0)]
421    fn apply_tail(input: u64, want: i64) {
422        let range = ReadRange::tail(input);
423        let mut request = ReadObjectRequest::new();
424        request.with_range(range);
425        assert_eq!(request.read_offset, want);
426        assert_eq!(request.read_limit, 0);
427    }
428
429    #[test_case(100, 100)]
430    #[test_case(u64::MAX, i64::MAX)]
431    #[test_case(0, 0)]
432    fn apply_segment_offset(input: u64, want: i64) {
433        let range = ReadRange::segment(input, 2000);
434        let mut request = ReadObjectRequest::new();
435        request.with_range(range);
436        assert_eq!(request.read_offset, want);
437        assert_eq!(request.read_limit, 2000);
438    }
439
440    #[test_case(100, 100)]
441    #[test_case(u64::MAX, i64::MAX)]
442    #[test_case(0, 0)]
443    fn apply_segment_limit(input: u64, want: i64) {
444        let range = ReadRange::segment(1000, input);
445        let mut request = ReadObjectRequest::new();
446        request.with_range(range);
447        assert_eq!(request.read_offset, 1000);
448        assert_eq!(request.read_limit, want);
449    }
450
451    #[test]
452    fn test_key_aes_256_display() -> Result {
453        let (key, key_base64, _, _) = create_key_helper();
454        let key_aes_256 = KeyAes256::new(&key)?;
455        assert_eq!(key_aes_256.to_string(), key_base64);
456        Ok(())
457    }
458}