#[cfg(feature = "abac")]
mod engine;
#[cfg(feature = "abac")]
mod loader;
#[cfg(feature = "abac")]
use crate::error::GarrisonResult;
#[cfg(feature = "abac")]
pub use engine::AbacEngine;
#[cfg(feature = "abac")]
pub use loader::{EmptyEntityLoader, StaticEntityLoader};
#[cfg(feature = "abac")]
#[async_trait::async_trait]
pub trait EntityLoader: Send + Sync {
async fn load_entities(&self) -> GarrisonResult<cedar_policy::Entities>;
}
#[cfg(feature = "abac")]
mod init;
#[cfg(feature = "abac")]
pub use init::*;
#[cfg(not(feature = "abac"))]
static ABAC_MISSING_FEATURE_POLICY: std::sync::atomic::AtomicU8 =
std::sync::atomic::AtomicU8::new(0);
#[cfg(not(feature = "abac"))]
pub fn set_abac_missing_feature_policy(allow_with_warn: bool) {
ABAC_MISSING_FEATURE_POLICY.store(
if allow_with_warn { 1 } else { 0 },
std::sync::atomic::Ordering::Relaxed,
);
}
#[cfg(not(feature = "abac"))]
pub async fn check_abac_with_policy(
action: &str,
_resource: &str,
abac_expr: &str,
) -> crate::error::GarrisonResult<()> {
if abac_expr.trim().is_empty() {
return Ok(());
}
if ABAC_MISSING_FEATURE_POLICY.load(std::sync::atomic::Ordering::Relaxed) == 1 {
tracing::warn!(
abac_expr = %abac_expr,
action = %action,
"ABAC feature disabled but endpoint requires abac policy; \
AllowWithWarn opt-in grants access (enable 'abac' feature for real enforcement)"
);
return Ok(());
}
Err(crate::error::GarrisonError::Config(format!(
"ABAC policy required by endpoint (action={action}, abac_expr={abac_expr}) \
but 'abac' feature is disabled (fail-closed). \
Enable 'abac' feature or remove the abac attribute."
)))
}
#[cfg(all(test, not(feature = "abac")))]
mod no_feature_tests {
use super::*;
static ABAC_POLICY_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
#[tokio::test]
#[allow(clippy::await_holding_lock)] async fn abac_with_expr_but_feature_off_is_fail_closed() {
let _guard = ABAC_POLICY_LOCK.lock().unwrap();
let r = check_abac_with_policy(
"order:read",
"Resource::\"order\"",
"resource.owner == principal.id",
)
.await;
assert!(
matches!(r, Err(crate::error::GarrisonError::Config(_))),
"应 fail-closed,实际: {:?}",
r
);
}
#[tokio::test]
async fn abac_without_expr_is_noop_ok() {
let r = check_abac_with_policy("order:read", "Resource::\"order\"", "").await;
assert!(r.is_ok(), "空 abac_expr 应 no-op 放行,实际: {:?}", r);
}
#[tokio::test]
#[allow(clippy::await_holding_lock)] async fn abac_allow_with_warn_opt_in_grants() {
let _guard = ABAC_POLICY_LOCK.lock().unwrap();
set_abac_missing_feature_policy(true);
let r = check_abac_with_policy(
"order:read",
"Resource::\"order\"",
"resource.owner == principal.id",
)
.await;
assert!(r.is_ok(), "opt-in 应放行,实际: {:?}", r);
set_abac_missing_feature_policy(false);
}
}
#[cfg(all(test, feature = "abac"))]
mod tests;