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")]
pub enum PrincipalKind {
User,
Client,
ServiceAccount,
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "PrincipalWire")]
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 {
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(),
})
}
pub fn user(id: impl Into<String>) -> Result<Self, PermissionError> {
Self::new(id, PrincipalKind::User)
}
pub fn client(id: impl Into<String>) -> Result<Self, PermissionError> {
Self::new(id, PrincipalKind::Client)
}
pub fn service_account(id: impl Into<String>) -> Result<Self, PermissionError> {
Self::new(id, PrincipalKind::ServiceAccount)
}
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)
}
pub fn with_roles(
mut self,
roles: impl IntoIterator<Item = impl Into<String>>,
) -> Result<Self, PermissionError> {
self.roles = normalize_authority_values(roles)?;
Ok(self)
}
pub fn with_scopes(
mut self,
scopes: impl IntoIterator<Item = impl Into<String>>,
) -> Result<Self, PermissionError> {
self.scopes = normalize_authority_values(scopes)?;
Ok(self)
}
pub fn add_role(&mut self, role: impl Into<String>) -> Result<(), PermissionError> {
push_unique(&mut self.roles, normalize_authority_value(role)?);
Ok(())
}
pub fn add_scope(&mut self, scope: impl Into<String>) -> Result<(), PermissionError> {
push_unique(&mut self.scopes, normalize_authority_value(scope)?);
Ok(())
}
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
}
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
}
pub fn clear_roles(&mut self) {
self.roles.clear();
}
pub fn clear_scopes(&mut self) {
self.scopes.clear();
}
#[must_use]
pub fn id(&self) -> &str {
&self.id
}
#[must_use]
pub const fn kind(&self) -> PrincipalKind {
self.kind
}
#[must_use]
pub fn tenant_id(&self) -> Option<&str> {
self.tenant_id.as_deref()
}
#[must_use]
pub fn roles(&self) -> &[String] {
&self.roles
}
#[must_use]
pub fn scopes(&self) -> &[String] {
&self.scopes
}
#[must_use]
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]
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]
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]
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]
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]
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]
pub fn is_user(&self) -> bool {
self.kind == PrincipalKind::User
}
#[must_use]
pub fn is_client(&self) -> bool {
self.kind == PrincipalKind::Client
}
#[must_use]
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")]
pub struct PermissionRequest {
action: String,
resource: String,
}
impl PermissionRequest {
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]
pub fn action(&self) -> &str {
&self.action
}
#[must_use]
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")]
pub enum PermissionDecision {
Allow,
Deny,
}
impl PermissionDecision {
#[must_use]
pub const fn is_allowed(self) -> bool {
matches!(self, Self::Allow)
}
pub fn ensure_allowed(self) -> Result<(), PermissionError> {
if self.is_allowed() {
Ok(())
} else {
Err(PermissionError::Denied)
}
}
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum PermissionError {
#[error("permission denied")]
Denied,
#[error("permission backend is unavailable")]
Unavailable,
#[error("invalid principal: {0}")]
InvalidPrincipal(String),
#[error("invalid principal authority: {0}")]
InvalidAuthority(String),
#[error("invalid permission policy: {0}")]
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",
})
}
}
#[async_trait]
pub trait PermissionChecker: Send + Sync {
async fn check(
&self,
principal: &Principal,
action: &str,
resource: &str,
) -> Result<PermissionDecision, PermissionError>;
async fn ensure_allowed(
&self,
principal: &Principal,
action: &str,
resource: &str,
) -> Result<(), PermissionError> {
self.check(principal, action, resource)
.await?
.ensure_allowed()
}
}
#[derive(Debug, Clone)]
pub struct PermissionGuard<C> {
checker: C,
}
impl<C> PermissionGuard<C> {
#[must_use]
pub fn new(checker: C) -> Self {
Self { checker }
}
#[must_use]
pub const fn checker(&self) -> &C {
&self.checker
}
}
impl<C> PermissionGuard<C>
where
C: PermissionChecker,
{
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)]
pub struct RequireRole {
role: String,
}
impl RequireRole {
pub fn new(role: impl Into<String>) -> Result<Self, PermissionError> {
Ok(Self {
role: normalize_policy_authority(role, "role guard")?,
})
}
#[must_use]
pub fn role(&self) -> &str {
&self.role
}
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)]
pub struct RequireAllRoles {
roles: Vec<String>,
}
impl RequireAllRoles {
pub fn new(
roles: impl IntoIterator<Item = impl Into<String>>,
) -> Result<Self, PermissionError> {
Ok(Self {
roles: normalize_policy_authorities(roles, "role guard")?,
})
}
#[must_use]
pub fn roles(&self) -> &[String] {
&self.roles
}
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)]
pub struct RequireAnyRole {
roles: Vec<String>,
}
impl RequireAnyRole {
pub fn new(
roles: impl IntoIterator<Item = impl Into<String>>,
) -> Result<Self, PermissionError> {
Ok(Self {
roles: normalize_policy_authorities(roles, "role guard")?,
})
}
#[must_use]
pub fn roles(&self) -> &[String] {
&self.roles
}
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)]
pub struct RequireScope {
scope: String,
}
impl RequireScope {
pub fn new(scope: impl Into<String>) -> Result<Self, PermissionError> {
Ok(Self {
scope: normalize_policy_authority(scope, "scope guard")?,
})
}
#[must_use]
pub fn scope(&self) -> &str {
&self.scope
}
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)]
pub struct RequireAnyScope {
scopes: Vec<String>,
}
impl RequireAnyScope {
pub fn new(
scopes: impl IntoIterator<Item = impl Into<String>>,
) -> Result<Self, PermissionError> {
Ok(Self {
scopes: normalize_policy_authorities(scopes, "scope guard")?,
})
}
#[must_use]
pub fn scopes(&self) -> &[String] {
&self.scopes
}
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)]
pub struct RequireAllScopes {
scopes: Vec<String>,
}
impl RequireAllScopes {
pub fn new(
scopes: impl IntoIterator<Item = impl Into<String>>,
) -> Result<Self, PermissionError> {
Ok(Self {
scopes: normalize_policy_authorities(scopes, "scope guard")?,
})
}
#[must_use]
pub fn scopes(&self) -> &[String] {
&self.scopes
}
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");
}
}