footing 0.1.0

Feature-gated foundations for Rust backend services
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
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
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
use std::{borrow::Cow, fmt};

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::result::{ClassifyError, ErrorKind};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
#[serde(rename_all = "snake_case")]
/// Classification of principal.
pub enum PrincipalKind {
    /// Indicates user.
    User,
    /// Indicates client.
    Client,
    /// Indicates service account.
    ServiceAccount,
}

#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "PrincipalWire")]
/// Represents principal.
pub struct Principal {
    id: String,
    kind: PrincipalKind,
    tenant_id: Option<String>,
    roles: Vec<String>,
    scopes: Vec<String>,
}

impl fmt::Debug for Principal {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Principal")
            .field("id", &"[REDACTED]")
            .field("kind", &self.kind)
            .field("tenant_id", &self.tenant_id.as_ref().map(|_| "[REDACTED]"))
            .field("role_count", &self.roles.len())
            .field("scope_count", &self.scopes.len())
            .finish()
    }
}

const MAX_PRINCIPAL_IDENTIFIER_LENGTH: usize = 256;
const MAX_AUTHORITY_LENGTH: usize = 128;
const MAX_PERMISSION_PART_LENGTH: usize = 256;

impl Principal {
    /// Creates a new instance.
    pub fn new(id: impl Into<String>, kind: PrincipalKind) -> Result<Self, PermissionError> {
        Ok(Self {
            id: normalize_principal_identifier(id, "principal id")?,
            kind,
            tenant_id: None,
            roles: Vec::new(),
            scopes: Vec::new(),
        })
    }

    /// Creates user.
    pub fn user(id: impl Into<String>) -> Result<Self, PermissionError> {
        Self::new(id, PrincipalKind::User)
    }

    /// Creates client.
    pub fn client(id: impl Into<String>) -> Result<Self, PermissionError> {
        Self::new(id, PrincipalKind::Client)
    }

    /// Creates service account.
    pub fn service_account(id: impl Into<String>) -> Result<Self, PermissionError> {
        Self::new(id, PrincipalKind::ServiceAccount)
    }

    /// Configures tenant identifier and returns the updated value.
    pub fn with_tenant_id(mut self, tenant_id: impl Into<String>) -> Result<Self, PermissionError> {
        self.tenant_id = normalize_optional_principal_identifier(tenant_id, "tenant id")?;
        Ok(self)
    }

    /// Configures roles and returns the updated value.
    pub fn with_roles(
        mut self,
        roles: impl IntoIterator<Item = impl Into<String>>,
    ) -> Result<Self, PermissionError> {
        self.roles = normalize_authority_values(roles)?;
        Ok(self)
    }

    /// Configures scopes and returns the updated value.
    pub fn with_scopes(
        mut self,
        scopes: impl IntoIterator<Item = impl Into<String>>,
    ) -> Result<Self, PermissionError> {
        self.scopes = normalize_authority_values(scopes)?;
        Ok(self)
    }

    /// Adds role.
    pub fn add_role(&mut self, role: impl Into<String>) -> Result<(), PermissionError> {
        push_unique(&mut self.roles, normalize_authority_value(role)?);
        Ok(())
    }

    /// Adds scope.
    pub fn add_scope(&mut self, scope: impl Into<String>) -> Result<(), PermissionError> {
        push_unique(&mut self.scopes, normalize_authority_value(scope)?);
        Ok(())
    }

    /// Removes role.
    pub fn remove_role(&mut self, role: &str) -> bool {
        let role = role.trim();
        let previous_len = self.roles.len();
        self.roles.retain(|item| item != role);
        self.roles.len() != previous_len
    }

    /// Removes scope.
    pub fn remove_scope(&mut self, scope: &str) -> bool {
        let scope = scope.trim();
        let previous_len = self.scopes.len();
        self.scopes.retain(|item| item != scope);
        self.scopes.len() != previous_len
    }

    /// Clears roles.
    pub fn clear_roles(&mut self) {
        self.roles.clear();
    }

    /// Clears scopes.
    pub fn clear_scopes(&mut self) {
        self.scopes.clear();
    }

    #[must_use]
    /// Returns the identifier.
    pub fn id(&self) -> &str {
        &self.id
    }

    #[must_use]
    /// Returns the kind.
    pub const fn kind(&self) -> PrincipalKind {
        self.kind
    }

    #[must_use]
    /// Returns the tenant identifier.
    pub fn tenant_id(&self) -> Option<&str> {
        self.tenant_id.as_deref()
    }

    #[must_use]
    /// Returns the roles.
    pub fn roles(&self) -> &[String] {
        &self.roles
    }

    #[must_use]
    /// Returns the scopes.
    pub fn scopes(&self) -> &[String] {
        &self.scopes
    }

    #[must_use]
    /// Returns whether this value has role.
    pub fn has_role(&self, role: &str) -> bool {
        let role = role.trim();
        if role.is_empty() {
            return false;
        }

        self.roles.iter().any(|item| item == role)
    }

    #[must_use]
    /// Returns whether this value has any role.
    pub fn has_any_role<'a>(&self, roles: impl IntoIterator<Item = &'a str>) -> bool {
        roles.into_iter().any(|role| self.has_role(role))
    }

    #[must_use]
    /// Returns whether this value has all roles.
    pub fn has_all_roles<'a>(&self, roles: impl IntoIterator<Item = &'a str>) -> bool {
        let mut roles = roles.into_iter().peekable();
        roles.peek().is_some() && roles.all(|role| self.has_role(role))
    }

    #[must_use]
    /// Returns whether this value has scope.
    pub fn has_scope(&self, scope: &str) -> bool {
        let scope = scope.trim();
        if scope.is_empty() {
            return false;
        }

        self.scopes
            .iter()
            .any(|item| item == scope || item == "*" || scope_matches(item, scope))
    }

    #[must_use]
    /// Returns whether this value has any scope.
    pub fn has_any_scope<'a>(&self, scopes: impl IntoIterator<Item = &'a str>) -> bool {
        scopes.into_iter().any(|scope| self.has_scope(scope))
    }

    #[must_use]
    /// Returns whether this value has all scopes.
    pub fn has_all_scopes<'a>(&self, scopes: impl IntoIterator<Item = &'a str>) -> bool {
        let mut scopes = scopes.into_iter().peekable();
        scopes.peek().is_some() && scopes.all(|scope| self.has_scope(scope))
    }

    #[must_use]
    /// Returns whether this value is user.
    pub fn is_user(&self) -> bool {
        self.kind == PrincipalKind::User
    }

    #[must_use]
    /// Returns whether this value is client.
    pub fn is_client(&self) -> bool {
        self.kind == PrincipalKind::Client
    }

    #[must_use]
    /// Returns whether this value is service account.
    pub fn is_service_account(&self) -> bool {
        self.kind == PrincipalKind::ServiceAccount
    }
}

#[derive(Deserialize)]
struct PrincipalWire {
    id: String,
    kind: PrincipalKind,
    #[serde(default)]
    tenant_id: Option<String>,
    #[serde(default)]
    roles: Vec<String>,
    #[serde(default)]
    scopes: Vec<String>,
}

impl TryFrom<PrincipalWire> for Principal {
    type Error = PermissionError;

    fn try_from(value: PrincipalWire) -> Result<Self, Self::Error> {
        let mut principal = Self::new(value.id, value.kind)?;
        if let Some(tenant_id) = value.tenant_id {
            principal = principal.with_tenant_id(tenant_id)?;
        }

        principal.with_roles(value.roles)?.with_scopes(value.scopes)
    }
}

fn scope_matches(granted: &str, required: &str) -> bool {
    granted.strip_suffix(":*").is_some_and(|prefix| {
        required
            .strip_prefix(prefix)
            .is_some_and(|suffix| suffix.starts_with(':'))
    })
}

fn push_unique(items: &mut Vec<String>, value: String) {
    if !items.iter().any(|item| item == &value) {
        items.push(value);
    }
}

fn normalize(value: impl Into<String>) -> String {
    value.into().trim().to_owned()
}

fn normalize_principal_identifier(
    value: impl Into<String>,
    field: &'static str,
) -> Result<String, PermissionError> {
    let value = normalize(value);
    validate_principal_identifier(&value, field)?;
    Ok(value)
}

fn normalize_optional_principal_identifier(
    value: impl Into<String>,
    field: &'static str,
) -> Result<Option<String>, PermissionError> {
    let value = normalize(value);
    if value.is_empty() {
        return Ok(None);
    }

    validate_principal_identifier(&value, field)?;
    Ok(Some(value))
}

fn validate_principal_identifier(value: &str, field: &'static str) -> Result<(), PermissionError> {
    if value.is_empty() {
        return Err(PermissionError::InvalidPrincipal(format!(
            "{field} must not be empty"
        )));
    }

    if value.len() > MAX_PRINCIPAL_IDENTIFIER_LENGTH {
        return Err(PermissionError::InvalidPrincipal(format!(
            "{field} must not exceed {MAX_PRINCIPAL_IDENTIFIER_LENGTH} bytes"
        )));
    }

    if value.chars().any(char::is_whitespace) || value.chars().any(char::is_control) {
        return Err(PermissionError::InvalidPrincipal(format!(
            "{field} must not contain whitespace or control characters"
        )));
    }

    Ok(())
}

fn normalize_authority_value(value: impl Into<String>) -> Result<String, PermissionError> {
    let value = normalize(value);
    validate_authority(&value).map_err(PermissionError::InvalidAuthority)?;
    Ok(value)
}

fn normalize_authority_values(
    values: impl IntoIterator<Item = impl Into<String>>,
) -> Result<Vec<String>, PermissionError> {
    let mut normalized = Vec::new();
    for value in values {
        push_unique(&mut normalized, normalize_authority_value(value)?);
    }
    Ok(normalized)
}

fn normalize_policy_authority(
    value: impl Into<String>,
    name: &'static str,
) -> Result<String, PermissionError> {
    let value = normalize(value);
    validate_authority(&value).map_err(|message| {
        PermissionError::InvalidPolicy(format!("{name} is invalid: {message}"))
    })?;
    Ok(value)
}

fn normalize_policy_authorities(
    values: impl IntoIterator<Item = impl Into<String>>,
    name: &'static str,
) -> Result<Vec<String>, PermissionError> {
    let mut normalized = Vec::new();
    for value in values {
        push_unique(&mut normalized, normalize_policy_authority(value, name)?);
    }

    if normalized.is_empty() {
        return Err(PermissionError::InvalidPolicy(format!(
            "{name} requires at least one value"
        )));
    }

    Ok(normalized)
}

fn validate_authority(value: &str) -> Result<(), String> {
    if value.is_empty() {
        return Err("must not be empty".to_owned());
    }

    if value.len() > MAX_AUTHORITY_LENGTH {
        return Err(format!("must not exceed {MAX_AUTHORITY_LENGTH} bytes"));
    }

    if value.chars().any(char::is_whitespace) || value.chars().any(char::is_control) {
        return Err("must not contain whitespace or control characters".to_owned());
    }

    Ok(())
}

fn normalize_permission_part(
    value: impl Into<String>,
    field: &'static str,
) -> Result<String, PermissionError> {
    let value = normalize(value);
    if value.is_empty() {
        return Err(PermissionError::InvalidPolicy(format!(
            "{field} must not be empty"
        )));
    }

    if value.len() > MAX_PERMISSION_PART_LENGTH {
        return Err(PermissionError::InvalidPolicy(format!(
            "{field} must not exceed {MAX_PERMISSION_PART_LENGTH} bytes"
        )));
    }

    if value.chars().any(char::is_control) {
        return Err(PermissionError::InvalidPolicy(format!(
            "{field} must not contain control characters"
        )));
    }

    Ok(value)
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "PermissionRequestWire")]
/// A request describing permission.
pub struct PermissionRequest {
    action: String,
    resource: String,
}

impl PermissionRequest {
    /// Creates a new instance.
    pub fn new(
        action: impl Into<String>,
        resource: impl Into<String>,
    ) -> Result<Self, PermissionError> {
        let action = normalize_permission_part(action, "permission action")?;
        let resource = normalize_permission_part(resource, "permission resource")?;

        Ok(Self { action, resource })
    }

    #[must_use]
    /// Returns the action.
    pub fn action(&self) -> &str {
        &self.action
    }

    #[must_use]
    /// Returns the resource.
    pub fn resource(&self) -> &str {
        &self.resource
    }
}

#[derive(Debug, Deserialize)]
struct PermissionRequestWire {
    action: String,
    resource: String,
}

impl TryFrom<PermissionRequestWire> for PermissionRequest {
    type Error = PermissionError;

    fn try_from(value: PermissionRequestWire) -> Result<Self, Self::Error> {
        Self::new(value.action, value.resource)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
#[serde(rename_all = "snake_case")]
/// Decision produced by permission.
pub enum PermissionDecision {
    /// The operation is allowed.
    Allow,
    /// The operation is denied.
    Deny,
}

impl PermissionDecision {
    #[must_use]
    /// Returns whether this value is allowed.
    pub const fn is_allowed(self) -> bool {
        matches!(self, Self::Allow)
    }

    /// Ensures allowed.
    pub fn ensure_allowed(self) -> Result<(), PermissionError> {
        if self.is_allowed() {
            Ok(())
        } else {
            Err(PermissionError::Denied)
        }
    }
}

#[derive(Debug, Error)]
#[non_exhaustive]
/// Errors that can occur while handling permission.
pub enum PermissionError {
    #[error("permission denied")]
    /// Indicates denied.
    Denied,
    #[error("permission backend is unavailable")]
    /// Indicates unavailable.
    Unavailable,
    #[error("invalid principal: {0}")]
    /// The principal is invalid.
    InvalidPrincipal(String),
    #[error("invalid principal authority: {0}")]
    /// The authority is invalid.
    InvalidAuthority(String),
    #[error("invalid permission policy: {0}")]
    /// The policy is invalid.
    InvalidPolicy(String),
}

impl ClassifyError for PermissionError {
    fn error_kind(&self) -> ErrorKind {
        match self {
            Self::Denied => ErrorKind::Authorization,
            Self::Unavailable => ErrorKind::Unavailable,
            Self::InvalidPrincipal(_) | Self::InvalidAuthority(_) => ErrorKind::Validation,
            Self::InvalidPolicy(_) => ErrorKind::Internal,
        }
    }

    fn error_code(&self) -> Cow<'static, str> {
        Cow::Borrowed(match self {
            Self::Denied => "permission_denied",
            Self::Unavailable => "permission_unavailable",
            Self::InvalidPrincipal(_) => "principal_invalid",
            Self::InvalidAuthority(_) => "principal_authority_invalid",
            Self::InvalidPolicy(_) => "permission_invalid_policy",
        })
    }
}

/// Defines the contract for permission checker.
#[async_trait]
pub trait PermissionChecker: Send + Sync {
    /// Evaluates this check.
    async fn check(
        &self,
        principal: &Principal,
        action: &str,
        resource: &str,
    ) -> Result<PermissionDecision, PermissionError>;

    /// Checks the requested permission and converts denial into an error.
    async fn ensure_allowed(
        &self,
        principal: &Principal,
        action: &str,
        resource: &str,
    ) -> Result<(), PermissionError> {
        self.check(principal, action, resource)
            .await?
            .ensure_allowed()
    }
}

#[derive(Debug, Clone)]
/// Represents permission guard.
pub struct PermissionGuard<C> {
    checker: C,
}

impl<C> PermissionGuard<C> {
    #[must_use]
    /// Creates a new instance.
    pub fn new(checker: C) -> Self {
        Self { checker }
    }

    #[must_use]
    /// Returns the checker.
    pub const fn checker(&self) -> &C {
        &self.checker
    }
}

impl<C> PermissionGuard<C>
where
    C: PermissionChecker,
{
    /// Returns the require.
    pub async fn require(
        &self,
        principal: &Principal,
        request: &PermissionRequest,
    ) -> Result<(), PermissionError> {
        self.checker
            .ensure_allowed(principal, request.action(), request.resource())
            .await
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
/// Represents require role.
pub struct RequireRole {
    role: String,
}

impl RequireRole {
    /// Creates a new instance.
    pub fn new(role: impl Into<String>) -> Result<Self, PermissionError> {
        Ok(Self {
            role: normalize_policy_authority(role, "role guard")?,
        })
    }

    #[must_use]
    /// Returns the role.
    pub fn role(&self) -> &str {
        &self.role
    }

    /// Evaluates this check.
    pub fn check(&self, principal: &Principal) -> Result<(), PermissionError> {
        if self.role.is_empty() {
            return Err(PermissionError::InvalidPolicy(
                "role guard requires a non-empty role".to_owned(),
            ));
        }

        if principal.has_role(&self.role) {
            Ok(())
        } else {
            Err(PermissionError::Denied)
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
/// Represents require all roles.
pub struct RequireAllRoles {
    roles: Vec<String>,
}

impl RequireAllRoles {
    /// Creates a new instance.
    pub fn new(
        roles: impl IntoIterator<Item = impl Into<String>>,
    ) -> Result<Self, PermissionError> {
        Ok(Self {
            roles: normalize_policy_authorities(roles, "role guard")?,
        })
    }

    #[must_use]
    /// Returns the roles.
    pub fn roles(&self) -> &[String] {
        &self.roles
    }

    /// Evaluates this check.
    pub fn check(&self, principal: &Principal) -> Result<(), PermissionError> {
        if self.roles.is_empty() || self.roles.iter().any(String::is_empty) {
            return Err(PermissionError::InvalidPolicy(
                "role guard requires at least one non-empty role".to_owned(),
            ));
        }

        if self.roles.iter().all(|role| principal.has_role(role)) {
            Ok(())
        } else {
            Err(PermissionError::Denied)
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
/// Represents require any role.
pub struct RequireAnyRole {
    roles: Vec<String>,
}

impl RequireAnyRole {
    /// Creates a new instance.
    pub fn new(
        roles: impl IntoIterator<Item = impl Into<String>>,
    ) -> Result<Self, PermissionError> {
        Ok(Self {
            roles: normalize_policy_authorities(roles, "role guard")?,
        })
    }

    #[must_use]
    /// Returns the roles.
    pub fn roles(&self) -> &[String] {
        &self.roles
    }

    /// Evaluates this check.
    pub fn check(&self, principal: &Principal) -> Result<(), PermissionError> {
        if self.roles.is_empty() || self.roles.iter().any(String::is_empty) {
            return Err(PermissionError::InvalidPolicy(
                "role guard requires at least one non-empty role".to_owned(),
            ));
        }

        if self.roles.iter().any(|role| principal.has_role(role)) {
            Ok(())
        } else {
            Err(PermissionError::Denied)
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
/// Represents require scope.
pub struct RequireScope {
    scope: String,
}

impl RequireScope {
    /// Creates a new instance.
    pub fn new(scope: impl Into<String>) -> Result<Self, PermissionError> {
        Ok(Self {
            scope: normalize_policy_authority(scope, "scope guard")?,
        })
    }

    #[must_use]
    /// Returns the scope.
    pub fn scope(&self) -> &str {
        &self.scope
    }

    /// Evaluates this check.
    pub fn check(&self, principal: &Principal) -> Result<(), PermissionError> {
        if self.scope.is_empty() {
            return Err(PermissionError::InvalidPolicy(
                "scope guard requires a non-empty scope".to_owned(),
            ));
        }

        if principal.has_scope(&self.scope) {
            Ok(())
        } else {
            Err(PermissionError::Denied)
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
/// Represents require any scope.
pub struct RequireAnyScope {
    scopes: Vec<String>,
}

impl RequireAnyScope {
    /// Creates a new instance.
    pub fn new(
        scopes: impl IntoIterator<Item = impl Into<String>>,
    ) -> Result<Self, PermissionError> {
        Ok(Self {
            scopes: normalize_policy_authorities(scopes, "scope guard")?,
        })
    }

    #[must_use]
    /// Returns the scopes.
    pub fn scopes(&self) -> &[String] {
        &self.scopes
    }

    /// Evaluates this check.
    pub fn check(&self, principal: &Principal) -> Result<(), PermissionError> {
        if self.scopes.is_empty() || self.scopes.iter().any(String::is_empty) {
            return Err(PermissionError::InvalidPolicy(
                "scope guard requires at least one non-empty scope".to_owned(),
            ));
        }

        if self.scopes.iter().any(|scope| principal.has_scope(scope)) {
            Ok(())
        } else {
            Err(PermissionError::Denied)
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
/// Represents require all scopes.
pub struct RequireAllScopes {
    scopes: Vec<String>,
}

impl RequireAllScopes {
    /// Creates a new instance.
    pub fn new(
        scopes: impl IntoIterator<Item = impl Into<String>>,
    ) -> Result<Self, PermissionError> {
        Ok(Self {
            scopes: normalize_policy_authorities(scopes, "scope guard")?,
        })
    }

    #[must_use]
    /// Returns the scopes.
    pub fn scopes(&self) -> &[String] {
        &self.scopes
    }

    /// Evaluates this check.
    pub fn check(&self, principal: &Principal) -> Result<(), PermissionError> {
        if self.scopes.is_empty() || self.scopes.iter().any(String::is_empty) {
            return Err(PermissionError::InvalidPolicy(
                "scope guard requires at least one non-empty scope".to_owned(),
            ));
        }

        if self.scopes.iter().all(|scope| principal.has_scope(scope)) {
            Ok(())
        } else {
            Err(PermissionError::Denied)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        PermissionError, Principal, RequireAllRoles, RequireAllScopes, RequireAnyRole,
        RequireAnyScope, RequireRole, RequireScope,
    };
    use crate::result::{ClassifyError, ErrorKind};

    fn test_user() -> Principal {
        Principal::user("usr_1").expect("static test principal id is valid")
    }

    #[test]
    fn supports_wildcard_scopes() {
        let principal = test_user()
            .with_scopes(["user:*"])
            .expect("static test scope is valid");

        assert!(principal.has_scope("user:read"));
        assert!(principal.has_scope("user:write"));
        assert!(!principal.has_scope("client:read"));
    }

    #[test]
    fn role_guard_requires_matching_role() {
        let principal = test_user()
            .with_roles(["admin"])
            .expect("static test role is valid");

        assert!(
            RequireRole::new("admin")
                .expect("static guard role is valid")
                .check(&principal)
                .is_ok()
        );
        assert!(
            RequireRole::new("operator")
                .expect("static guard role is valid")
                .check(&principal)
                .is_err()
        );
    }

    #[test]
    fn scope_guard_supports_wildcard_scopes() {
        let principal = test_user()
            .with_scopes(["user:*"])
            .expect("static test scope is valid");

        assert!(
            RequireScope::new("user:read")
                .expect("static guard scope is valid")
                .check(&principal)
                .is_ok()
        );
        assert!(
            RequireScope::new("client:read")
                .expect("static guard scope is valid")
                .check(&principal)
                .is_err()
        );
    }

    #[test]
    fn role_set_guard_allows_any_matching_role() {
        let principal = test_user()
            .with_roles(["operator"])
            .expect("static test role is valid");

        assert!(
            RequireAnyRole::new(["admin", "operator"])
                .expect("static guard roles are valid")
                .check(&principal)
                .is_ok()
        );
        assert!(
            RequireAnyRole::new(["admin"])
                .expect("static guard role is valid")
                .check(&principal)
                .is_err()
        );
    }

    #[test]
    fn role_set_guard_can_require_all_roles() {
        let principal = test_user()
            .with_roles(["admin", "operator"])
            .expect("static test roles are valid");

        assert!(
            RequireAllRoles::new(["admin", "operator"])
                .expect("static guard roles are valid")
                .check(&principal)
                .is_ok()
        );
        assert!(
            RequireAllRoles::new(["admin", "auditor"])
                .expect("static guard roles are valid")
                .check(&principal)
                .is_err()
        );
    }

    #[test]
    fn scope_set_guard_requires_all_scopes() {
        let principal = test_user()
            .with_scopes(["user:*", "audit:read"])
            .expect("static test scopes are valid");

        assert!(
            RequireAllScopes::new(["user:read", "audit:read"])
                .expect("static guard scopes are valid")
                .check(&principal)
                .is_ok()
        );
        assert!(
            RequireAllScopes::new(["user:read", "client:read"])
                .expect("static guard scopes are valid")
                .check(&principal)
                .is_err()
        );
    }

    #[test]
    fn scope_set_guard_can_allow_any_scope() {
        let principal = test_user()
            .with_scopes(["user:*"])
            .expect("static test scope is valid");

        assert!(
            RequireAnyScope::new(["client:read", "user:read"])
                .expect("static guard scopes are valid")
                .check(&principal)
                .is_ok()
        );
        assert!(
            RequireAnyScope::new(["client:read", "audit:read"])
                .expect("static guard scopes are valid")
                .check(&principal)
                .is_err()
        );
    }

    #[test]
    fn empty_permission_guards_are_invalid_policies() {
        assert!(matches!(
            RequireRole::new(""),
            Err(PermissionError::InvalidPolicy(_))
        ));
        assert!(matches!(
            RequireScope::new(""),
            Err(PermissionError::InvalidPolicy(_))
        ));
        assert!(matches!(
            RequireAnyRole::new(std::iter::empty::<&str>()),
            Err(PermissionError::InvalidPolicy(_))
        ));
        assert!(matches!(
            RequireAllRoles::new(std::iter::empty::<&str>()),
            Err(PermissionError::InvalidPolicy(_))
        ));
        assert!(matches!(
            RequireAnyScope::new(std::iter::empty::<&str>()),
            Err(PermissionError::InvalidPolicy(_))
        ));
        assert!(matches!(
            RequireAllScopes::new(std::iter::empty::<&str>()),
            Err(PermissionError::InvalidPolicy(_))
        ));
    }

    #[test]
    fn permission_request_rejects_empty_parts() {
        assert!(matches!(
            super::PermissionRequest::new("", "users"),
            Err(PermissionError::InvalidPolicy(_))
        ));
        assert!(matches!(
            super::PermissionRequest::new("read", ""),
            Err(PermissionError::InvalidPolicy(_))
        ));
        let request =
            super::PermissionRequest::new("read", "users").expect("request should be valid");

        assert_eq!(request.action(), "read");
        assert_eq!(request.resource(), "users");

        let invalid = serde_json::json!({
            "action": "",
            "resource": "users"
        });
        assert!(serde_json::from_value::<super::PermissionRequest>(invalid).is_err());
    }

    #[test]
    fn principal_deduplicates_roles_and_scopes() {
        let mut principal = test_user()
            .with_roles(["admin", " admin "])
            .expect("static test roles are valid")
            .with_scopes(["user:read", " user:read "])
            .expect("static test scopes are valid");
        principal
            .add_role(" admin ")
            .expect("static test role is valid");
        principal
            .add_scope(" user:read ")
            .expect("static test scope is valid");

        assert_eq!(principal.id(), "usr_1");
        assert_eq!(principal.kind(), super::PrincipalKind::User);
        assert_eq!(principal.roles(), ["admin"]);
        assert_eq!(principal.scopes(), ["user:read"]);
    }

    #[test]
    fn principal_debug_redacts_identifiers_and_authorities_without_changing_wire_data() {
        let id = "private-principal-id";
        let tenant_id = "private-tenant-id";
        let role = "private-role";
        let scope = "private:scope";
        let principal = Principal::user(id)
            .expect("principal should be valid")
            .with_tenant_id(tenant_id)
            .expect("tenant should be valid")
            .with_roles([role])
            .expect("role should be valid")
            .with_scopes([scope])
            .expect("scope should be valid");

        let debug = format!("{principal:?}");
        assert!(debug.contains("[REDACTED]"));
        for sensitive in [id, tenant_id, role, scope] {
            assert!(!debug.contains(sensitive));
        }

        let wire = serde_json::to_value(principal).expect("principal should serialize");
        assert_eq!(wire["id"], id);
        assert_eq!(wire["tenant_id"], tenant_id);
        assert_eq!(wire["roles"][0], role);
        assert_eq!(wire["scopes"][0], scope);
    }

    #[test]
    fn principal_rejects_invalid_identifiers_and_authorities() {
        assert!(matches!(
            Principal::user(""),
            Err(PermissionError::InvalidPrincipal(_))
        ));
        assert!(matches!(
            Principal::client("client with space"),
            Err(PermissionError::InvalidPrincipal(_))
        ));
        assert!(matches!(
            test_user().with_roles([""]),
            Err(PermissionError::InvalidAuthority(_))
        ));
        assert!(matches!(
            test_user().with_scopes(["user read"]),
            Err(PermissionError::InvalidAuthority(_))
        ));
    }

    #[test]
    fn principal_deserialization_uses_same_validation() {
        let valid = serde_json::json!({
            "id": "usr_1",
            "kind": "user",
            "roles": ["admin", " admin "],
            "scopes": ["user:*"]
        });
        let principal: Principal =
            serde_json::from_value(valid).expect("valid principal JSON should deserialize");

        assert_eq!(principal.roles(), ["admin"]);
        assert!(principal.has_scope("user:read"));

        let invalid = serde_json::json!({
            "id": "usr_1",
            "kind": "user",
            "roles": [""]
        });
        assert!(serde_json::from_value::<Principal>(invalid).is_err());
    }

    #[test]
    fn blank_role_or_scope_checks_are_not_satisfied_by_wildcards() {
        let principal = test_user()
            .with_roles(["admin"])
            .expect("static test role is valid")
            .with_scopes(["*"])
            .expect("static test scope is valid");

        assert!(!principal.has_role(" "));
        assert!(!principal.has_scope(" "));
        assert!(!principal.has_all_roles(std::iter::empty::<&str>()));
        assert!(!principal.has_all_scopes(std::iter::empty::<&str>()));
    }

    #[test]
    fn principal_can_remove_authorities() {
        let mut principal = test_user()
            .with_roles(["admin", "operator"])
            .expect("static test roles are valid")
            .with_scopes(["user:read", "audit:read"])
            .expect("static test scopes are valid");

        assert!(principal.remove_role(" operator "));
        assert!(principal.remove_scope(" audit:read "));
        assert!(!principal.remove_role("missing"));

        assert_eq!(principal.roles(), ["admin"]);
        assert_eq!(principal.scopes(), ["user:read"]);
    }

    #[test]
    fn permission_errors_have_stable_classification() {
        let denied = PermissionError::Denied.error_descriptor();
        let unavailable = PermissionError::Unavailable.error_descriptor();
        let invalid_principal =
            PermissionError::InvalidPrincipal("empty id".to_owned()).error_descriptor();
        let invalid = PermissionError::InvalidPolicy("empty scope".to_owned()).error_descriptor();

        assert_eq!(denied.kind(), ErrorKind::Authorization);
        assert_eq!(denied.code().as_str(), "permission_denied");
        assert_eq!(unavailable.kind(), ErrorKind::Unavailable);
        assert!(unavailable.retryable());
        assert_eq!(invalid_principal.kind(), ErrorKind::Validation);
        assert_eq!(invalid_principal.code().as_str(), "principal_invalid");
        assert_eq!(invalid.kind(), ErrorKind::Internal);
        assert_eq!(invalid.code().as_str(), "permission_invalid_policy");
    }
}