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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
//! Storj DCS Access Grant and bound types.
use crate::config::Config;
use crate::uplink_c::{string_from_ffi_string_result, Ensurer};
use crate::{helpers, EncryptionKey, Error, Result};
use std::ffi::CString;
use std::os::raw::c_char;
use std::time::Duration;
use std::vec::Vec;
use uplink_sys as ulksys;
/// Represents an access grant
///
/// An access grant contains everything to access a project and specific buckets.
///
/// It includes a potentially-restricted API Key, a potentially-restricted set of encryption
/// information, and information about the Satellite responsible for the project's metadata.
#[derive(Debug)]
pub struct Grant {
/// The FFI access type that an instance of this struct represents and guards its lifetime
/// until this instance drops.
///
/// It's an access result because it's the one that holds the access grant and allows to free
/// its memory.
inner: ulksys::UplinkAccessResult,
}
impl Grant {
/// Creates a new access grant from a serialized access grant string.
pub fn new(serialized_access: &str) -> Result<Self> {
let saccess = helpers::cstring_from_str_fn_arg("serialized_access", serialized_access)?;
// SAFETY: we are passing a pointer to a valid CString to the FFI.
let res = unsafe { ulksys::uplink_parse_access(saccess.as_ptr() as *mut c_char) };
Self::from_ffi_access_result(res)
}
/// Generates a new access grant using a passphrase requesting to the satellite a project-based
/// salt for deterministic key derivation.
pub fn request_access_with_passphrase(
satellite_addr: &str,
api_key: &str,
passphrase: &str,
) -> Result<Self> {
let satellite_addr = helpers::cstring_from_str_fn_arg("satellite_addr", satellite_addr)?;
let api_key = helpers::cstring_from_str_fn_arg("api_key", api_key)?;
let passphrase = helpers::cstring_from_str_fn_arg("passphrase", passphrase)?;
// SAFETY: it's safe to pass this strings to the FFI function because it makes copies of it
// to return the result so the result will still valid when the call to this method ends
// which is when those strings will be dropped.
let res = unsafe {
ulksys::uplink_request_access_with_passphrase(
satellite_addr.as_ptr() as *mut c_char,
api_key.as_ptr() as *mut c_char,
passphrase.as_ptr() as *mut c_char,
)
};
Self::from_ffi_access_result(res)
}
/// Generates a new access grant using the configuration and the specific satellite address, API
/// key, and passphrase.
/// It connects to the satellite address for getting a project-based salt for deterministic key
/// derivation.
///
/// NOTE: this is a CPU-heavy operation that uses a password-based key derivation (Argon2). It
/// should be a setup-only step. Most common interactions with the library should be using a
/// serialized access grant through [`Grant::new()`](../access/struct.Grant.html#.method.new).
pub fn request_access_with_config_and_passphrase(
config: &Config,
satellite_addr: &str,
api_key: &str,
passphrase: &str,
) -> Result<Self> {
let satellite_addr = helpers::cstring_from_str_fn_arg("satellite_addr", satellite_addr)?;
let api_key = helpers::cstring_from_str_fn_arg("api_key", api_key)?;
let passphrase = helpers::cstring_from_str_fn_arg("passphrase", passphrase)?;
// SAFETY: it's safe to pass this strings to the FFI function because it makes copies of it
// to return the result so the result will still valid when the call to this method ends
// which is when those strings will be dropped.
let res = unsafe {
*ulksys::uplink_config_request_access_with_passphrase(
config.as_ffi_config(),
satellite_addr.as_ptr() as *mut c_char,
api_key.as_ptr() as *mut c_char,
passphrase.as_ptr() as *mut c_char,
)
.ensure()
};
Self::from_ffi_access_result(res)
}
/// Creates a Grant instance from the FFI type.
///
/// An [`Error::new_uplink` constructor](crate::Error::new_uplink), if `ffi_result` contains a
/// non `NULL` pointer in the `error` field.
fn from_ffi_access_result(ffi_result: ulksys::UplinkAccessResult) -> Result<Self> {
ffi_result.ensure();
Error::new_uplink(ffi_result.error).map_or(Ok(Grant { inner: ffi_result }), |err| {
// SAFETY: FFI free function doesn't free if the result fields are `NULL` and this
// result should only be instantiated through the same FFI.
unsafe { ulksys::uplink_free_access_result(ffi_result) };
Err(err)
})
}
/// Overrides the root encryption key for the prefix in bucket with the encryption key.
/// `prefix` must end with slash (i.e. `/`), otherwise it returns an error.
///
/// This method is useful for overriding the encryption key in user-specific access grants when
/// implementing multitenancy in a single app bucket.
/// See relevant information in the general crate documentation.
pub fn override_encryption_key(
&self,
bucket: &str,
prefix: &str,
encryption_key: &EncryptionKey,
) -> Result<()> {
let bucket = helpers::cstring_from_str_fn_arg("bucket", bucket)?;
let prefix = helpers::cstring_from_str_fn_arg("prefix", prefix)?;
// SAFETY: it's safe to pass this strings to the FFI function because it makes copies of it
// to return the result so the result will still valid after the call to this method ends
// which is when those strings will be dropped.
let uc_err = unsafe {
ulksys::uplink_access_override_encryption_key(
self.inner.access,
bucket.as_ptr() as *mut c_char,
prefix.as_ptr() as *mut c_char,
encryption_key.as_ffi_encryption_key(),
)
};
Error::new_uplink(uc_err).map_or(Ok(()), |err| {
helpers::drop_uplink_sys_error(uc_err);
Err(err)
})
}
/// Returns the satellite node URL associated with this access grant.
pub fn satellite_address(&self) -> Result<String> {
// SAFETY: we have checked that the FFI value attached to this instance is valid at its
// construction time.
let res = unsafe { ulksys::uplink_access_satellite_address(self.inner.access) };
string_from_ffi_string_result(res)
}
/// Serializes an access grant such that it can be used to create a [`Self::new()`] instance of
/// this type or parsed with other tools.
pub fn serialize(&self) -> Result<String> {
// SAFETY: we have checked that the FFI value attached to this instance is valid at its
// construction time.
let res = unsafe { ulksys::uplink_access_serialize(self.inner.access) };
string_from_ffi_string_result(res)
}
/// Creates a new access grant with specific permissions.
///
/// An access grant can only have their existing permissions restricted, and the resulting
/// access will only allow for the intersection of all previous share calls in the access
/// construction chain.
///
/// Prefixes restrict the access grant (and internal encryption information) to only contain
/// enough information to allow access to just those prefixes.
///
/// To revoke an access grant see [`Project.revoke_access()`](../project/struct.Project.html#method.revoke_access).
pub fn share(
&self,
permission: &Permission,
prefixes: Option<Vec<SharePrefix>>,
) -> Result<Grant> {
let res;
if let Some(prefix_list) = prefixes {
let mut ulk_prefixes: Vec<ulksys::UplinkSharePrefix> =
Vec::with_capacity(prefix_list.len());
for sp in &prefix_list {
ulk_prefixes.push(sp.as_ffi_share_prefix());
}
// SAFETY: it's safe to pass the vector to the FFI function because it makes copies of it
// to return the result so the result will still valid when the call to this method ends
// which is when the vector will be dropped.
res = unsafe {
*ulksys::uplink_access_share(
self.inner.access,
permission.as_ffi_permissions(),
ulk_prefixes.as_mut_ptr(),
ulk_prefixes.len() as i64,
)
.ensure()
};
} else {
// SAFETY: it's safe to pass nil to the FFI function to indicate that there isn't any
// prefix restriction.
res = unsafe {
*ulksys::uplink_access_share(
self.inner.access,
permission.as_ffi_permissions(),
std::ptr::null_mut(),
0,
)
.ensure()
};
}
Self::from_ffi_access_result(res)
}
/// Returns the FFI representation of this access grant.
pub(crate) fn as_ffi_access(&self) -> *mut ulksys::UplinkAccess {
self.inner.access
}
}
impl Drop for Grant {
fn drop(&mut self) {
// SAFETY: this type implementation guarantees that the FFI value since an instance is
// created until it's dropped.
unsafe { ulksys::uplink_free_access_result(self.inner) };
}
}
/// Represents a prefix to be shared.
#[derive(Debug)]
pub struct SharePrefix<'a> {
bucket: &'a str,
c_bucket: CString,
prefix: &'a str,
c_prefix: CString,
}
impl<'a> SharePrefix<'a> {
/// Create a new prefix to be shared in the specified bucket.
/// It returns an error if bucket or prefix contains a null character (0 byte).
pub fn new(bucket: &'a str, prefix: &'a str) -> Result<Self> {
let c_bucket = helpers::cstring_from_str_fn_arg("bucket", bucket)?;
let c_prefix = helpers::cstring_from_str_fn_arg("prefix", prefix)?;
Ok(SharePrefix {
bucket,
c_bucket,
prefix,
c_prefix,
})
}
/// Create a new share prefix that shares all the content of the bucket.
/// It returns an error if bucket contains a null character (0 byte).
pub fn full_bucket(bucket: &'a str) -> Result<Self> {
Self::new(bucket, "")
}
/// Returns the bucket where the prefix to be shared belongs.
pub fn bucket(&self) -> &str {
self.bucket
}
/// Returns the actual prefix to be shared.
pub fn prefix(&self) -> &str {
self.prefix
}
/// Returns the FFI representation of share prefix.
fn as_ffi_share_prefix(&self) -> ulksys::UplinkSharePrefix {
ulksys::UplinkSharePrefix {
bucket: self.c_bucket.as_ptr(),
prefix: self.c_prefix.as_ptr(),
}
}
}
/// Defines what actions and an optional specific period of time are granted to a shared access
/// grant.
///
/// A shared access grant can never has more permission that its parent, hence even some allowed
/// permission is set for the shared access Grant but not to its parent, the shared access Grant
/// won't be allowed. shared access Grant wont See
/// [`Grant.share()`](struct.Grant.html#method.share).
#[derive(Default)]
pub struct Permission {
/// Gives permission to download the content of the objects and their associated metadata, but
/// it does not allow listing buckets.
pub allow_download: bool,
/// Gives permission to create buckets and upload new objects. It does not allow overwriting
/// existing objects unless allow_delete is granted too.
pub allow_upload: bool,
/// Gives permission to list buckets and getting the metadata of the objects. It does not allow
/// downloading the content of the objects.
pub allow_list: bool,
/// Gives permission to delete buckets and objects. Unless either allow `allow_download` or
/// `allow_list` is grated too, neither the metadata of the objects nor error information will
/// be returned for deleted objects.
pub allow_delete: bool,
/// Restricts when the resulting access grant is valid for. If it is set then it must always be
/// before not_after and the resulting access grant will not work if the satellite believes the
/// time is before the set it one.
///
/// The time is measured with the number of seconds since the Unix Epoch time.
not_before: Option<Duration>,
/// Restricts when the resulting access grant is valid for. If it is set then it must always be
/// after not_before and the resulting access grant will not work if the satellite believes the
/// time is after the set it one.
///
/// The time is measured with the number of seconds since the Unix Epoch
/// time.
not_after: Option<Duration>,
}
impl Permission {
/// Creates a permission that doesn't allow any operation, which is the default permission.
/// This constructor is useful for creating a permission for after setting the specific allowed
/// operations when none of the other constructors creates a permission with a set of allowed
/// operations that works for your use case.
pub fn new() -> Permission {
Permission {
..Default::default()
}
}
/// Creates a permission that allows all the operations (i.e. Downloading, uploading, listing
/// and deleting).
pub fn full() -> Permission {
Permission {
allow_download: true,
allow_upload: true,
allow_list: true,
allow_delete: true,
not_before: None,
not_after: None,
}
}
/// Creates a permission that allows for reading (i.e. Downloading) and listing.
pub fn read_only() -> Permission {
Permission {
allow_download: true,
allow_upload: false,
allow_list: true,
allow_delete: false,
not_before: None,
not_after: None,
}
}
/// Creates a permission that allows for writing (i.e. Uploading) and deleting.
pub fn write_only() -> Permission {
Permission {
allow_download: false,
allow_upload: true,
allow_list: false,
allow_delete: true,
not_before: None,
not_after: None,
}
}
/// Returns the duration from Unix Epoch time since this permission is valid.
/// Return `None` when there is not before restriction.
pub fn not_before(&self) -> Option<Duration> {
self.not_before
}
/// Sets a not before valid time for this permission or removing it when `None` is passed.
/// An error is returned if since is more recent or equal to the current not after valid time of
/// the permission, when not after is set. The time is measured with the number of seconds since
/// the Unix Epoch time.
pub fn set_not_before(&mut self, since: Option<Duration>) -> Result<()> {
if let Some(since) = since {
if let Some(until) = self.not_after {
if since >= until {
return Err(
Error::new_invalid_arguments(
"since",
"cannot be more recent or equal to the not after valid time of the permission",
));
}
}
}
self.not_before = since;
Ok(())
}
/// Returns the duration from Unix Epoch time until this permission is valid.
/// Return `None` when there is not after restriction.
pub fn not_after(&self) -> Option<Duration> {
self.not_after
}
/// Sets a not after valid time for this permission or removing it when `None` is passed.
///
/// An error is returned if until is previous or equal to the current not before valid time of
/// the permission, when not before is set.
///
/// The time is measured with the number of seconds since the Unix Epoch time.
pub fn set_not_after(&mut self, until: Option<Duration>) -> Result<()> {
if let Some(until) = until {
if let Some(since) = self.not_before {
if until <= since {
return Err(
Error::new_invalid_arguments(
"until",
"cannot be previous or equal to the not before valid time of the permission",
));
}
}
}
self.not_after = until;
Ok(())
}
/// Returns the FFI representation of this permissions.
fn as_ffi_permissions(&self) -> ulksys::UplinkPermission {
ulksys::UplinkPermission {
allow_download: self.allow_download,
allow_upload: self.allow_upload,
allow_list: self.allow_list,
allow_delete: self.allow_delete,
not_before: self.not_before.map_or(0, |d| d.as_secs()) as i64,
not_after: self.not_after.map_or(0, |d| d.as_secs()) as i64,
}
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::error;
/*** Grant tests ***/
#[test]
fn test_grant_new_invalid_param() {
if let Error::InvalidArguments(error::Args { names, msg }) = Grant::new("serialized\0")
.expect_err("when passing an serialized access grant with NULL bytes")
{
assert_eq!(names, "serialized_access", "invalid error argument name");
assert_eq!(
msg, "cannot contains null bytes (0 byte). Null byte found at 10",
"invalid error argument message"
);
} else {
panic!("expected an invalid argument error");
}
}
#[test]
fn test_grant_request_access_with_passphrase_invalid_params() {
{
// Invalid satelite address.
if let Error::InvalidArguments(error::Args { names, msg }) =
Grant::request_access_with_passphrase("localh\0st", "some-key", "pass")
.expect_err("when passing an satellite address with NULL bytes")
{
assert_eq!(names, "satellite_addr", "invalid error argument name");
assert_eq!(
msg, "cannot contains null bytes (0 byte). Null byte found at 6",
"invalid error argument message"
);
} else {
panic!("expected an invalid argument error");
}
}
{
// Invalid API Key.
if let Error::InvalidArguments(error::Args { names, msg }) =
Grant::request_access_with_passphrase("localhost", "s\0me-key", "pass")
.expect_err("when passing an API key with NULL bytes")
{
assert_eq!(names, "api_key", "invalid error argument name");
assert_eq!(
msg, "cannot contains null bytes (0 byte). Null byte found at 1",
"invalid error argument message"
);
} else {
panic!("expected an invalid argument error");
}
}
{
// Invalid passphrase.
if let Error::InvalidArguments(error::Args { names, msg }) =
Grant::request_access_with_passphrase("localhost", "some-key", "pass\0")
.expect_err("when passing an passphrase with NULL bytes")
{
assert_eq!(names, "passphrase", "invalid error argument name");
assert_eq!(
msg, "cannot contains null bytes (0 byte). Null byte found at 4",
"invalid error argument message"
);
} else {
panic!("expected an invalid argument error");
}
}
}
#[test]
fn test_grant_request_access_with_config_and_passphrase_invalid_params() {
{
// Invalid satelite address.
let config = Config::new("rust-uplink", Duration::new(1, 0), None)
.expect("new shouldn't fail when 'user agent' doesn't contain ny nul character");
if let Error::InvalidArguments(error::Args { names, msg }) =
Grant::request_access_with_config_and_passphrase(
&config,
"localh\0st",
"some-key",
"pass",
)
.expect_err("when passing an satellite address with NULL bytes")
{
assert_eq!(names, "satellite_addr", "invalid error argument name");
assert_eq!(
msg, "cannot contains null bytes (0 byte). Null byte found at 6",
"invalid error argument message"
);
} else {
panic!("expected an invalid argument error");
}
}
{
// Invalid API Key.
let config = Config::new("rust-uplink", Duration::new(1, 0), None)
.expect("new shouldn't fail when 'user agent' doesn't contain ny nul character");
if let Error::InvalidArguments(error::Args { names, msg }) =
Grant::request_access_with_config_and_passphrase(
&config,
"localhost",
"s\0me-key",
"pass",
)
.expect_err("when passing an API key with NULL bytes")
{
assert_eq!(names, "api_key", "invalid error argument name");
assert_eq!(
msg, "cannot contains null bytes (0 byte). Null byte found at 1",
"invalid error argument message"
);
} else {
panic!("expected an invalid argument error");
}
}
{
// Invalid passphrase.
let config = Config::new("rust-uplink", Duration::new(1, 0), None)
.expect("new shouldn't fail when 'user agent' doesn't contain ny nul character");
if let Error::InvalidArguments(error::Args { names, msg }) =
Grant::request_access_with_config_and_passphrase(
&config,
"localhost",
"some-key",
"pass\0",
)
.expect_err("when passing a passphrase with NULL bytes")
{
assert_eq!(names, "passphrase", "invalid error argument name");
assert_eq!(
msg, "cannot contains null bytes (0 byte). Null byte found at 4",
"invalid error argument message"
);
} else {
panic!("expected an invalid argument error");
}
}
}
#[test]
fn test_grant_override_encryption_key() {
// This access grant is invalidated so it isn't leaking any valid access grant.
let grant = Grant::new("15kvZYL7aMhTXFU6vne8iedGfvvZdcbaDLAZ9SiN1yChpAYupdDw3SMfyHqA7pETdFjhe8SnjLox4tnq5hYbZWfCm443kv3fWV8ZWNkKwaq1mbrmyz3pPd1WSxiJn2g5tYKWoPpzvG1ygjDaB4yEq9zdpYSaH5DiVHrbaWmq6mCwRrnEF1ANdVcA2gXNbFpmSKp2i59fA14RRdZYVTrvY6rWKyG35p35eenp3ePyjwoXNSe9Cs8KvMRteVcozNiMwwuYCm4ExwP8os5Eqydqwjpx8ic8hnirkn7ThBbLLAtJBLtu").expect("valid serialized access grant");
let enc_key = EncryptionKey::derive("Rust test", &[0]).expect("derive encryption key");
{
// Valid arguments.
grant
.override_encryption_key("a-bucket", "prefix/", &enc_key)
.expect("when passing a valid bucket and prefix");
}
{
// Invalid prefix, it doesn't ends with `/`.
match grant
.override_encryption_key("a-bucket", "prefix", &enc_key)
.expect_err("when passing a prefix without ending with slash")
{
Error::Uplink(error::Uplink::Internal(_)) => {}
_ => panic!("expected an Uplink error"),
}
}
{
// Invalid bucket.
if let Error::InvalidArguments(error::Args { names, msg }) = grant
.override_encryption_key("\0a-bucket", "prefix", &enc_key)
.expect_err("when passing a bucket name with NULL bytes")
{
assert_eq!(names, "bucket", "invalid error argument name");
assert_eq!(
msg, "cannot contains null bytes (0 byte). Null byte found at 0",
"invalid error argument message"
);
} else {
panic!("expected an invalid argument error");
}
}
{
// Invalid prefix.
if let Error::InvalidArguments(error::Args { names, msg }) = grant
.override_encryption_key("a-bucket", "pre\0fix", &enc_key)
.expect_err("when passing a bucket name with NULL bytes")
{
assert_eq!(names, "prefix", "invalid error argument name");
assert_eq!(
msg, "cannot contains null bytes (0 byte). Null byte found at 3",
"invalid error argument message"
);
} else {
panic!("expected an invalid argument error");
}
}
}
/*** SharePrefix tests ***/
#[test]
fn test_share_prefix() {
{
// Pass a valid bucket and prefix.
let sp = SharePrefix::new("a-bucket", "a/b/c")
.expect("new shouldn't fail when passing a valid bucket and prefix");
assert_eq!(sp.bucket(), "a-bucket", "bucket");
assert_eq!(sp.prefix(), "a/b/c", "prefix");
}
{
// Pass an invalid bucket.
if let Error::InvalidArguments(error::Args { names, msg }) =
SharePrefix::new("a\0bucket\0", "a/b/c")
.expect_err("new passing a bucket with NULL bytes")
{
assert_eq!(names, "bucket", "invalid error argument name");
assert_eq!(
msg, "cannot contains null bytes (0 byte). Null byte found at 1",
"invalid error argument message"
);
} else {
panic!("expected an invalid argument error");
}
}
{
// Pass an invalid prefix.
if let Error::InvalidArguments(error::Args { names, msg }) =
SharePrefix::new("a-bucket", "a/b\0/c")
.expect_err("new passing a prefix with NULL bytes")
{
assert_eq!(names, "prefix", "invalid error argument name");
assert_eq!(
msg, "cannot contains null bytes (0 byte). Null byte found at 3",
"invalid error argument message"
);
} else {
panic!("expected an invalid argument error");
}
}
{
// Pass an invalid bucket and prefix.
if let Error::InvalidArguments(error::Args { names, msg }) =
SharePrefix::new("a\0bucket", "a/b\0/c")
.expect_err("new passing a bucket and prefix with NULL bytes")
{
assert_eq!(names, "bucket", "invalid error argument name");
assert_eq!(
msg, "cannot contains null bytes (0 byte). Null byte found at 1",
"invalid error argument message"
);
} else {
panic!("expected an invalid argument error");
}
}
}
/*** Permission tests ***/
#[test]
fn test_permission_default() {
let perm = Permission::new();
assert!(!perm.allow_download, "allow download");
assert!(!perm.allow_upload, "allow upload");
assert!(!perm.allow_list, "allow list");
assert!(!perm.allow_delete, "allow delete");
assert_eq!(perm.not_before(), None, "not before");
assert_eq!(perm.not_after(), None, "not after");
}
#[test]
fn test_permission_full() {
let perm = Permission::full();
assert!(perm.allow_download, "allow download");
assert!(perm.allow_upload, "allow upload");
assert!(perm.allow_list, "allow list");
assert!(perm.allow_delete, "allow delete");
assert_eq!(perm.not_before(), None, "not before");
assert_eq!(perm.not_after(), None, "not after");
}
#[test]
fn test_permission_read_only() {
let perm = Permission::read_only();
assert!(perm.allow_download, "allow download");
assert!(!perm.allow_upload, "allow upload");
assert!(perm.allow_list, "allow list");
assert!(!perm.allow_delete, "allow delete");
assert_eq!(perm.not_before(), None, "not before");
assert_eq!(perm.not_after(), None, "not after");
}
#[test]
fn test_permission_write_only() {
let perm = Permission::write_only();
assert!(!perm.allow_download, "allow download");
assert!(perm.allow_upload, "allow upload");
assert!(!perm.allow_list, "allow list");
assert!(perm.allow_delete, "allow delete");
assert_eq!(perm.not_before(), None, "not before");
assert_eq!(perm.not_after(), None, "not after");
}
#[test]
fn test_permission_time_boundaries() {
let mut perm = Permission::full();
assert_eq!(perm.not_before(), None, "not before");
assert_eq!(perm.not_after(), None, "not after");
// set not before and after without violating their constraints.
{
perm.set_not_before(Some(Duration::new(5, 50)))
.expect("set not before");
assert_eq!(
perm.not_before(),
Some(Duration::new(5, 50)),
"set not before"
);
perm.set_not_after(Some(Duration::new(5, 51)))
.expect("set not after");
assert_eq!(
perm.not_after(),
Some(Duration::new(5, 51)),
"set not after"
);
}
// set not before violating its constraints.
{
if let Error::InvalidArguments(error::Args { names, msg }) = perm
.set_not_before(Some(Duration::new(5, 52)))
.expect_err("set not before")
{
assert_eq!(names, "since", "invalid error argument name");
assert_eq!(
msg,
"cannot be more recent or equal to the not after valid time of the permission",
"invalid error argument message"
);
} else {
panic!("expected an invalid argument error");
}
}
// set not after violating its constraints.
{
if let Error::InvalidArguments(error::Args { names, msg }) = perm
.set_not_after(Some(Duration::new(5, 50)))
.expect_err("set not after")
{
assert_eq!(names, "until", "invalid error argument name");
assert_eq!(
msg,
"cannot be previous or equal to the not before valid time of the permission",
"invalid error argument message"
);
} else {
panic!("expected an invalid argument error");
}
}
// removing not before and after
{
perm.set_not_before(None).expect("set not before");
assert_eq!(perm.not_before(), None, "removing not before");
perm.set_not_after(None).expect("set not after");
assert_eq!(perm.not_after(), None, "removing not after");
}
}
}