Skip to main content

bitwarden_send/
access.rs

1use bitwarden_api_api::{
2    apis::ApiClient,
3    models::{self, SendEncryptionType},
4};
5use bitwarden_core::{ApiError, key_management::KeySlotIds};
6use bitwarden_crypto::{
7    CryptoError, EncString, KeyDecryptable as _, KeyStore, SymmetricCryptoKey, derive_shareable_key,
8};
9use bitwarden_encoding::{B64, B64Url};
10use bitwarden_error::bitwarden_error;
11use bitwarden_vault::{CipherId, CipherView};
12use chrono::{DateTime, Utc};
13use serde::{Deserialize, Serialize};
14use thiserror::Error;
15#[cfg(feature = "wasm")]
16use wasm_bindgen::prelude::*;
17use zeroize::Zeroizing;
18
19use crate::{
20    SendParseError, SendType,
21    send::{SEND_ITERATIONS, SendItemMetadataView},
22    send_client::SendClient,
23};
24
25/// Length in bytes of the raw Send key carried in a Send URL fragment. `pub(crate)` so
26/// `SendView::encrypt_composite` (`send.rs`) can generate keys of exactly this length,
27/// enforcing the relationship at compile time instead of relying on a test to catch drift.
28pub(crate) const SEND_KEY_LEN: usize = 16;
29
30// ===== Public output types (returned to callers) =====
31
32/// View of a send's accessible content, returned after a successful send access call.
33/// Name, text, file, and item fields are encrypted and must be decrypted client-side
34/// using the key derived from the URL fragment.
35#[derive(Debug, Serialize, Deserialize)]
36#[serde(rename_all = "camelCase")]
37#[bitwarden_ffi::wasm_record]
38pub struct SendAccessResponse {
39    /// The send access ID
40    pub id: Option<String>,
41    /// The send type.
42    #[serde(rename = "type")]
43    pub type_: Option<SendType>,
44    /// Encrypted send name
45    pub name: Option<String>,
46    /// Text content (if type is Text)
47    pub text: Option<SendAccessTextResponse>,
48    /// File metadata (if type is File)
49    pub file: Option<SendAccessFileResponse>,
50    /// Item metadata (if type is Item)
51    pub data: Option<SendAccessItemResponse>,
52    /// When the send expires.
53    pub expiration_date: Option<DateTime<Utc>>,
54    /// The creator's identifier (email), if not hidden
55    pub creator_identifier: Option<String>,
56}
57
58/// Encrypted text content of a text send.
59#[derive(Debug, Serialize, Deserialize)]
60#[serde(rename_all = "camelCase")]
61#[bitwarden_ffi::wasm_record]
62pub struct SendAccessTextResponse {
63    /// Encrypted text content
64    pub text: Option<String>,
65    /// Whether to hide the text by default
66    pub hidden: bool,
67}
68
69/// Encrypted file metadata of a file send.
70#[derive(Debug, Serialize, Deserialize)]
71#[serde(rename_all = "camelCase")]
72#[bitwarden_ffi::wasm_record]
73pub struct SendAccessFileResponse {
74    /// The file ID
75    pub id: Option<String>,
76    /// Encrypted file name
77    pub file_name: Option<String>,
78    /// File size in bytes as a string
79    pub size: Option<String>,
80    /// Human-readable size (e.g. "4.2 KB")
81    pub size_name: Option<String>,
82}
83
84/// Encrypted item metadata of an item send.
85#[derive(Debug, Serialize, Deserialize)]
86#[serde(rename_all = "camelCase")]
87#[bitwarden_ffi::wasm_record]
88pub struct SendAccessItemResponse {
89    /// The version of encryption used to encrypt the item data
90    pub encryption_version: Option<SendEncryptionType>,
91    /// The encrypted item data
92    pub data: Option<String>,
93    /// Partially encrypted item metadata
94    pub metadata: SendAccessItemMetadataResponse,
95}
96
97#[derive(Debug, Serialize, Deserialize)]
98#[serde(rename_all = "camelCase")]
99#[bitwarden_ffi::wasm_record]
100pub struct SendAccessItemMetadataResponse {
101    /// Id of the vault item being sent
102    pub item_id: CipherId,
103    /// The encrypted name of the folder the vault item being sent belongs to
104    pub folder_name: Option<String>,
105    /// The encrypted names of the collections the vault item being sent belongs to
106    pub collection_names: Option<Vec<String>>,
107    /// The name of the organization the vault item being sent belongs to. This is stored
108    /// unencrypted unlike other metadata.
109    pub organization_name: Option<String>,
110    /// The date the vault item being sent was created
111    pub creation_date: Option<DateTime<Utc>>,
112    /// The date the vault item being sent was last edited
113    pub revision_date: Option<DateTime<Utc>>,
114}
115
116/// File download URL data returned from a send file access call.
117#[derive(Debug, Serialize, Deserialize)]
118#[serde(rename_all = "camelCase")]
119#[bitwarden_ffi::wasm_record]
120pub struct SendFileDownloadData {
121    /// The file ID
122    pub id: Option<String>,
123    /// The pre-signed download URL
124    pub url: Option<String>,
125}
126
127// ===== Decrypted views of an anonymous send access =====
128
129/// Plaintext view of a [`SendAccessResponse`], produced by
130/// [`SendAccessKey::decrypt_response`].
131///
132/// Mirrors the legacy CLI's `SendAccessResponse` output shape (`apps/cli`) so that a
133/// JSON dump of a received send stays recognizable to existing scripts, with two additions:
134/// `expirationDate` and `creatorIdentifier` are already present on the raw
135/// `SendAccessResponse` the server returns, but the legacy CLI's output shape drops them.
136///
137/// `text`/`file` are kept as independent `Option`s rather than collapsed into an enum with
138/// associated data: `type_` is `Option<SendType>` on the wire and an unrecognized or absent
139/// discriminant must still round-trip (both the legacy CLI and `bw receive` fall back to
140/// dumping whatever the server returned), which a total enum could not represent.
141#[derive(Debug, Serialize, Deserialize, PartialEq)]
142#[serde(rename_all = "camelCase")]
143#[bitwarden_ffi::wasm_record]
144pub struct SendAccessView {
145    /// The send access ID
146    pub id: Option<String>,
147    /// The send type.
148    #[serde(rename = "type")]
149    pub type_: Option<SendType>,
150    /// The decrypted send name. `None` when the send has no name, which is not an error —
151    /// a nameless text send still has printable content.
152    pub name: Option<String>,
153    /// Decrypted text content (if type is Text)
154    pub text: Option<SendAccessTextView>,
155    /// Decrypted file metadata (if type is File)
156    pub file: Option<SendAccessFileView>,
157    /// Decrypted item content (if type is Item)
158    pub data: Option<SendAccessItemView>,
159    /// When the send expires.
160    pub expiration_date: Option<DateTime<Utc>>,
161    /// The creator's identifier (email), if not hidden
162    pub creator_identifier: Option<String>,
163}
164
165/// Decrypted text content of a text send.
166#[derive(Debug, Serialize, Deserialize, PartialEq)]
167#[serde(rename_all = "camelCase")]
168#[bitwarden_ffi::wasm_record]
169pub struct SendAccessTextView {
170    /// The decrypted text content
171    pub text: Option<String>,
172    /// Whether to hide the text by default
173    pub hidden: bool,
174}
175
176/// Decrypted file metadata of a file send.
177#[derive(Debug, Serialize, Deserialize, PartialEq)]
178#[serde(rename_all = "camelCase")]
179#[bitwarden_ffi::wasm_record]
180pub struct SendAccessFileView {
181    /// The file ID
182    pub id: Option<String>,
183    /// The decrypted file name
184    pub file_name: Option<String>,
185    /// File size in bytes as a string
186    pub size: Option<String>,
187    /// Human-readable size (e.g. "4.2 KB")
188    pub size_name: Option<String>,
189}
190
191/// Decrypted item metadata of an item send.
192#[derive(Debug, Serialize, Deserialize, PartialEq)]
193#[serde(rename_all = "camelCase")]
194#[bitwarden_ffi::wasm_record]
195pub struct SendAccessItemView {
196    /// The decrypted Cipher data
197    pub data: Option<CipherView>,
198    /// Unencrypted metadata that travels alongside the item data
199    pub metadata: SendItemMetadataView,
200}
201
202// ===== Error types =====
203
204/// Error returned when the key from a send URL fragment cannot be turned into a
205/// [`SendAccessKey`]. Deliberately carries no key material.
206#[bitwarden_error(flat)]
207#[derive(Debug, Error)]
208pub enum SendAccessKeyError {
209    /// The fragment key was not valid URL-safe base64.
210    #[error("The send key is not valid url-safe base64")]
211    InvalidEncoding,
212    /// The decoded key was not `SEND_KEY_LEN` (16) bytes long.
213    #[error("The send key must be {SEND_KEY_LEN} bytes")]
214    InvalidLength,
215}
216
217/// Error returned when decrypting an anonymous send access response or file blob fails.
218/// Wraps [`CryptoError`], which never embeds plaintext or key material in its messages.
219#[bitwarden_error(flat)]
220#[derive(Debug, Error)]
221pub enum SendAccessDecryptError {
222    /// The ciphertext was malformed, or the key derived from the URL fragment does not
223    /// decrypt it (wrong key, or a tampered response).
224    #[error(transparent)]
225    Crypto(#[from] CryptoError),
226    /// The key could not be derived from the URL fragment
227    #[error(transparent)]
228    Key(#[from] SendAccessKeyError),
229}
230
231// ===== Anonymous access key =====
232
233/// Symmetric key material for an anonymous Send access, derived entirely from the URL
234/// fragment — no account key store or logged-in user involved. This is the only Send flow
235/// whose key doesn't come from the user's key store, hence a standalone type rather than a
236/// [`bitwarden_crypto::KeyStoreContext`] slot.
237///
238/// The key is opaque by design: callers need to *use* it three ways (hash a password,
239/// decrypt a response, decrypt a downloaded blob) but never need to *see* it.
240pub struct SendAccessKey {
241    /// The raw fragment key, exactly as decoded from the URL — not run through the KDF that
242    /// derives [`Self::key`] below. Retained because the send password hash is salted with
243    /// these raw bytes, not with the derived key.
244    secret: Zeroizing<[u8; SEND_KEY_LEN]>,
245    /// The send's actual symmetric key, derived from `secret` via `derive_shareable_key`.
246    /// This is what encrypts the send's fields and file blob.
247    key: SymmetricCryptoKey,
248}
249
250impl SendAccessKey {
251    /// Parse the URL-safe-base64 key from a Send URL fragment and stretch it into the
252    /// send's symmetric key. Equivalent to the legacy clients' `Utils.fromUrlB64ToArray`
253    /// followed by `KeyService.makeSendKey`.
254    ///
255    /// The `"send"`/`Some("send")` name/info pair must stay in lockstep with
256    /// `Send::derive_shareable_key` — that is what `bw send create` used to encrypt the send,
257    /// so any divergence makes every send undecryptable through this path. The round-trip
258    /// test below pins the two together.
259    pub fn from_url_b64(key_b64: &str) -> Result<Self, SendAccessKeyError> {
260        // Wrap the decoded bytes in `Zeroizing` before any length check so a wrong-length
261        // key is still scrubbed rather than left in freed memory.
262        let decoded = Zeroizing::new(
263            B64Url::try_from(key_b64)
264                .map_err(|_| SendAccessKeyError::InvalidEncoding)?
265                .into_bytes(),
266        );
267        if decoded.len() != SEND_KEY_LEN {
268            return Err(SendAccessKeyError::InvalidLength);
269        }
270        let mut secret = Zeroizing::new([0u8; SEND_KEY_LEN]);
271        secret.copy_from_slice(&decoded);
272
273        let key = SymmetricCryptoKey::Aes256CbcHmacKey(derive_shareable_key(
274            secret.clone(),
275            "send",
276            Some("send"),
277        ));
278
279        Ok(Self { secret, key })
280    }
281
282    /// PBKDF2-HMAC-SHA256 over `password`, `SEND_ITERATIONS` (100,000) rounds, salted with the
283    /// raw URL key — the `password_hash_b64` credential the send-access token grant expects.
284    ///
285    /// Identical recipe to `SendAuthType::auth_data`, which is what `bw send create --password`
286    /// stored on the server. A pinning test asserts the two agree; if they ever diverge, every
287    /// password-protected receive fails with an opaque server-side rejection.
288    pub fn hash_password_b64(&self, password: &str) -> String {
289        let hashed =
290            bitwarden_crypto::pbkdf2(password.as_bytes(), self.secret.as_slice(), SEND_ITERATIONS);
291        B64::from(hashed.as_slice()).to_string()
292    }
293
294    /// Decrypt a [`SendAccessResponse`]'s encrypted fields into a plaintext
295    /// [`SendAccessView`].
296    pub fn decrypt_response(
297        &self,
298        response: SendAccessResponse,
299    ) -> Result<SendAccessView, SendAccessDecryptError> {
300        let text = match response.text {
301            Some(t) => Some(SendAccessTextView {
302                text: self.decrypt_optional(t.text)?,
303                hidden: t.hidden,
304            }),
305            None => None,
306        };
307        let file = match response.file {
308            Some(f) => Some(SendAccessFileView {
309                id: f.id,
310                file_name: self.decrypt_optional(f.file_name)?,
311                size: f.size,
312                size_name: f.size_name,
313            }),
314            None => None,
315        };
316        let data = match response.data {
317            Some(d) => {
318                let key_store: KeyStore<KeySlotIds> = KeyStore::default();
319                let mut ctx = key_store.context_mut();
320                let key = ctx.add_local_symmetric_key(self.key.clone());
321                let Some(data) = d.data else {
322                    return Err(SendAccessDecryptError::Crypto(CryptoError::MissingField(
323                        "data",
324                    )));
325                };
326                let mut cipher_view = CipherView::unseal_blob_for_item_sends(&data, &mut ctx, key)?;
327                // The blob holds no id or dates; restore them from the metadata.
328                cipher_view.id = Some(d.metadata.item_id);
329                if let Some(creation_date) = d.metadata.creation_date {
330                    cipher_view.creation_date = creation_date;
331                }
332                if let Some(revision_date) = d.metadata.revision_date {
333                    cipher_view.revision_date = revision_date;
334                }
335                Some(SendAccessItemView {
336                    data: Some(cipher_view),
337                    metadata: SendItemMetadataView {
338                        item_id: d.metadata.item_id,
339                        folder_name: self.decrypt_optional(d.metadata.folder_name)?,
340                        collection_names: d
341                            .metadata
342                            .collection_names
343                            .as_ref()
344                            .map(|cols| {
345                                cols.iter()
346                                    .map(|c| self.decrypt_required(c.to_string()))
347                                    .collect()
348                            })
349                            .transpose()?,
350                        organization_name: d.metadata.organization_name,
351                        creation_date: d.metadata.creation_date,
352                        revision_date: d.metadata.revision_date,
353                    },
354                })
355            }
356            None => None,
357        };
358
359        Ok(SendAccessView {
360            id: response.id,
361            type_: response.type_,
362            name: self.decrypt_optional(response.name)?,
363            text,
364            file,
365            data,
366            expiration_date: response.expiration_date,
367            creator_identifier: response.creator_identifier,
368        })
369    }
370
371    /// Decrypt a downloaded file-send blob. The blob is a single whole-buffer [`EncString`]
372    /// (not the chunked attachment format), matching the legacy clients'
373    /// `EncArrayBuffer.fromResponse` + `EncryptService.decryptFileData`.
374    pub fn decrypt_file_buffer(&self, buffer: &[u8]) -> Result<Vec<u8>, SendAccessDecryptError> {
375        Ok(EncString::from_buffer(buffer)?.decrypt_with_key(&self.key)?)
376    }
377
378    /// Parse and decrypt an optional wire-format [`EncString`] field. Absent fields stay
379    /// absent — the caller decides whether a missing field is fatal.
380    fn decrypt_optional(
381        &self,
382        value: Option<String>,
383    ) -> Result<Option<String>, SendAccessDecryptError> {
384        match value {
385            Some(s) => Ok(Some(s.parse::<EncString>()?.decrypt_with_key(&self.key)?)),
386            None => Ok(None),
387        }
388    }
389
390    /// Parse and decrypt a required wire-format [`EncString`] field.
391    fn decrypt_required(&self, value: String) -> Result<String, SendAccessDecryptError> {
392        Ok(EncString::parse_strict(value.as_str())?.decrypt_with_key(&self.key)?)
393    }
394}
395
396/// Error returned when accessing a send fails.
397#[bitwarden_error(flat)]
398#[derive(Debug, Error)]
399pub enum AccessSendError {
400    /// The send does not exist, has expired, or has been deleted (the server answered 404).
401    #[error("The send was not found")]
402    NotFound,
403    /// An API or network error occurred.
404    #[error(transparent)]
405    Api(ApiError),
406    /// The response body could not be parsed into a [`SendAccessResponse`] — either a
407    /// required field was missing, the send type was an unrecognized value, or a date
408    /// field was malformed.
409    #[error(transparent)]
410    Parse(#[from] SendParseError),
411}
412
413/// Error returned when getting send file download data fails.
414#[bitwarden_error(flat)]
415#[derive(Debug, Error)]
416pub enum GetFileDownloadDataError {
417    /// The send or its file does not exist, has expired, or has been deleted (the server
418    /// answered 404).
419    #[error("The send file was not found")]
420    NotFound,
421    /// An API or network error occurred.
422    #[error(transparent)]
423    Api(ApiError),
424}
425
426fn is_not_found(error: &ApiError) -> bool {
427    matches!(error, ApiError::Response(r) if r.status == reqwest::StatusCode::NOT_FOUND)
428}
429
430impl From<ApiError> for AccessSendError {
431    fn from(error: ApiError) -> Self {
432        if is_not_found(&error) {
433            Self::NotFound
434        } else {
435            Self::Api(error)
436        }
437    }
438}
439
440impl From<ApiError> for GetFileDownloadDataError {
441    fn from(error: ApiError) -> Self {
442        if is_not_found(&error) {
443            Self::NotFound
444        } else {
445            Self::Api(error)
446        }
447    }
448}
449
450// ===== HTTP request functions =====
451
452pub(crate) async fn access_send(
453    api_client: &ApiClient,
454    access_token: &str,
455) -> Result<SendAccessResponse, AccessSendError> {
456    let resp = api_client
457        .sends_api()
458        .access_using_auth(access_token)
459        .await?;
460    Ok(resp.try_into()?)
461}
462
463pub(crate) async fn get_file_download_data(
464    api_client: &ApiClient,
465    file_id: &str,
466    access_token: &str,
467) -> Result<SendFileDownloadData, GetFileDownloadDataError> {
468    let resp = api_client
469        .sends_api()
470        .get_send_file_download_data_using_auth(file_id, access_token)
471        .await?;
472    Ok(resp.into())
473}
474
475// ===== Conversions from API response models =====
476
477impl TryFrom<models::SendAccessResponseModel> for SendAccessResponse {
478    type Error = SendParseError;
479
480    fn try_from(r: models::SendAccessResponseModel) -> Result<Self, Self::Error> {
481        Ok(SendAccessResponse {
482            id: r.id,
483            type_: r.r#type.map(SendType::try_from).transpose()?,
484            name: r.name,
485            text: r.text.map(|t| SendAccessTextResponse {
486                text: t.text,
487                hidden: t.hidden.unwrap_or(false),
488            }),
489            file: r.file.map(|f| SendAccessFileResponse {
490                id: f.id,
491                file_name: f.file_name,
492                size: f.size,
493                size_name: f.size_name,
494            }),
495            data: r
496                .data
497                .map(|dat| {
498                    Ok::<SendAccessItemResponse, SendParseError>(SendAccessItemResponse {
499                        encryption_version: dat.encryption_version,
500                        data: dat.data,
501                        metadata: SendAccessItemMetadataResponse {
502                            item_id: CipherId::new(dat.metadata.item_id),
503                            folder_name: dat.metadata.folder_name,
504                            collection_names: dat.metadata.collection_names,
505                            organization_name: dat.metadata.organization_name,
506                            creation_date: dat
507                                .metadata
508                                .creation_date
509                                .map(|cd| cd.parse())
510                                .transpose()?,
511                            revision_date: dat
512                                .metadata
513                                .revision_date
514                                .map(|rd| rd.parse())
515                                .transpose()?,
516                        },
517                    })
518                })
519                .transpose()?,
520            expiration_date: r.expiration_date.map(|s| s.parse()).transpose()?,
521            creator_identifier: r.creator_identifier,
522        })
523    }
524}
525
526impl From<models::SendFileDownloadDataResponseModel> for SendFileDownloadData {
527    fn from(r: models::SendFileDownloadDataResponseModel) -> Self {
528        SendFileDownloadData {
529            id: r.id,
530            url: r.url,
531        }
532    }
533}
534
535// ===== SendClient methods =====
536
537// wasm_bindgen generates glue that calls the deprecated methods below, which would otherwise
538// warn.
539#[allow(deprecated)]
540#[bitwarden_ffi::wasm_export]
541impl SendClient {
542    /// Accesses a send, authenticated with a send access token.
543    /// The returned [SendAccessResponse] contains encrypted fields that must be decrypted
544    /// client-side using the key derived from the URL fragment.
545    #[deprecated(
546        note = "use `SendReceiveClient::access_send` instead; a `SendClient` is tied to the signed-in instance"
547    )]
548    pub async fn access_send(
549        &self,
550        access_token: String,
551    ) -> Result<SendAccessResponse, AccessSendError> {
552        let config = self.client.internal.get_api_configurations();
553        access_send(&config.api_client, &access_token).await
554    }
555
556    /// Gets file download data for a file send, authenticated with a send access token.
557    #[deprecated(
558        note = "use `SendReceiveClient::get_file_download_data` instead; a `SendClient` is tied to the signed-in instance"
559    )]
560    pub async fn get_file_download_data(
561        &self,
562        access_token: String,
563        file_id: String,
564    ) -> Result<SendFileDownloadData, GetFileDownloadDataError> {
565        let config = self.client.internal.get_api_configurations();
566        get_file_download_data(&config.api_client, &file_id, &access_token).await
567    }
568
569    /// Decrypt a [`SendAccessResponse`] into a [`SendAccessView`].
570    ///
571    /// `key_b64` is the URL-safe-base64 send key from the trailing segment of the send URL
572    /// fragment (16 bytes when decoded) — the same form [`SendAccessKey::from_url_b64`] accepts
573    ///
574    /// This is a temporary function to support the transition to fully using the SDK for Send logic
575    #[deprecated(
576        note = "use `SendReceiveClient::decrypt_send_access` instead; a `SendClient` is tied to the signed-in instance"
577    )]
578    pub fn decrypt_send_access(
579        key_b64: String,
580        response: SendAccessResponse,
581    ) -> Result<SendAccessView, SendAccessDecryptError> {
582        let access_key = SendAccessKey::from_url_b64(key_b64.as_str())?;
583        access_key.decrypt_response(response)
584    }
585}
586
587#[cfg(test)]
588#[allow(deprecated)]
589mod tests {
590    use bitwarden_api_api::{
591        apis::ApiClient,
592        models::{
593            SendAccessResponseModel, SendFileDownloadDataResponseModel, SendFileModel,
594            SendTextModel, SendType,
595        },
596    };
597
598    use super::*;
599
600    const SEND_ID: &str = "25afb11c-9c95-4db5-8bac-c21cb204a3f1";
601    const FILE_ID: &str = "file-id-abc";
602    const ACCESS_TOKEN: &str = "send-access-token";
603
604    // ===== access_send =====
605
606    #[tokio::test]
607    async fn test_access_send_text() {
608        let api_client = ApiClient::new_mocked(|mock| {
609            mock.sends_api
610                .expect_access_using_auth()
611                .returning(|token| {
612                    assert_eq!(token, ACCESS_TOKEN);
613                    Ok(SendAccessResponseModel {
614                        object: Some("send-access".to_string()),
615                        id: Some(SEND_ID.to_string()),
616                        r#type: Some(SendType::Text),
617                        auth_type: None,
618                        name: Some("encrypted-name".to_string()),
619                        file: None,
620                        text: Some(Box::new(SendTextModel {
621                            text: Some("encrypted_send_text".to_string()),
622                            hidden: Some(true),
623                        })),
624                        data: None,
625                        expiration_date: Some("2025-01-10T00:00:00Z".to_string()),
626                        creator_identifier: Some("[email protected]".to_string()),
627                    })
628                })
629                .once();
630        });
631
632        let result = access_send(&api_client, ACCESS_TOKEN).await.unwrap();
633
634        assert_eq!(result.id, Some(SEND_ID.to_string()));
635        assert_eq!(result.type_, Some(crate::SendType::Text));
636        assert_eq!(result.name, Some("encrypted-name".to_string()));
637        assert!(result.file.is_none());
638        let text = result.text.expect("text variant should be populated");
639        assert_eq!(text.text, Some("encrypted_send_text".to_string()));
640        assert!(text.hidden);
641        assert_eq!(
642            result.expiration_date,
643            Some("2025-01-10T00:00:00Z".parse::<DateTime<Utc>>().unwrap())
644        );
645        assert_eq!(
646            result.creator_identifier,
647            Some("[email protected]".to_string())
648        );
649    }
650
651    #[tokio::test]
652    async fn test_access_send_file() {
653        let api_client = ApiClient::new_mocked(|mock| {
654            mock.sends_api
655                .expect_access_using_auth()
656                .returning(|token| {
657                    assert_eq!(token, ACCESS_TOKEN);
658                    Ok(SendAccessResponseModel {
659                        object: Some("send-access".to_string()),
660                        id: Some(SEND_ID.to_string()),
661                        r#type: Some(SendType::File),
662                        auth_type: None,
663                        name: Some("encrypted-name".to_string()),
664                        file: Some(Box::new(SendFileModel {
665                            id: Some(FILE_ID.to_string()),
666                            file_name: Some("encrypted-file-name".to_string()),
667                            size: Some("4200".to_string()),
668                            size_name: Some("4.2 KB".to_string()),
669                        })),
670                        text: None,
671                        data: None,
672                        expiration_date: None,
673                        creator_identifier: None,
674                    })
675                })
676                .once();
677        });
678
679        let result = access_send(&api_client, ACCESS_TOKEN).await.unwrap();
680
681        assert_eq!(result.id, Some(SEND_ID.to_string()));
682        assert_eq!(result.type_, Some(crate::SendType::File));
683        assert_eq!(result.name, Some("encrypted-name".to_string()));
684        assert!(result.text.is_none());
685        let file = result.file.expect("file variant should be populated");
686        assert_eq!(file.id, Some(FILE_ID.to_string()));
687        assert_eq!(file.file_name, Some("encrypted-file-name".to_string()));
688        assert_eq!(file.size, Some("4200".to_string()));
689        assert_eq!(file.size_name, Some("4.2 KB".to_string()));
690        assert_eq!(result.expiration_date, None);
691        assert_eq!(result.creator_identifier, None);
692    }
693
694    #[tokio::test]
695    async fn test_access_send_http_error() {
696        let api_client = ApiClient::new_mocked(|mock| {
697            mock.sends_api
698                .expect_access_using_auth()
699                .returning(|_token| {
700                    Err(bitwarden_api_api::ApiError::Io(std::io::Error::other(
701                        "Simulated error",
702                    )))
703                })
704                .once();
705        });
706
707        let result = access_send(&api_client, ACCESS_TOKEN).await;
708
709        assert!(matches!(result.unwrap_err(), AccessSendError::Api(_)));
710    }
711
712    #[tokio::test]
713    async fn test_access_send_404_is_not_found() {
714        let api_client = ApiClient::new_mocked(|mock| {
715            mock.sends_api
716                .expect_access_using_auth()
717                .returning(|_token| Err(not_found_response()))
718                .once();
719        });
720
721        let result = access_send(&api_client, ACCESS_TOKEN).await;
722
723        assert!(matches!(result.unwrap_err(), AccessSendError::NotFound));
724    }
725
726    #[tokio::test]
727    async fn test_access_send_other_status_stays_api_error() {
728        let api_client = ApiClient::new_mocked(|mock| {
729            mock.sends_api
730                .expect_access_using_auth()
731                .returning(|_token| {
732                    Err(bitwarden_api_api::ApiError::Response(
733                        bitwarden_api_api::ResponseContent {
734                            status: reqwest::StatusCode::INTERNAL_SERVER_ERROR,
735                            message: "boom".to_string(),
736                        },
737                    ))
738                })
739                .once();
740        });
741
742        let result = access_send(&api_client, ACCESS_TOKEN).await;
743
744        assert!(matches!(result.unwrap_err(), AccessSendError::Api(_)));
745    }
746
747    fn not_found_response() -> bitwarden_api_api::ApiError {
748        bitwarden_api_api::ApiError::Response(bitwarden_api_api::ResponseContent {
749            status: reqwest::StatusCode::NOT_FOUND,
750            message: "Not Found".to_string(),
751        })
752    }
753
754    // ===== get_file_download_data =====
755
756    #[tokio::test]
757    async fn test_get_file_download_data() {
758        let api_client = ApiClient::new_mocked(|mock| {
759            mock.sends_api
760                .expect_get_send_file_download_data_using_auth()
761                .returning(|file_id, token| {
762                    assert_eq!(file_id, FILE_ID);
763                    assert_eq!(token, ACCESS_TOKEN);
764                    Ok(SendFileDownloadDataResponseModel {
765                        object: Some("send-fileDownload".to_string()),
766                        id: Some(FILE_ID.to_string()),
767                        url: Some("https://example.com/download".to_string()),
768                    })
769                })
770                .once();
771        });
772
773        let result = get_file_download_data(&api_client, FILE_ID, ACCESS_TOKEN)
774            .await
775            .unwrap();
776
777        assert_eq!(result.id, Some(FILE_ID.to_string()));
778        assert_eq!(result.url, Some("https://example.com/download".to_string()));
779    }
780
781    #[tokio::test]
782    async fn test_get_file_download_data_http_error() {
783        let api_client = ApiClient::new_mocked(|mock| {
784            mock.sends_api
785                .expect_get_send_file_download_data_using_auth()
786                .returning(|_file_id, _token| {
787                    Err(bitwarden_api_api::ApiError::Io(std::io::Error::other(
788                        "Simulated error",
789                    )))
790                })
791                .once();
792        });
793
794        let result = get_file_download_data(&api_client, FILE_ID, ACCESS_TOKEN).await;
795
796        assert!(matches!(
797            result.unwrap_err(),
798            GetFileDownloadDataError::Api(_)
799        ));
800    }
801
802    #[tokio::test]
803    async fn test_get_file_download_data_404_is_not_found() {
804        let api_client = ApiClient::new_mocked(|mock| {
805            mock.sends_api
806                .expect_get_send_file_download_data_using_auth()
807                .returning(|_file_id, _token| Err(not_found_response()))
808                .once();
809        });
810
811        let result = get_file_download_data(&api_client, FILE_ID, ACCESS_TOKEN).await;
812
813        assert!(matches!(
814            result.unwrap_err(),
815            GetFileDownloadDataError::NotFound
816        ));
817    }
818
819    // ===== SendAccessKey =====
820
821    mod send_access_key {
822        //! Tests for [`SendAccessKey`]: URL-fragment key parsing/derivation, password hashing,
823        //! and decrypting a [`SendAccessResponse`] into a [`SendAccessView`].
824
825        use bitwarden_core::key_management::create_test_crypto_with_user_key;
826        use bitwarden_crypto::{OctetStreamBytes, PrimitiveEncryptable as _, SymmetricCryptoKey};
827        use bitwarden_vault::CipherId;
828
829        use crate::{
830            Send, SendAccessDecryptError, SendAccessFileResponse, SendAccessKey,
831            SendAccessKeyError, SendAccessResponse, SendAccessTextResponse, SendAuthType,
832            SendClient, SendFileView, SendTextView, SendType, SendView,
833            access::{SendAccessItemMetadataResponse, SendAccessItemResponse},
834            send::tests::{TEST_ITEM_ID, TEST_VECTOR_ITEM_SEND_DATA},
835        };
836
837        /// The url-safe-base64 form of a 16-byte send key, as it appears in the trailing
838        /// segment of a send URL fragment. Shared with the tests in `send.rs`.
839        const URL_KEY: &str = "Pgui0FK85cNhBGWHAlBHBw";
840        const USER_KEY: &str = "bYCsk857hl8QJJtxyRK65tjUrbxKC4aDifJpsml+NIv4W9cVgFvi3qVD+yJTUU2T4UwNKWYtt9pqWf7Q+2WCCg==";
841
842        fn user_key() -> SymmetricCryptoKey {
843            USER_KEY
844                .to_string()
845                .try_into()
846                .expect("valid test user key")
847        }
848
849        /// Encrypt a [`SendView`] through the authenticated (key-store) path — the exact
850        /// path `bw send create` takes — so the receive path can be checked against real
851        /// ciphertext rather than a fixture that could drift.
852        fn encrypt_send(view: SendView) -> Send {
853            create_test_crypto_with_user_key(user_key())
854                .encrypt(view)
855                .expect("send encrypts")
856        }
857
858        fn text_send_view(text: &str, name: &str) -> SendView {
859            SendView {
860                id: "3d80dd72-2d14-4f26-812c-b0f0018aa144".parse().ok(),
861                access_id: Some("ct2APRQtJk-BLLDwAYqhRA".to_owned()),
862                name: name.to_owned(),
863                notes: None,
864                key: Some(URL_KEY.to_owned()),
865                new_password: None,
866                has_password: false,
867                r#type: SendType::Text,
868                file: None,
869                text: Some(SendTextView {
870                    text: Some(text.to_owned()),
871                    hidden: false,
872                }),
873                data: None,
874                max_access_count: None,
875                access_count: 0,
876                disabled: false,
877                hide_email: false,
878                revision_date: "2024-01-07T23:56:48.207363Z".parse().unwrap(),
879                deletion_date: "2024-01-14T23:56:48Z".parse().unwrap(),
880                expiration_date: None,
881                emails: Vec::new(),
882                auth_type: crate::AuthType::None,
883            }
884        }
885
886        /// Build the wire-format [`SendAccessResponse`] the server would return for a
887        /// text send encrypted by [`encrypt_send`].
888        fn text_send_response(send: &Send) -> SendAccessResponse {
889            SendAccessResponse {
890                id: Some("access-id".to_owned()),
891                type_: Some(SendType::Text),
892                name: Some(send.name.to_string()),
893                text: Some(SendAccessTextResponse {
894                    text: send
895                        .text
896                        .as_ref()
897                        .and_then(|t| t.text.as_ref())
898                        .map(|t| t.to_string()),
899                    hidden: false,
900                }),
901                file: None,
902                data: None,
903                expiration_date: None,
904                creator_identifier: None,
905            }
906        }
907
908        /// The load-bearing test for this whole flow: a send encrypted through the
909        /// authenticated key-store path must be decryptable by a key derived *only* from the
910        /// URL fragment. This pins [`SendAccessKey::from_url_b64`]'s derivation
911        /// (`derive_shareable_key(secret, "send", Some("send"))`) byte-for-byte against
912        /// [`Send::derive_shareable_key`]. If the two ever drift, every `bw receive`
913        /// silently fails to decrypt.
914        #[test]
915        fn decrypts_ciphertext_produced_by_the_authenticated_path() {
916            let send = encrypt_send(text_send_view("This is a test", "Test"));
917            let response = text_send_response(&send);
918
919            let access_key = SendAccessKey::from_url_b64(URL_KEY).expect("key parses");
920            let view = access_key.decrypt_response(response).expect("decrypts");
921
922            assert_eq!(view.name.as_deref(), Some("Test"));
923            assert_eq!(
924                view.text.expect("text present").text.as_deref(),
925                Some("This is a test")
926            );
927        }
928
929        #[test]
930        fn decrypts_file_name_produced_by_the_authenticated_path() {
931            let mut view = text_send_view("unused", "File Send");
932            view.r#type = SendType::File;
933            view.text = None;
934            view.file = Some(SendFileView {
935                id: Some("file-id".to_owned()),
936                file_name: "secrets.txt".to_owned(),
937                size: Some("11".to_owned()),
938                size_name: Some("11 B".to_owned()),
939            });
940            let send = encrypt_send(view);
941            let file = send.file.expect("file present");
942
943            let response = SendAccessResponse {
944                id: Some("access-id".to_owned()),
945                type_: Some(SendType::File),
946                name: Some(send.name.to_string()),
947                text: None,
948                file: Some(SendAccessFileResponse {
949                    id: file.id.clone(),
950                    file_name: Some(file.file_name.to_string()),
951                    size: file.size.clone(),
952                    size_name: file.size_name.clone(),
953                }),
954                data: None,
955                expiration_date: None,
956                creator_identifier: None,
957            };
958
959            let access_key = SendAccessKey::from_url_b64(URL_KEY).expect("key parses");
960            let view = access_key.decrypt_response(response).expect("decrypts");
961
962            let decrypted_file = view.file.expect("file present");
963            assert_eq!(decrypted_file.file_name.as_deref(), Some("secrets.txt"));
964            assert_eq!(decrypted_file.size.as_deref(), Some("11"));
965            assert_eq!(decrypted_file.id.as_deref(), Some("file-id"));
966            assert_eq!(view.name.as_deref(), Some("File Send"));
967        }
968
969        /// A file-send blob is a whole-buffer `EncString`, encrypted under the same stretched
970        /// send key. Round-trip it through the authenticated encrypt path (what
971        /// `create_file_send` uploads) and the anonymous decrypt path (what `bw receive`
972        /// downloads).
973        #[test]
974        fn decrypt_file_buffer_round_trips_with_the_authenticated_path() {
975            let plaintext = b"file send contents".to_vec();
976
977            let crypto = create_test_crypto_with_user_key(user_key());
978            let mut ctx = crypto.context();
979            let raw_key = bitwarden_encoding::B64Url::try_from(URL_KEY)
980                .expect("url key decodes")
981                .into_bytes();
982            let send_key = Send::derive_shareable_key(&mut ctx, &raw_key).expect("key derives");
983            let encrypted = OctetStreamBytes::from(plaintext.clone())
984                .encrypt(&mut ctx, send_key)
985                .expect("buffer encrypts")
986                .to_buffer()
987                .expect("buffer serializes");
988
989            let access_key = SendAccessKey::from_url_b64(URL_KEY).expect("key parses");
990            let decrypted = access_key
991                .decrypt_file_buffer(&encrypted)
992                .expect("buffer decrypts");
993
994            assert_eq!(decrypted, plaintext);
995        }
996
997        /// `hash_password_b64` and [`SendAuthType::auth_data`] must produce the same
998        /// `password_hash_b64`: `auth_data` is what `bw send create --password` stored on the
999        /// server, and `hash_password_b64` is what `bw receive` presents to the token grant.
1000        /// Any divergence turns every password-protected receive into an opaque 400.
1001        #[test]
1002        fn hash_password_b64_matches_send_auth_type_auth_data() {
1003            let raw_key = bitwarden_encoding::B64Url::try_from(URL_KEY)
1004                .expect("url key decodes")
1005                .into_bytes();
1006
1007            let (created_hash, emails) = SendAuthType::Password {
1008                password: "hunter2".to_owned(),
1009            }
1010            .auth_data(&raw_key);
1011            assert_eq!(emails, None);
1012
1013            let access_key = SendAccessKey::from_url_b64(URL_KEY).expect("key parses");
1014            let receive_hash = access_key.hash_password_b64("hunter2");
1015
1016            assert_eq!(
1017                created_hash,
1018                Some(receive_hash),
1019                "receive's password hash must match the one `bw send create` stored"
1020            );
1021        }
1022
1023        #[test]
1024        fn hash_password_b64_is_salted_with_the_send_key() {
1025            // Different sends (different URL keys) must produce different hashes for the
1026            // same password, otherwise a hash captured from one send would unlock another.
1027            let a = SendAccessKey::from_url_b64(URL_KEY).expect("key parses");
1028            let b = SendAccessKey::from_url_b64("AAAAAAAAAAAAAAAAAAAAAA").expect("key parses");
1029            assert_ne!(
1030                a.hash_password_b64("hunter2"),
1031                b.hash_password_b64("hunter2")
1032            );
1033        }
1034
1035        #[test]
1036        fn from_url_b64_accepts_padded_and_unpadded() {
1037            // The fragment form is unpadded, but a caller pasting a padded key (or a URL that
1038            // has been round-tripped through a tool that re-adds padding) should still work.
1039            let unpadded = SendAccessKey::from_url_b64(URL_KEY).expect("unpadded parses");
1040            let padded =
1041                SendAccessKey::from_url_b64(&format!("{URL_KEY}==")).expect("padded parses");
1042            assert_eq!(
1043                unpadded.hash_password_b64("p"),
1044                padded.hash_password_b64("p"),
1045                "padded and unpadded forms must derive the same key"
1046            );
1047        }
1048
1049        #[test]
1050        fn from_url_b64_rejects_invalid_base64() {
1051            assert!(matches!(
1052                SendAccessKey::from_url_b64("not valid base64!"),
1053                Err(SendAccessKeyError::InvalidEncoding)
1054            ));
1055        }
1056
1057        #[test]
1058        fn from_url_b64_rejects_wrong_length() {
1059            // Too short (8 bytes) and too long (32 bytes) must both be rejected rather than
1060            // silently truncated or zero-padded into a different key.
1061            for bad in ["AAAAAAAAAAA", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"] {
1062                assert!(
1063                    matches!(
1064                        SendAccessKey::from_url_b64(bad),
1065                        Err(SendAccessKeyError::InvalidLength)
1066                    ),
1067                    "expected InvalidLength for {bad:?}"
1068                );
1069            }
1070            assert!(matches!(
1071                SendAccessKey::from_url_b64(""),
1072                Err(SendAccessKeyError::InvalidLength)
1073            ));
1074        }
1075
1076        /// A send with no name and no text body must decrypt to a view with `None` fields
1077        /// rather than erroring — legacy prints whatever it got, and requiring a name would
1078        /// make otherwise-valid sends unreadable.
1079        #[test]
1080        fn decrypt_response_tolerates_absent_fields() {
1081            let response = SendAccessResponse {
1082                id: None,
1083                type_: None,
1084                name: None,
1085                text: Some(SendAccessTextResponse {
1086                    text: None,
1087                    hidden: true,
1088                }),
1089                file: None,
1090                data: None,
1091                expiration_date: None,
1092                creator_identifier: None,
1093            };
1094
1095            let access_key = SendAccessKey::from_url_b64(URL_KEY).expect("key parses");
1096            let view = access_key.decrypt_response(response).expect("decrypts");
1097
1098            assert_eq!(view.name, None);
1099            assert_eq!(view.type_, None);
1100            let text = view.text.expect("text block present");
1101            assert_eq!(text.text, None);
1102            assert!(text.hidden);
1103        }
1104
1105        #[test]
1106        fn decrypt_response_restores_item_id_from_metadata() {
1107            let item_id: CipherId = TEST_ITEM_ID.parse().unwrap();
1108            let response = SendAccessResponse {
1109                id: None,
1110                type_: Some(SendType::Item),
1111                name: None,
1112                text: None,
1113                file: None,
1114                data: Some(SendAccessItemResponse {
1115                    encryption_version: None,
1116                    data: Some(TEST_VECTOR_ITEM_SEND_DATA.to_owned()),
1117                    metadata: SendAccessItemMetadataResponse {
1118                        item_id,
1119                        creation_date: Default::default(),
1120                        revision_date: Default::default(),
1121                        folder_name: None,
1122                        collection_names: None,
1123                        organization_name: None,
1124                    },
1125                }),
1126                expiration_date: None,
1127                creator_identifier: None,
1128            };
1129
1130            let access_key = SendAccessKey::from_url_b64(URL_KEY).expect("key parses");
1131            let view = access_key.decrypt_response(response).expect("decrypts");
1132
1133            let cipher = view.data.and_then(|d| d.data).expect("item present");
1134            assert_eq!(cipher.id, Some(item_id));
1135        }
1136
1137        #[test]
1138        fn decrypt_response_errors_on_a_key_that_does_not_match() {
1139            let send = encrypt_send(text_send_view("This is a test", "Test"));
1140            let response = SendAccessResponse {
1141                id: None,
1142                type_: Some(SendType::Text),
1143                name: Some(send.name.to_string()),
1144                text: None,
1145                file: None,
1146                data: None,
1147                expiration_date: None,
1148                creator_identifier: None,
1149            };
1150
1151            // A syntactically valid but wrong URL key must fail loudly, not return garbage.
1152            let wrong_key =
1153                SendAccessKey::from_url_b64("AAAAAAAAAAAAAAAAAAAAAA").expect("key parses");
1154            assert!(wrong_key.decrypt_response(response).is_err());
1155        }
1156
1157        #[test]
1158        fn decrypt_response_errors_on_a_malformed_enc_string() {
1159            let response = SendAccessResponse {
1160                id: None,
1161                type_: Some(SendType::Text),
1162                name: Some("this is not an EncString".to_owned()),
1163                text: None,
1164                file: None,
1165                data: None,
1166                expiration_date: None,
1167                creator_identifier: None,
1168            };
1169
1170            let access_key = SendAccessKey::from_url_b64(URL_KEY).expect("key parses");
1171            assert!(access_key.decrypt_response(response).is_err());
1172        }
1173
1174        /// The `--fullObject` JSON dump is a user-facing contract; pin its camelCase wire
1175        /// shape (including `type` rather than `type_`) so a field rename can't silently
1176        /// break scripts parsing `bw receive --fullObject`.
1177        #[test]
1178        fn send_access_view_serializes_in_camel_case() {
1179            let view = crate::SendAccessView {
1180                id: Some("access-id".to_owned()),
1181                type_: Some(SendType::File),
1182                name: Some("name".to_owned()),
1183                text: None,
1184                file: Some(crate::SendAccessFileView {
1185                    id: Some("file-id".to_owned()),
1186                    file_name: Some("secrets.txt".to_owned()),
1187                    size: Some("11".to_owned()),
1188                    size_name: Some("11 B".to_owned()),
1189                }),
1190                data: None,
1191                expiration_date: None,
1192                creator_identifier: None,
1193            };
1194
1195            let json = serde_json::to_value(&view).expect("serializes");
1196            assert_eq!(json["type"], serde_json::json!(1));
1197            assert_eq!(json["file"]["fileName"], serde_json::json!("secrets.txt"));
1198            assert_eq!(json["file"]["sizeName"], serde_json::json!("11 B"));
1199            assert_eq!(json["creatorIdentifier"], serde_json::Value::Null);
1200        }
1201
1202        #[test]
1203        fn decrypt_send_access_success() {
1204            let send = encrypt_send(text_send_view("This is a test", "Test"));
1205            let view =
1206                SendClient::decrypt_send_access(URL_KEY.to_owned(), text_send_response(&send))
1207                    .expect("decrypts");
1208
1209            assert_eq!(view.name.as_deref(), Some("Test"));
1210            assert_eq!(
1211                view.text.expect("text present").text.as_deref(),
1212                Some("This is a test")
1213            );
1214        }
1215
1216        #[test]
1217        fn decrypt_send_access_malformed_b64() {
1218            let response = SendAccessResponse {
1219                id: Some("access-id".to_owned()),
1220                type_: Some(SendType::Text),
1221                name: Some("Test".to_owned()),
1222                text: None,
1223                file: None,
1224                data: None,
1225                expiration_date: None,
1226                creator_identifier: None,
1227            };
1228
1229            let result = SendClient::decrypt_send_access("not valid base64!".to_owned(), response);
1230
1231            assert!(matches!(
1232                result.unwrap_err(),
1233                SendAccessDecryptError::Key(SendAccessKeyError::InvalidEncoding)
1234            ));
1235        }
1236    }
1237}