rust_filen 0.3.0

Rust interface for Filen.io API
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
use crate::{
    crypto, queries, utils,
    v1::{
        files, fs, response_payload, Expire, FileProperties, HasFileMetadata, HasLinkKey, HasLocationName, HasUuid,
        ItemKind, Lazy, LocationNameMetadata, ParentOrBase, PasswordState, PlainResponsePayload,
    },
    FilenSettings,
};
use secstr::SecUtf8;
use serde::{Deserialize, Serialize};
use serde_repr::{Deserialize_repr, Serialize_repr};
use serde_with::skip_serializing_none;
use snafu::{ResultExt, Snafu};
use strum::{Display, EnumString};
use uuid::Uuid;

type Result<T, E = Error> = std::result::Result<T, E>;

pub static LINK_EMPTY_PASSWORD_VALUE: Lazy<String> = Lazy::new(|| PasswordState::Empty.to_string());
pub static LINK_EMPTY_PASSWORD_HASH: Lazy<String> = Lazy::new(|| crypto::hash_fn(LINK_EMPTY_PASSWORD_VALUE.clone()));
pub static SEC_LINK_EMPTY_PASSWORD_VALUE: Lazy<SecUtf8> =
    Lazy::new(|| SecUtf8::from(LINK_EMPTY_PASSWORD_VALUE.as_str()));

const DIR_LINK_ADD_PATH: &str = "/v1/dir/link/add";
const DIR_LINK_EDIT_PATH: &str = "/v1/dir/link/edit";
const DIR_LINK_REMOVE_PATH: &str = "/v1/dir/link/remove";
const DIR_LINK_STATUS_PATH: &str = "/v1/dir/link/status";

#[allow(clippy::enum_variant_names)]
#[derive(Snafu, Debug)]
pub enum Error {
    #[snafu(display("Failed to decrypt link key metadata '{}': {}", metadata, source))]
    DecryptLinkKeyMetadataFailed { metadata: String, source: crypto::Error },

    #[snafu(display("{}", source))]
    DecryptLocationNameFailed { source: fs::Error },

    #[snafu(display("{}", source))]
    DecryptFileMetadataFailed { source: files::Error },

    #[snafu(display("{} query failed: {}", DIR_LINK_ADD_PATH, source))]
    DirLinkAddQueryFailed { source: queries::Error },

    #[snafu(display("{} query failed: {}", DIR_LINK_EDIT_PATH, source))]
    DirLinkEditQueryFailed { source: queries::Error },

    #[snafu(display("{} query failed: {}", DIR_LINK_REMOVE_PATH, source))]
    DirLinkRemoveQueryFailed { source: queries::Error },

    #[snafu(display("{} query failed: {}", DIR_LINK_STATUS_PATH, source))]
    DirLinkStatusQueryFailed { source: queries::Error },
}

/// State of the 'Enable download button' GUI toggle represented as a string.
/// It is the toggle you can see at the bottom of modal popup when creating or sharing an item.
#[derive(Clone, Copy, Debug, Deserialize, Display, EnumString, Eq, Hash, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
#[strum(ascii_case_insensitive, serialize_all = "lowercase")]
pub enum DownloadBtnState {
    /// 'Enable download button' checkbox is disabled.
    Disable,
    /// 'Enable download button' checkbox is enabled.
    Enable,
}

/// State of the 'Enable download button' GUI toggle represented as a 0|1 flag.
/// It is the toggle you can see at the bottom of modal popup when creating or sharing an item.
#[derive(Clone, Copy, Debug, Deserialize_repr, Display, EnumString, Eq, Hash, PartialEq, Serialize_repr)]
#[repr(u8)]
#[strum(ascii_case_insensitive, serialize_all = "lowercase")]
pub enum DownloadBtnStateByte {
    Disable = 0,
    Enable = 1,
}

/// Used for requests to `DIR_LINK_ADD_PATH` endpoint.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct DirLinkAddRequestPayload<'dir_link_add> {
    /// User-associated Filen API key.
    #[serde(rename = "apiKey")]
    pub api_key: &'dir_link_add SecUtf8,

    /// Filen sets this to "enable" by default.
    #[serde(rename = "downloadBtn")]
    pub download_btn: DownloadBtnState,

    /// Link expiration time in text form. Usually has value "never".
    pub expiration: Expire,

    /// Link key, encrypted.
    #[serde(rename = "key")]
    pub key_metadata: &'dir_link_add str,

    /// Link ID; hyphenated lowercased UUID V4.
    #[serde(rename = "linkUUID")]
    pub link_uuid: Uuid,

    /// Linked item metadata.
    pub metadata: String,

    /// ID of the linked parent of the linked item, hyphenated lowercased UUID V4.
    /// Use "base" if linked item's parent is not linked.
    pub parent: ParentOrBase,

    /// Filen always uses "empty" when adding links.
    pub password: PasswordState,

    /// Output of hash_fn for the link's password.
    #[serde(rename = "passwordHashed")]
    pub password_hashed: &'dir_link_add str,

    /// Determines whether a file or a folder is being linked.
    #[serde(rename = "type")]
    pub link_type: ItemKind,

    /// Linked item ID; hyphenated lowercased UUID V4.
    pub uuid: Uuid,
}
utils::display_from_json_with_lifetime!('dir_link_add, DirLinkAddRequestPayload);

impl<'dir_link_add> DirLinkAddRequestPayload<'dir_link_add> {
    pub fn from_file_data<T: HasFileMetadata + HasUuid>(
        api_key: &'dir_link_add SecUtf8,
        file_data: &T,
        parent: ParentOrBase,
        link_uuid: Uuid,
        link_key_metadata: &'dir_link_add str,
        master_keys: &[SecUtf8],
    ) -> Result<Self> {
        let file_properties = file_data
            .decrypt_file_metadata(master_keys)
            .context(DecryptFileMetadataFailedSnafu {})?;
        Self::from_file_properties(
            api_key,
            *file_data.uuid_ref(),
            &file_properties,
            parent,
            link_uuid,
            link_key_metadata,
            master_keys,
        )
    }

    pub fn from_file_properties(
        api_key: &'dir_link_add SecUtf8,
        file_uuid: Uuid,
        file_properties: &FileProperties,
        parent: ParentOrBase,
        link_uuid: Uuid,
        link_key_metadata: &'dir_link_add str,
        master_keys: &[SecUtf8],
    ) -> Result<Self> {
        let link_key = SecUtf8::from(
            crypto::decrypt_metadata_str_any_key(link_key_metadata, master_keys).context(
                DecryptLinkKeyMetadataFailedSnafu {
                    metadata: link_key_metadata.to_owned(),
                },
            )?,
        );
        let metadata = file_properties.to_metadata_string(&link_key);
        Ok(Self {
            api_key,
            download_btn: DownloadBtnState::Enable,
            expiration: Expire::Never,
            key_metadata: link_key_metadata,
            link_uuid,
            metadata,
            parent,
            password: PasswordState::Empty,
            password_hashed: &LINK_EMPTY_PASSWORD_HASH,
            link_type: ItemKind::File,
            uuid: file_uuid,
        })
    }

    pub fn from_folder_data<T: HasLocationName + HasUuid>(
        api_key: &'dir_link_add SecUtf8,
        folder_data: &T,
        parent: ParentOrBase,
        link_uuid: Uuid,
        link_key_metadata: &'dir_link_add str,
        master_keys: &[SecUtf8],
    ) -> Result<Self> {
        let folder_name = folder_data
            .decrypt_name_metadata(master_keys)
            .context(DecryptLocationNameFailedSnafu {})?;
        Self::from_folder_name(
            api_key,
            *folder_data.uuid_ref(),
            &folder_name,
            parent,
            link_uuid,
            link_key_metadata,
            master_keys,
        )
    }

    pub fn from_folder_name(
        api_key: &'dir_link_add SecUtf8,
        folder_uuid: Uuid,
        folder_name: &str,
        parent: ParentOrBase,
        link_uuid: Uuid,
        link_key_metadata: &'dir_link_add str,
        master_keys: &[SecUtf8],
    ) -> Result<Self> {
        let link_key = SecUtf8::from(
            crypto::decrypt_metadata_str_any_key(link_key_metadata, master_keys).context(
                DecryptLinkKeyMetadataFailedSnafu {
                    metadata: link_key_metadata.to_owned(),
                },
            )?,
        );
        let metadata = LocationNameMetadata::encrypt_name_to_metadata(folder_name, &link_key);
        Ok(Self {
            api_key,
            download_btn: DownloadBtnState::Enable,
            expiration: Expire::Never,
            key_metadata: link_key_metadata,
            link_uuid,
            metadata,
            parent,
            password: PasswordState::Empty,
            password_hashed: &LINK_EMPTY_PASSWORD_HASH,
            link_type: ItemKind::Folder,
            uuid: folder_uuid,
        })
    }
}

/// Used for requests to `DIR_LINK_EDIT_PATH` endpoint.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct DirLinkEditRequestPayload<'dir_link_edit> {
    /// User-associated Filen API key.
    #[serde(rename = "apiKey")]
    pub api_key: &'dir_link_edit SecUtf8,

    /// Filen sets this to "enable" by default. If user toggled off the 'Enable download button' checkbox,
    /// then this is set to "disable".
    #[serde(rename = "downloadBtn")]
    pub download_btn: DownloadBtnState,

    /// Link expiration time in text form. Usually has value "never".
    pub expiration: Expire,

    /// "empty" means no password protection, "notempty" means password is present.
    pub password: PasswordState,

    /// Hashed link's password, output of [crypto::derive_key_from_password_512] with 32 random bytes of salt;
    /// converted to a hex string.
    #[serde(rename = "passwordHashed")]
    pub password_hashed: String,

    /// Salt used to make hashed password.
    pub salt: String,

    /// Linked item ID; hyphenated lowercased UUID V4.
    pub uuid: Uuid,
}
utils::display_from_json_with_lifetime!('dir_link_edit, DirLinkEditRequestPayload);

impl<'dir_link_edit> DirLinkEditRequestPayload<'dir_link_edit> {
    #[must_use]
    pub fn new(
        api_key: &'dir_link_edit SecUtf8,
        download_btn: DownloadBtnState,
        item_uuid: Uuid,
        expiration: Expire,
        link_plain_password: Option<&SecUtf8>,
    ) -> Self {
        let (password_hashed, salt) = link_plain_password.map_or_else(
            || crypto::encrypt_to_link_password_and_salt(&SEC_LINK_EMPTY_PASSWORD_VALUE),
            crypto::encrypt_to_link_password_and_salt,
        );
        Self {
            api_key,
            download_btn,
            expiration,
            password: link_plain_password.map_or(PasswordState::Empty, |_| PasswordState::NotEmpty),
            password_hashed,
            salt,
            uuid: item_uuid,
        }
    }
}

/// Used for requests to `DIR_LINK_REMOVE_PATH` endpoint.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct DirLinkRemoveRequestPayload<'dir_link_remove> {
    /// User-associated Filen API key.
    #[serde(rename = "apiKey")]
    pub api_key: &'dir_link_remove SecUtf8,

    /// Linked folder ID; hyphenated lowercased UUID V4.
    pub uuid: Uuid,
}
utils::display_from_json_with_lifetime!('dir_link_remove, DirLinkRemoveRequestPayload);

/// Used for requests to `DIR_LINK_STATUS_PATH` endpoint.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct DirLinkStatusRequestPayload<'dir_link_status> {
    /// User-associated Filen API key.
    #[serde(rename = "apiKey")]
    pub api_key: &'dir_link_status SecUtf8,

    /// ID of the item whose link should be checked; hyphenated lowercased UUID V4.
    pub uuid: Uuid,
}
utils::display_from_json_with_lifetime!('dir_link_status, DirLinkStatusRequestPayload);

/// Response data for `DIR_LINK_STATUS_PATH` endpoint.
#[skip_serializing_none]
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct DirLinkStatusResponseData {
    /// True if link exists; false if link for the given item ID cannot be found.
    pub exists: bool,

    /// Found link ID; hyphenated lowercased UUID V4. None if no link was found.
    pub uuid: Option<Uuid>,

    /// Link key metadata. None if no link was found.
    pub key: Option<String>,

    /// Link expiration time, as Unix timestamp in seconds. None if no link was found.
    pub expiration: Option<u64>,

    /// Link expiration time in text form. None if no link was found.
    #[serde(rename = "expirationText")]
    pub expiration_text: Option<Expire>,

    /// None if no link was found.
    #[serde(rename = "downloadBtn")]
    pub download_btn: Option<DownloadBtnStateByte>,

    /// Link password hash in hex string form, or None if no password was set by user or if no link was found.
    pub password: Option<String>,
}
utils::display_from_json!(DirLinkStatusResponseData);

impl HasLinkKey for DirLinkStatusResponseData {
    fn link_key_metadata_ref(&self) -> Option<&str> {
        self.key.as_deref()
    }
}

response_payload!(
    /// Response for `DIR_LINK_STATUS_PATH` endpoint.
    DirLinkStatusResponsePayload<DirLinkStatusResponseData>
);

/// Calls `DIR_LINK_ADD_PATH` endpoint. Used to add a folder or a file to a folder link.
///
/// Filen always creates a link without password first, and optionally sets password later using `dir_link_edit_request`.
pub fn dir_link_add_request(
    payload: &DirLinkAddRequestPayload,
    filen_settings: &FilenSettings,
) -> Result<PlainResponsePayload> {
    queries::query_filen_api(DIR_LINK_ADD_PATH, payload, filen_settings).context(DirLinkAddQueryFailedSnafu {})
}

/// Calls `DIR_LINK_ADD_PATH` endpoint asynchronously. Used to add a folder or a file to a folder link.
///
/// Filen always creates a link without password first, and optionally sets password later using `dir_link_edit_request`.
#[cfg(feature = "async")]
pub async fn dir_link_add_request_async(
    payload: &DirLinkAddRequestPayload<'_>,
    filen_settings: &FilenSettings,
) -> Result<PlainResponsePayload> {
    queries::query_filen_api_async(DIR_LINK_ADD_PATH, payload, filen_settings)
        .await
        .context(DirLinkAddQueryFailedSnafu {})
}

/// Calls `DIR_LINK_EDIT_PATH` endpoint. Used to edit given folder link.
///
/// Filen always creates a link without password first, and optionally sets password later using this query.
pub fn dir_link_edit_request(
    payload: &DirLinkEditRequestPayload,
    filen_settings: &FilenSettings,
) -> Result<PlainResponsePayload> {
    queries::query_filen_api(DIR_LINK_EDIT_PATH, payload, filen_settings).context(DirLinkEditQueryFailedSnafu {})
}

/// Calls `DIR_LINK_EDIT_PATH` endpoint asynchronously. Used to edit given folder link.
///
/// Filen always creates a link without password first, and optionally sets password later using this query.
#[cfg(feature = "async")]
pub async fn dir_link_edit_request_async(
    payload: &DirLinkEditRequestPayload<'_>,
    filen_settings: &FilenSettings,
) -> Result<PlainResponsePayload> {
    queries::query_filen_api_async(DIR_LINK_EDIT_PATH, payload, filen_settings)
        .await
        .context(DirLinkEditQueryFailedSnafu {})
}

/// Calls `DIR_LINK_REMOVE_PATH` endpoint. Used to remove given folder link.
pub fn dir_link_remove_request(
    payload: &DirLinkRemoveRequestPayload,
    filen_settings: &FilenSettings,
) -> Result<PlainResponsePayload> {
    queries::query_filen_api(DIR_LINK_REMOVE_PATH, payload, filen_settings).context(DirLinkRemoveQueryFailedSnafu {})
}

/// Calls `DIR_LINK_REMOVE_PATH` endpoint asynchronously. Used to remove given folder link.
#[cfg(feature = "async")]
pub async fn dir_link_remove_request_async(
    payload: &DirLinkRemoveRequestPayload<'_>,
    filen_settings: &FilenSettings,
) -> Result<PlainResponsePayload> {
    queries::query_filen_api_async(DIR_LINK_REMOVE_PATH, payload, filen_settings)
        .await
        .context(DirLinkRemoveQueryFailedSnafu {})
}

/// Calls `DIR_LINK_STATUS_PATH` endpoint. Used to check folder link status.
pub fn dir_link_status_request(
    payload: &DirLinkStatusRequestPayload,
    filen_settings: &FilenSettings,
) -> Result<DirLinkStatusResponsePayload> {
    queries::query_filen_api(DIR_LINK_STATUS_PATH, payload, filen_settings).context(DirLinkStatusQueryFailedSnafu {})
}

/// Calls `DIR_LINK_STATUS_PATH` endpoint asynchronously. Used to check folder link status.
#[cfg(feature = "async")]
pub async fn dir_link_status_request_async(
    payload: &DirLinkStatusRequestPayload<'_>,
    filen_settings: &FilenSettings,
) -> Result<DirLinkStatusResponsePayload> {
    queries::query_filen_api_async(DIR_LINK_STATUS_PATH, payload, filen_settings)
        .await
        .context(DirLinkStatusQueryFailedSnafu {})
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_utils::validate_contract;
    #[cfg(feature = "async")]
    use crate::test_utils::validate_contract_async;
    use once_cell::sync::Lazy;
    use secstr::SecUtf8;

    static API_KEY: Lazy<SecUtf8> =
        Lazy::new(|| SecUtf8::from("bYZmrwdVEbHJSqeA1RfnPtKiBcXzUpRdKGRkjw9m1o1eqSGP1s6DM11CDnklpFq6"));

    #[test]
    fn dir_link_status_request_should_have_proper_contract_for_no_link() {
        let request_payload = DirLinkStatusRequestPayload {
            api_key: &API_KEY,
            uuid: Uuid::nil(),
        };
        validate_contract(
            DIR_LINK_STATUS_PATH,
            request_payload,
            "tests/resources/responses/dir_link_status_no_link.json",
            |request_payload, filen_settings| dir_link_status_request(&request_payload, &filen_settings),
        );
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn dir_link_status_request_async_should_have_proper_contract_for_no_link() {
        let request_payload = DirLinkStatusRequestPayload {
            api_key: &API_KEY,
            uuid: Uuid::nil(),
        };
        validate_contract_async(
            DIR_LINK_STATUS_PATH,
            request_payload,
            "tests/resources/responses/dir_link_status_no_link.json",
            |request_payload, filen_settings| async move {
                dir_link_status_request_async(&request_payload, &filen_settings).await
            },
        )
        .await;
    }

    #[test]
    fn dir_link_status_request_should_have_proper_contract_for_link_without_password() {
        let request_payload = DirLinkStatusRequestPayload {
            api_key: &API_KEY,
            uuid: Uuid::nil(),
        };
        validate_contract(
            DIR_LINK_STATUS_PATH,
            request_payload,
            "tests/resources/responses/dir_link_status_no_password.json",
            |request_payload, filen_settings| dir_link_status_request(&request_payload, &filen_settings),
        );
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn dir_link_status_request_async_should_have_proper_contract_for_link_without_password() {
        let request_payload = DirLinkStatusRequestPayload {
            api_key: &API_KEY,
            uuid: Uuid::nil(),
        };
        validate_contract_async(
            DIR_LINK_STATUS_PATH,
            request_payload,
            "tests/resources/responses/dir_link_status_no_password.json",
            |request_payload, filen_settings| async move {
                dir_link_status_request_async(&request_payload, &filen_settings).await
            },
        )
        .await;
    }
}