use serde::{Deserialize, Deserializer, Serialize};
use std::fmt;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum CapabilityPolicy {
Deny,
#[default]
Ask,
Allow,
}
impl CapabilityPolicy {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Deny => "deny",
Self::Ask => "ask",
Self::Allow => "allow",
}
}
#[must_use]
pub const fn is_denied(self) -> bool {
matches!(self, Self::Deny)
}
#[must_use]
pub const fn is_preauthorized(self) -> bool {
matches!(self, Self::Allow)
}
#[must_use]
pub const fn allows_requests(self) -> bool {
!self.is_denied()
}
}
impl fmt::Display for CapabilityPolicy {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
impl<'de> Deserialize<'de> for CapabilityPolicy {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
match value.as_str() {
"deny" => Ok(Self::Deny),
"ask" => Ok(Self::Ask),
"allow" => Ok(Self::Allow),
other => Err(serde::de::Error::custom(format!(
"invalid capability policy `{other}`; expected \"deny\", \"ask\", or \"allow\""
))),
}
}
}
#[derive(
Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
)]
#[serde(rename_all = "kebab-case")]
pub enum ApprovalScope {
#[default]
Once,
Session,
}
impl ApprovalScope {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Once => "once",
Self::Session => "session",
}
}
}
impl fmt::Display for ApprovalScope {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
#[cfg(test)]
mod tests {
use super::{ApprovalScope, CapabilityPolicy};
#[test]
fn capability_policy_round_trips_canonical_strings() {
for policy in [
CapabilityPolicy::Deny,
CapabilityPolicy::Ask,
CapabilityPolicy::Allow,
] {
let encoded = serde_json::to_string(&policy).expect("serialize");
let decoded: CapabilityPolicy = serde_json::from_str(&encoded).expect("deserialize");
assert_eq!(decoded, policy);
assert_eq!(encoded, format!("\"{}\"", policy.as_str()));
}
assert!(serde_json::from_str::<CapabilityPolicy>("\"invalid\"").is_err());
}
#[test]
fn approval_scope_defaults_to_once_and_round_trips() {
assert_eq!(ApprovalScope::default(), ApprovalScope::Once);
for scope in [ApprovalScope::Once, ApprovalScope::Session] {
let encoded = serde_json::to_string(&scope).expect("serialize");
let decoded: ApprovalScope = serde_json::from_str(&encoded).expect("deserialize");
assert_eq!(decoded, scope);
assert_eq!(encoded, format!("\"{}\"", scope.as_str()));
}
}
}