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 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
use std::collections::BTreeSet;
use std::fmt;
use std::ops::Deref;
/// Validates the name of a resource, operation, constraint, or resource path.
///
/// # Arguments
/// * `s` - A string slice that holds the name to be validated.
///
/// # Returns
/// * `Ok(())` if the name only contains valid characters (A-Z, a-z, 0-9, '_', '-').
/// * `Err(String)` if the name is empty or contains invalid characters.
///
pub fn validate_name(s: &str) -> Result<(), String> {
if s.is_empty() {
return Err("empty string".to_string());
}
for c in s.chars() {
if !matches!(c, 'A'..='Z' | 'a'..='z' | '0'..='9' | '_' | '-') {
return Err(format!("invalid character: {}", c));
}
}
Ok(())
}
/// Represents a resource within the permission model, which could be generic or specific.
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub enum Resource {
#[default]
All, // Represents all resources, denoted by "*"
File,
Folder,
Bucket,
Cluster,
Other(String),
}
impl Resource {
/// Checks if a given resource matches the current resource.
///
/// # Arguments
/// * `value` - A reference to another `Resource` to compare with.
///
/// # Returns
/// * `true` if the resources match or if the current resource represents all resources.
/// * `false` otherwise.
pub fn check(&self, value: &Resource) -> bool {
match self {
Self::All => true,
other => value == other,
}
}
}
impl fmt::Display for Resource {
/// Formats the `Resource` enum into a human-readable string.
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::All => write!(f, "*"),
Self::File => write!(f, "File"),
Self::Folder => write!(f, "Folder"),
Self::Bucket => write!(f, "Bucket"),
Self::Cluster => write!(f, "Cluster"),
Self::Other(ref s) => write!(f, "{}", s),
}
}
}
impl TryFrom<&str> for Resource {
type Error = String;
/// Attempts to create a `Resource` from a string slice.
///
/// # Arguments
/// * `value` - The string slice to parse into a `Resource`.
///
/// # Returns
/// * `Ok(Resource)` if successfully parsed.
/// * `Err(String)` if the input is invalid or does not match any known resource.
///
fn try_from(value: &str) -> Result<Self, Self::Error> {
match value {
"*" => Ok(Self::All),
"File" => Ok(Self::File),
"Folder" => Ok(Self::Folder),
"Bucket" => Ok(Self::Bucket),
"Cluster" => Ok(Self::Cluster),
_ => match validate_name(value) {
Ok(_) => Ok(Self::Other(value.to_string())),
Err(err) => Err(format!("invalid resource: {}, {}", value, err)),
},
}
}
}
/// Represents an operation that can be performed on a resource.
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub enum Operation {
#[default]
All, // Represents all operations, denoted by "*"
List,
Read,
Write,
Delete,
Other(String),
}
impl Operation {
/// Checks if a given operation matches the current operation.
///
/// # Arguments
/// * `value` - A reference to another `Operation` to compare with.
///
/// # Returns
/// * `true` if the operations match or if the current operation represents all operations.
/// * `false` otherwise.
pub fn check(&self, value: &Operation) -> bool {
match self {
Self::All => true,
other => value == other,
}
}
}
impl fmt::Display for Operation {
/// Formats the `Operation` enum into a human-readable string.
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::All => write!(f, "*"),
Self::List => write!(f, "List"),
Self::Read => write!(f, "Read"),
Self::Write => write!(f, "Write"),
Self::Delete => write!(f, "Delete"),
Self::Other(ref s) => write!(f, "{}", s),
}
}
}
impl TryFrom<&str> for Operation {
type Error = String;
/// Attempts to create an `Operation` from a string slice.
///
/// # Arguments
/// * `value` - The string slice to parse into an `Operation`.
///
/// # Returns
/// * `Ok(Operation)` if successfully parsed.
/// * `Err(String)` if the input is invalid or does not match any known operation.
///
fn try_from(value: &str) -> Result<Self, Self::Error> {
match value {
"*" => Ok(Self::All),
"List" => Ok(Self::List),
"Read" => Ok(Self::Read),
"Write" => Ok(Self::Write),
"Delete" => Ok(Self::Delete),
_ => match validate_name(value) {
Ok(_) => Ok(Self::Other(value.to_string())),
Err(err) => Err(format!("invalid operation: {}, {}", value, err)),
},
}
}
}
/// Represents a permission string in the format "Resource.Operation[.Constraint]".
///
/// # Fields
/// * `resource` - The resource to which the permission applies.
/// * `operation` - The operation allowed on the resource.
/// * `constraint` - An optional constraint on the resource.
///
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub struct Permission {
pub resource: Resource,
pub operation: Operation,
pub constraint: Option<Resource>,
}
impl Permission {
/// Checks if the permission grants unrestricted access to all resources and operations.
///
/// # Returns
/// * `true` if the permission represents all resources and operations without constraints.
/// * `false` otherwise.
///
pub fn is_all(&self) -> bool {
self.resource == Resource::All
&& self.operation == Operation::All
&& self.constraint.is_none()
}
/// Compares a given `Permission` object to the current one for a match.
///
/// # Arguments
/// * `value` - A reference to another `Permission` to compare with.
///
/// # Returns
/// * `true` if the permissions match, considering resources, operations, and constraints.
/// * `false` otherwise.
///
pub fn check(&self, value: &Permission) -> bool {
self.resource.check(&value.resource)
&& self.operation.check(&value.operation)
&& self.check_constraint(&value.constraint)
}
/// Helper method to check constraints.
///
/// # Arguments
/// * `value` - Optional reference to a `Resource` that represents the constraint.
///
/// # Returns
/// * `true` if there are no constraints or the constraints match.
/// * `false` otherwise.
///
pub fn check_constraint(&self, value: &Option<Resource>) -> bool {
match self.constraint {
None | Some(Resource::All) => true,
Some(ref c) => value.as_ref().map_or(false, |v| c == v),
}
}
}
impl fmt::Display for Permission {
/// Formats the `Permission` struct into a human-readable string, considering constraints.
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.constraint {
Some(ref c) if c != &Resource::All => {
write!(f, "{}.{}.{}", self.resource, self.operation, c)
}
_ => {
if self.is_all() {
write!(f, "*")
} else {
write!(f, "{}.{}", self.resource, self.operation)
}
}
}
}
}
impl TryFrom<&str> for Permission {
type Error = String;
/// Attempts to create a `Permission` from a string slice.
///
/// # Arguments
/// * `value` - The string slice to parse into a `Permission`.
///
/// # Returns
/// * `Ok(Permission)` if successfully parsed.
/// * `Err(String)` if the input is invalid or does not match the expected format.
///
fn try_from(value: &str) -> Result<Self, Self::Error> {
if value == "*" {
return Ok(Self {
resource: Resource::All,
operation: Operation::All,
constraint: None,
});
}
let mut parts = value.split('.');
let resource = match parts.next() {
Some(v) => Resource::try_from(v)?,
_ => return Err(format!("invalid permission format {}", value)),
};
let operation = match parts.next() {
Some(v) => Operation::try_from(v)?,
_ => return Err(format!("invalid permission format {}", value)),
};
let constraint = match parts.next() {
Some(v) => {
Some(Resource::try_from(v).map_err(|err| format!("invalid constraint: {}", err))?)
}
None => None,
};
if parts.next().is_some() {
return Err(format!("invalid permission format {}", value));
}
Ok(Self {
resource,
operation,
constraint,
})
}
}
/// Represents a resource paths.
pub type ResourcePath = String;
/// Represents a collection of resource paths.
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub struct Resources(pub BTreeSet<ResourcePath>);
impl Resources {
/// Checks if the collection represents all resources.
///
/// # Returns
/// * `true` if the collection is empty or contains the wildcard "*".
/// * `false` otherwise.
///
pub fn is_all(&self) -> bool {
self.0.is_empty() || self.0.contains("*")
}
/// Checks if a given resource path is part of the collection.
///
/// # Arguments
/// * `value` - The resource path to check.
///
/// # Returns
/// * `true` if the collection contains the resource path or represents all resources.
/// * `false` otherwise.
///
fn check<T>(&self, value: T) -> bool
where
T: AsRef<str>,
{
self.is_all() || self.0.contains(value.as_ref())
}
}
impl Deref for Resources {
type Target = BTreeSet<ResourcePath>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl AsRef<BTreeSet<ResourcePath>> for Resources {
fn as_ref(&self) -> &BTreeSet<ResourcePath> {
&self.0
}
}
impl fmt::Display for Resources {
/// Formats the `Resources` struct into a comma-separated string.
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.0.first() {
None => Ok(()),
Some(v) => {
if !self.is_all() {
write!(f, "{}", v)?;
for r in self.0.iter().skip(1) {
write!(f, ",{}", r)?;
}
}
Ok(())
}
}
}
}
impl<const N: usize> From<[ResourcePath; N]> for Resources {
fn from(val: [ResourcePath; N]) -> Self {
Self(BTreeSet::from(val))
}
}
impl TryFrom<&str> for Resources {
type Error = String;
/// Attempts to create `Resources` from a comma-separated string slice.
///
/// # Arguments
/// * `value` - The string slice to parse into `Resources`.
///
/// # Returns
/// * `Ok(Resources)` if successfully parsed.
/// * `Err(String)` if any resource name is invalid.
///
fn try_from(value: &str) -> Result<Self, Self::Error> {
match value {
"" | "*" => Ok(Self::default()),
_ => {
let rs: BTreeSet<_> = value.split(',').map(|v| v.to_string()).collect();
for r in rs.iter() {
validate_name(r)?;
}
Ok(Resources(rs))
}
}
}
}
/// A trait for checking permission on a single resource.
pub trait PermissionChecker<T> {
/// Checks if a permission is granted on a resource.
///
/// # Arguments
/// * `permission` - The permission to check.
/// * `resource_path` - The path of the resource.
///
/// # Returns
/// * `true` if the permission is granted.
/// * `false` otherwise.
fn has_permission(&self, permission: &Permission, resource_path: T) -> bool;
}
/// A trait for checking permissions on multiple resources.
pub trait PermissionCheckerAny<T> {
/// Checks if a permission is granted on any of the given resources.
///
/// # Arguments
/// * `permission` - The permission to check.
/// * `resources_path` - The paths of the resources.
///
/// # Returns
/// * `true` if the permission is granted on any of the resources.
/// * `false` otherwise.
fn has_permission_any(&self, permission: &Permission, resources_path: &[T]) -> bool;
}
/// Represents a policy string in the format "Permission:Resource1,Resource2,...".
///
/// # Fields
/// * `permission` - The permission associated with the policy.
/// * `resources` - The resources associated with the policy.
///
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub struct Policy {
pub permission: Permission,
pub resources: Resources,
}
impl<T> PermissionChecker<T> for Policy
where
T: AsRef<str>,
{
fn has_permission(&self, permission: &Permission, resource_path: T) -> bool {
self.permission.check(permission) && self.resources.check(resource_path.as_ref())
}
}
impl<T> PermissionCheckerAny<T> for Policy
where
T: AsRef<str>,
{
fn has_permission_any(&self, permission: &Permission, resources_path: &[T]) -> bool {
self.permission.check(permission)
&& (self.resources.is_all() || resources_path.iter().any(|r| self.resources.check(r)))
}
}
impl fmt::Display for Policy {
/// Formats the `Policy` struct into a human-readable string.
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.resources.is_all() {
if self.permission.is_all() {
write!(f, "*")
} else {
write!(f, "{}", self.permission)
}
} else {
write!(f, "{}:{}", self.permission, self.resources)
}
}
}
impl TryFrom<&str> for Policy {
type Error = String;
/// Attempts to create a `Policy` from a string slice.
///
/// # Arguments
/// * `value` - The string slice to parse into a `Policy`.
///
/// # Returns
/// * `Ok(Policy)` if successfully parsed.
/// * `Err(String)` if the input is invalid or does not match the expected format.
///
fn try_from(value: &str) -> Result<Self, Self::Error> {
if value == "*" {
return Ok(Self::default());
}
let mut parts = value.split(':');
let permission = match parts.next() {
Some(v) => Permission::try_from(v)?,
_ => return Err(format!("invalid policy format {}", value)),
};
let resources = match parts.next() {
Some(v) => Resources::try_from(v)?,
_ => Resources::default(),
};
if parts.next().is_some() {
return Err(format!("invalid policy format {}", value));
}
Ok(Self {
permission,
resources,
})
}
}
/// Represents a collection of policies.
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub struct Policies(pub BTreeSet<Policy>);
impl Policies {
/// Creates policies with all permissions for all resources.
///
/// # Returns
/// * `Policies` containing a policy with all permissions for all resources.
///
pub fn all() -> Self {
Self(BTreeSet::from([Policy::default()]))
}
/// Creates policies with read and list permissions for all resources.
///
/// # Returns
/// * `Policies` containing policies with read and list permissions for all resources.
///
pub fn read() -> Self {
Self(BTreeSet::from([
Policy {
permission: Permission {
resource: Resource::All,
operation: Operation::Read,
constraint: None,
},
resources: Resources::default(),
},
Policy {
permission: Permission {
resource: Resource::All,
operation: Operation::List,
constraint: None,
},
resources: Resources::default(),
},
]))
}
// TODO: compress policies
/// Appends policies to the current collection.
///
/// # Arguments
/// * `policies` - The policies to append.
///
pub fn append(&mut self, policies: &mut Policies) {
self.0.append(&mut policies.0);
}
/// Removes policies from the current collection.
///
/// # Arguments
/// * `policies` - The policies to remove.
///
pub fn remove(&mut self, policies: &Policies) {
self.0.retain(|p| !policies.0.contains(p));
}
}
impl Deref for Policies {
type Target = BTreeSet<Policy>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl AsRef<BTreeSet<Policy>> for Policies {
fn as_ref(&self) -> &BTreeSet<Policy> {
&self.0
}
}
impl<T> PermissionChecker<T> for Policies
where
T: AsRef<str>,
{
fn has_permission(&self, permission: &Permission, resource_path: T) -> bool {
self.0
.iter()
.any(|p| p.has_permission(permission, resource_path.as_ref()))
}
}
impl<T> PermissionCheckerAny<T> for Policies
where
T: AsRef<str>,
{
fn has_permission_any(&self, permission: &Permission, resources_any: &[T]) -> bool {
self.0
.iter()
.any(|p| p.has_permission_any(permission, resources_any))
}
}
impl fmt::Display for Policies {
/// Formats the `Policies` struct into a human-readable string.
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.0.first() {
None => Ok(()),
Some(v) => {
write!(f, "{}", v)?;
for r in self.0.iter().skip(1) {
write!(f, " {}", r)?;
}
Ok(())
}
}
}
}
impl<const N: usize> From<[Policy; N]> for Policies {
fn from(val: [Policy; N]) -> Self {
Self(BTreeSet::from(val))
}
}
impl TryFrom<&str> for Policies {
type Error = String;
/// Attempts to create `Policies` from a space-separated string slice.
///
/// # Arguments
/// * `value` - The string slice to parse into `Policies`.
///
/// # Returns
/// * `Ok(Policies)` if successfully parsed.
/// * `Err(String)` if any policy is invalid.
///
fn try_from(value: &str) -> Result<Self, Self::Error> {
if value.is_empty() {
return Ok(Self::default());
}
let policies = value
.split(' ')
.map(Policy::try_from)
.collect::<Result<BTreeSet<_>, _>>()?;
Ok(Policies(policies))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_validate_name() {
assert!(validate_name("").is_err());
assert!(validate_name("*").is_err());
assert!(validate_name(" ").is_err());
assert!(validate_name(".").is_err());
assert!(validate_name(",").is_err());
assert!(validate_name(".Info").is_err());
assert!(validate_name("Info").is_ok());
assert!(validate_name("123").is_ok());
assert!(validate_name("Level_1").is_ok());
assert!(validate_name("mmrxu-fqaaa-aaaap-ahhna-cai").is_ok());
}
#[test]
fn test_permission() {
for (s, p) in [
(
"Bucket.Read.Info",
Permission {
resource: Resource::Bucket,
operation: Operation::Read,
constraint: Some(Resource::Other("Info".to_string())),
},
),
(
"Bucket.Read.File",
Permission {
resource: Resource::Bucket,
operation: Operation::Read,
constraint: Some(Resource::File),
},
),
(
"SomeResource.some_operation",
Permission {
resource: Resource::Other("SomeResource".to_string()),
operation: Operation::Other("some_operation".to_string()),
constraint: None,
},
),
(
"File.Read",
Permission {
resource: Resource::File,
operation: Operation::Read,
constraint: None,
},
),
(
"File.*",
Permission {
resource: Resource::File,
operation: Operation::All,
constraint: None,
},
),
(
"*.Read",
Permission {
resource: Resource::All,
operation: Operation::Read,
constraint: None,
},
),
(
"*",
Permission {
resource: Resource::All,
operation: Operation::All,
constraint: None,
},
),
] {
assert_eq!(p.to_string(), s, "Permission({})", s);
assert_eq!(Permission::try_from(s).unwrap(), p);
}
assert!(Permission::try_from(".File").is_err());
assert!(Permission::try_from("File").is_err());
assert!(Permission::try_from("File.").is_err());
assert!(Permission::try_from("File.Read.Info.Info").is_err());
assert!(Permission::default().check(&Permission::default()));
assert!(Permission::default().check(&Permission {
resource: Resource::File,
operation: Operation::Read,
constraint: None,
}));
assert!(Permission::default().check(&Permission {
resource: Resource::Bucket,
operation: Operation::Read,
constraint: Some(Resource::File),
}));
assert!(Permission {
resource: Resource::Bucket,
operation: Operation::Read,
constraint: None,
}
.check(&Permission {
resource: Resource::Bucket,
operation: Operation::Read,
constraint: Some(Resource::Other("Info".to_string())),
}));
assert!(!Permission {
resource: Resource::Bucket,
operation: Operation::Read,
constraint: Some(Resource::Other("Info".to_string())),
}
.check(&Permission {
resource: Resource::Bucket,
operation: Operation::Read,
constraint: Some(Resource::File),
}));
assert!(!Permission {
resource: Resource::Bucket,
operation: Operation::Write,
constraint: None,
}
.check(&Permission {
resource: Resource::Bucket,
operation: Operation::Read,
constraint: None,
}));
assert!(!Permission {
resource: Resource::Folder,
operation: Operation::Write,
constraint: None,
}
.check(&Permission {
resource: Resource::File,
operation: Operation::Write,
constraint: None,
}));
}
#[test]
fn test_resources() {
let rs = Resources::default();
assert_eq!(rs.to_string(), "");
assert_eq!(Resources::try_from("").unwrap(), rs);
assert!(rs.check(""));
assert!(rs.check("123"));
assert!(rs.check("abc"));
let rs = Resources::try_from("*").unwrap();
assert!(rs.check(""));
assert!(rs.check("123"));
assert!(rs.check("abc"));
assert_eq!(rs.to_string(), "");
let rs = Resources::from(["1".to_string()]);
assert_eq!(rs.to_string(), "1");
assert_eq!(Resources::try_from("1").unwrap(), rs);
assert!(rs.check("1"));
assert!(!rs.check("2"));
assert!(!rs.check(""));
assert!(!rs.check("12"));
assert!(!rs.check("a"));
let rs = Resources::from(["1".to_string(), "2".to_string(), "3".to_string()]);
assert_eq!(rs.to_string(), "1,2,3");
assert_eq!(Resources::try_from("1,2,3").unwrap(), rs);
assert!(rs.check("1"));
assert!(rs.check("2"));
assert!(!rs.check(""));
assert!(!rs.check("12"));
assert!(!rs.check("a"));
assert!(Resources::try_from("1, 2").is_err());
assert!(Resources::try_from("1,2 ").is_err());
assert!(Resources::try_from("1,2.3").is_err());
}
#[test]
fn test_policy() {
let po = Policy::default();
assert_eq!(po.to_string(), "*");
assert_eq!(Policy::try_from("*").unwrap(), po);
assert_eq!(Policy::try_from("*:*").unwrap(), po);
assert_eq!(Policy::try_from("*.*:*").unwrap(), po);
assert!(po.has_permission(
&Permission {
resource: Resource::File,
operation: Operation::Read,
constraint: None,
},
""
));
assert!(po.has_permission(
&Permission {
resource: Resource::Folder,
operation: Operation::Write,
constraint: None,
},
"1"
));
let po = Policy {
permission: Permission {
resource: Resource::File,
operation: Operation::All,
constraint: None,
},
resources: Resources::from(["123".to_string()]),
};
assert_eq!(po.to_string(), "File.*:123");
assert_eq!(Policy::try_from("File.*:123").unwrap(), po);
assert!(po.has_permission(
&Permission {
resource: Resource::File,
operation: Operation::Read,
constraint: None,
},
"123"
));
assert!(po.has_permission(
&Permission {
resource: Resource::File,
operation: Operation::Write,
constraint: None,
},
"123"
));
assert!(!po.has_permission(
&Permission {
resource: Resource::File,
operation: Operation::Read,
constraint: None,
},
"1"
));
assert!(!po.has_permission(
&Permission {
resource: Resource::File,
operation: Operation::Write,
constraint: None,
},
"1"
));
assert!(!po.has_permission(
&Permission {
resource: Resource::Folder,
operation: Operation::Write,
constraint: None,
},
"123"
));
assert!(!po.has_permission(
&Permission {
resource: Resource::File,
operation: Operation::Write,
constraint: None,
},
""
));
}
#[test]
fn test_policies() {
let ps = Policies::default();
assert_eq!(ps.to_string(), "");
assert!(!ps.has_permission(
&Permission {
resource: Resource::File,
operation: Operation::Read,
constraint: None,
},
""
));
let ps = Policies::all();
assert_eq!(Policies::try_from("*").unwrap(), ps);
assert_eq!(Policies::try_from("*:*").unwrap(), ps);
assert_eq!(Policies::try_from("*.*:*").unwrap(), ps);
assert!(ps.has_permission(
&Permission {
resource: Resource::File,
operation: Operation::Read,
constraint: None,
},
""
));
assert!(ps.has_permission(
&Permission {
resource: Resource::File,
operation: Operation::Read,
constraint: None,
},
"123"
));
assert!(ps.has_permission(
&Permission {
resource: Resource::Bucket,
operation: Operation::Write,
constraint: Some(Resource::Folder),
},
"bucket1"
));
let ps = Policies::from([
Policy {
permission: Permission {
resource: Resource::Bucket,
operation: Operation::Read,
constraint: Some(Resource::All),
},
resources: Resources::from([]),
},
Policy {
permission: Permission {
resource: Resource::Folder,
operation: Operation::Read,
constraint: None,
},
resources: Resources::default(),
},
Policy {
permission: Permission {
resource: Resource::Folder,
operation: Operation::All,
constraint: None,
},
resources: Resources::from(["2".to_string(), "3".to_string(), "5".to_string()]),
},
Policy {
permission: Permission {
resource: Resource::File,
operation: Operation::All,
constraint: None,
},
resources: Resources::from(["1".to_string()]),
},
]);
println!("{}", ps);
let scope = "File.*:1 Folder.*:2,3,5 Folder.Read Bucket.Read";
assert_eq!(ps.to_string(), scope);
assert_eq!(Policies::try_from(scope).unwrap().to_string(), scope);
// File.*:1
assert!(ps.has_permission(
&Permission {
resource: Resource::File,
operation: Operation::Delete,
constraint: None,
},
"1"
));
// File.*:1
assert!(ps.has_permission(
&Permission {
resource: Resource::File,
operation: Operation::Read,
constraint: Some(Resource::Other("Info".to_string())),
},
"1"
));
// File.*:1
assert!(!ps.has_permission(
&Permission {
resource: Resource::File,
operation: Operation::Read,
constraint: Some(Resource::Other("Info".to_string())),
},
"2"
));
// File.*:1
assert!(ps.has_permission(
&Permission {
resource: Resource::File,
operation: Operation::All,
constraint: None,
},
"1"
));
// Folder.*:2,3,5
assert!(ps.has_permission(
&Permission {
resource: Resource::Folder,
operation: Operation::Delete,
constraint: Some(Resource::File),
},
"2"
));
// Folder.*:2,3,5
assert!(!ps.has_permission(
&Permission {
resource: Resource::Folder,
operation: Operation::Delete,
constraint: Some(Resource::File),
},
"4"
));
// Folder.*:2,3,5
assert!(ps.has_permission_any(
&Permission {
resource: Resource::Folder,
operation: Operation::Delete,
constraint: Some(Resource::File),
},
&["4", "5"]
));
assert!(ps.has_permission_any(
&Permission {
resource: Resource::Folder,
operation: Operation::Delete,
constraint: Some(Resource::File),
},
&[4.to_string(), 5.to_string()]
));
// Folder.Read
assert!(ps.has_permission(
&Permission {
resource: Resource::Folder,
operation: Operation::Read,
constraint: Some(Resource::Other("Info".to_string())),
},
"1"
));
// Folder.Read
assert!(ps.has_permission(
&Permission {
resource: Resource::Folder,
operation: Operation::Read,
constraint: Some(Resource::File),
},
"6"
));
// Bucket.Read
assert!(ps.has_permission(
&Permission {
resource: Resource::Bucket,
operation: Operation::Read,
constraint: Some(Resource::Folder),
},
"1"
));
// Bucket.Read
assert!(!ps.has_permission(
&Permission {
resource: Resource::Bucket,
operation: Operation::Write,
constraint: Some(Resource::Folder),
},
"1"
));
}
}