#[cfg(feature = "capsules")]
mod store_layout {
use std::collections::HashMap;
use std::io;
use std::path::{Path, PathBuf};
use chrono::{DateTime, Utc};
use rusty_agent_runtime::capsule::CapsuleOverlay;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub(crate) struct CapsulePolicyRecord {
pub version: String,
pub policy_text: String,
pub registered_at: DateTime<Utc>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum CapsulePolicyWrite {
Created,
Converged,
Conflict,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub(crate) struct CapsulePolicyActivation {
pub version: String,
pub activated_at: DateTime<Utc>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub(crate) struct CapsuleOverlayRecord {
pub overlay: CapsuleOverlay,
pub author: String,
pub attached_at: DateTime<Utc>,
}
fn capsule_policies_dir(root: &Path) -> PathBuf {
root.join("capsule_policies")
}
pub(crate) fn capsule_policy_versions_dir(root: &Path) -> PathBuf {
capsule_policies_dir(root).join("versions")
}
pub(crate) fn capsule_policy_active_dir(root: &Path) -> PathBuf {
capsule_policies_dir(root).join("active")
}
pub(crate) fn capsule_overlays_dir(root: &Path) -> PathBuf {
capsule_policies_dir(root).join("overlays")
}
fn collect_json_files(root: &Path, out: &mut Vec<PathBuf>) {
let Ok(entries) = std::fs::read_dir(root) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
collect_json_files(&path, out);
} else if path.extension().and_then(|e| e.to_str()) == Some("json") {
out.push(path);
}
}
}
fn path_scoped_name(dir: &Path, path: &Path) -> Option<String> {
path.strip_prefix(dir)
.ok()
.map(|relative| relative.with_extension(""))
.map(|relative| {
relative
.components()
.map(|component| component.as_os_str().to_string_lossy().into_owned())
.collect::<Vec<_>>()
.join("/")
})
}
async fn persist_record<T: Serialize>(
dir: &Path,
scoped_name: &str,
record: &T,
what: &str,
) -> io::Result<()> {
tokio::fs::create_dir_all(dir).await?;
let bytes = serde_json::to_vec_pretty(record)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
let path = dir.join(format!("{scoped_name}.json"));
if let Some(parent) = path.parent() {
tokio::fs::create_dir_all(parent).await?;
}
let tmp = dir.join(format!("{scoped_name}.{what}.tmp"));
tokio::fs::write(&tmp, bytes).await?;
tokio::fs::rename(&tmp, path).await
}
fn load_records<T: serde::de::DeserializeOwned>(dir: &Path, what: &str) -> HashMap<String, T> {
let mut out = HashMap::new();
let mut files = Vec::new();
collect_json_files(dir, &mut files);
for path in files {
let scoped = path_scoped_name(dir, &path);
let parsed = std::fs::read_to_string(&path)
.ok()
.and_then(|raw| serde_json::from_str::<T>(&raw).ok());
match (scoped, parsed) {
(Some(name), Some(record)) => {
out.insert(name, record);
}
_ => {
tracing::warn!(path = %path.display(), "skipping unreadable {what} file")
}
}
}
out
}
pub(crate) async fn persist_capsule_policy(
root: &Path,
scoped_version: &str,
record: &CapsulePolicyRecord,
) -> io::Result<()> {
persist_record(
&capsule_policy_versions_dir(root),
scoped_version,
record,
"policy",
)
.await
}
pub(crate) fn load_capsule_policies(root: &Path) -> HashMap<String, CapsulePolicyRecord> {
load_records(&capsule_policy_versions_dir(root), "capsule policy")
}
pub(crate) fn activation_scoped_name(tenant: &str) -> String {
crate::auth::scope_id(tenant, "active")
}
pub(crate) async fn persist_capsule_policy_activation(
root: &Path,
tenant: &str,
activation: &CapsulePolicyActivation,
) -> io::Result<()> {
persist_record(
&capsule_policy_active_dir(root),
&activation_scoped_name(tenant),
activation,
"activation",
)
.await
}
pub(crate) fn load_capsule_policy_activations(
root: &Path,
) -> HashMap<String, CapsulePolicyActivation> {
load_records(
&capsule_policy_active_dir(root),
"capsule policy activation",
)
}
pub(crate) async fn persist_capsule_overlay(
root: &Path,
scoped_name: &str,
record: &CapsuleOverlayRecord,
) -> io::Result<()> {
persist_record(&capsule_overlays_dir(root), scoped_name, record, "overlay").await
}
pub(crate) fn load_capsule_overlays(root: &Path) -> HashMap<String, CapsuleOverlayRecord> {
load_records(&capsule_overlays_dir(root), "capsule overlay")
}
#[cfg(test)]
mod tests {
use super::*;
use rusty_agent_runtime::capsule::CapabilityGrant;
use std::collections::BTreeSet;
fn ts(millis: i64) -> DateTime<Utc> {
DateTime::<Utc>::from_timestamp_millis(millis).unwrap()
}
#[tokio::test]
async fn layout_round_trips_policies_pointer_and_overlays() {
let root = std::env::temp_dir().join(format!(
"rusty-capsule-policy-test-{}",
uuid::Uuid::new_v4()
));
let record = CapsulePolicyRecord {
version: "cedar-0123456789ab".into(),
policy_text: "permit(principal, action, resource);".into(),
registered_at: ts(1_000),
};
persist_capsule_policy(&root, "cedar-0123456789ab", &record)
.await
.unwrap();
persist_capsule_policy(&root, "acme/cedar-0123456789ab", &record)
.await
.unwrap();
let activation = CapsulePolicyActivation {
version: "cedar-0123456789ab".into(),
activated_at: ts(2_000),
};
persist_capsule_policy_activation(&root, "default", &activation)
.await
.unwrap();
persist_capsule_policy_activation(&root, "acme", &activation)
.await
.unwrap();
let overlay = CapsuleOverlayRecord {
overlay: CapsuleOverlay {
name: "ceiling".into(),
targets: None,
capabilities: BTreeSet::from([CapabilityGrant::Clock]),
note: None,
},
author: "acme".into(),
attached_at: ts(3_000),
};
persist_capsule_overlay(&root, "acme/ceiling", &overlay)
.await
.unwrap();
std::fs::create_dir_all(capsule_policy_versions_dir(&root)).unwrap();
std::fs::write(
capsule_policy_versions_dir(&root).join("broken.json"),
b"{nope",
)
.unwrap();
let policies = load_capsule_policies(&root);
assert_eq!(policies.len(), 2, "corrupt files are skipped, not fatal");
assert!(policies.contains_key("cedar-0123456789ab"));
assert!(policies.contains_key("acme/cedar-0123456789ab"));
let activations = load_capsule_policy_activations(&root);
assert_eq!(activations.len(), 2);
assert!(activations.contains_key("active"));
assert!(activations.contains_key("acme/active"));
let overlays = load_capsule_overlays(&root);
assert_eq!(overlays.len(), 1);
assert!(overlays.contains_key("acme/ceiling"));
let _ = std::fs::remove_dir_all(root);
}
}
}
#[cfg(feature = "capsules")]
pub(crate) use store_layout::*;
#[cfg(feature = "capsules")]
pub use engine::{CapsulePolicyError, CapsulePolicyPlane};
#[cfg(feature = "capsules")]
pub(crate) use engine::{
activation, authorize_overlay_attach, authorize_registration, compose_admission,
derive_capsule_policy_version, load_config_policies, preload_active_policies,
prospective_record, validate_capsule_policy_version, AdmissionRefusal, CedarEngine,
};
#[cfg(feature = "capsules")]
mod engine {
use std::collections::BTreeSet;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::{Arc, RwLock};
use cedar_policy::{
Authorizer, Context, Decision, Entities, EntityId, EntityTypeName, EntityUid, PolicySet,
Request,
};
use chrono::Utc;
use rusty_agent_runtime::capsule::{
grants_beyond, CapabilityGrant, CapsuleId, CapsuleManifest, CapsuleOverlay, ResourceBudget,
};
use rusty_agent_runtime::capsule_host::{GrantRecheck, RecheckDenial};
use rusty_agent_runtime::record::sha256_hex;
use serde_json::{json, Value};
use super::{CapsulePolicyActivation, CapsulePolicyRecord, CapsulePolicyWrite};
use crate::capsules::CapsuleRecord;
use crate::server_store::ServerStore;
const ACTION_ADMIT: &str = "AdmitCapsule";
const ACTION_USE: &str = "UseCapability";
const ACTION_ATTACH: &str = "AttachOverlay";
#[derive(Debug)]
pub enum CapsulePolicyError {
Parse(String),
Evaluation(String),
Request(String),
}
impl std::fmt::Display for CapsulePolicyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
CapsulePolicyError::Parse(e) => write!(f, "cedar policy parse error: {e}"),
CapsulePolicyError::Evaluation(e) => {
write!(f, "cedar policy evaluation error: {e}")
}
CapsulePolicyError::Request(e) => {
write!(f, "cedar request construction error: {e}")
}
}
}
}
impl std::error::Error for CapsulePolicyError {}
fn entity_uid(entity_type: &str, id: &str) -> Result<EntityUid, CapsulePolicyError> {
let entity_type = EntityTypeName::from_str(entity_type).map_err(|e| {
CapsulePolicyError::Request(format!("entity type `{entity_type}`: {e}"))
})?;
let id = EntityId::from_str(id)
.map_err(|e| CapsulePolicyError::Request(format!("entity id `{id}`: {e}")))?;
Ok(EntityUid::from_type_name_and_id(entity_type, id))
}
fn grant_context(grant: &CapabilityGrant) -> Value {
match grant {
CapabilityGrant::Filesystem { paths, mode } => json!({
"kind": "filesystem",
"paths": paths,
"mode": mode,
}),
CapabilityGrant::Network {
hosts,
protocols,
methods,
} => json!({
"kind": "network",
"hosts": hosts,
"protocols": protocols,
"methods": methods,
}),
CapabilityGrant::Secret { handles } => json!({
"kind": "secret",
"handles": handles,
}),
CapabilityGrant::Tool { tools } => json!({
"kind": "tool",
"tools": tools,
}),
CapabilityGrant::Model { models } => json!({
"kind": "model",
"models": models,
}),
CapabilityGrant::Clock => json!({ "kind": "clock" }),
}
}
fn kind_name(grant: &CapabilityGrant) -> &'static str {
match grant {
CapabilityGrant::Filesystem { .. } => "filesystem",
CapabilityGrant::Network { .. } => "network",
CapabilityGrant::Secret { .. } => "secret",
CapabilityGrant::Tool { .. } => "tool",
CapabilityGrant::Model { .. } => "model",
CapabilityGrant::Clock => "clock",
}
}
#[derive(Debug)]
pub(crate) struct Verdict {
pub(crate) allowed: bool,
pub(crate) reasons: Vec<String>,
}
pub(crate) struct CedarEngine {
authorizer: Authorizer,
policies: PolicySet,
}
impl CedarEngine {
pub(crate) fn parse(text: &str) -> Result<Self, CapsulePolicyError> {
let policies =
PolicySet::from_str(text).map_err(|e| CapsulePolicyError::Parse(e.to_string()))?;
Ok(Self {
authorizer: Authorizer::new(),
policies,
})
}
fn decide(
&self,
tenant: &str,
action: &str,
resource: EntityUid,
entities: Vec<Value>,
context: Value,
) -> Result<Verdict, CapsulePolicyError> {
let request = Request::new(
entity_uid("Tenant", tenant)?,
entity_uid("Action", action)?,
resource,
Context::from_json_value(context, None)
.map_err(|e| CapsulePolicyError::Request(e.to_string()))?,
None,
)
.map_err(|e| CapsulePolicyError::Request(e.to_string()))?;
let entities = Entities::from_json_value(Value::Array(entities), None)
.map_err(|e| CapsulePolicyError::Request(e.to_string()))?;
let response = self
.authorizer
.is_authorized(&request, &self.policies, &entities);
let errors: Vec<String> = response
.diagnostics()
.errors()
.map(ToString::to_string)
.collect();
if !errors.is_empty() {
return Err(CapsulePolicyError::Evaluation(errors.join("; ")));
}
Ok(Verdict {
allowed: response.decision() == Decision::Allow,
reasons: response
.diagnostics()
.reason()
.map(ToString::to_string)
.collect(),
})
}
fn tenant_entity(tenant: &str) -> Value {
json!({"uid": {"type": "Tenant", "id": tenant}, "attrs": {}, "parents": []})
}
fn capsule_entity(record: &CapsuleRecord) -> Value {
json!({
"uid": {"type": "Capsule", "id": record.capsule_id.as_str()},
"attrs": {
"name": record.manifest.identity.name,
"version": record.manifest.version,
"build_digest": record.manifest.build_digest,
},
"parents": [],
})
}
pub(crate) fn authorize_admission(
&self,
tenant: &str,
record: &CapsuleRecord,
) -> Result<Verdict, CapsulePolicyError> {
self.decide(
tenant,
ACTION_ADMIT,
entity_uid("Capsule", record.capsule_id.as_str())?,
vec![Self::tenant_entity(tenant), Self::capsule_entity(record)],
json!({
"name": record.manifest.identity.name,
"version": record.manifest.version,
"build_digest": record.manifest.build_digest,
}),
)
}
fn authorize_grant(
&self,
tenant: &str,
capsule_id: &CapsuleId,
capsule_entities: Vec<Value>,
grant: &CapabilityGrant,
) -> Result<Verdict, CapsulePolicyError> {
self.decide(
tenant,
ACTION_USE,
entity_uid("Capsule", capsule_id.as_str())?,
capsule_entities,
grant_context(grant),
)
}
pub(crate) fn forbidden_grants(
&self,
tenant: &str,
record: &CapsuleRecord,
) -> Result<Vec<CapabilityGrant>, CapsulePolicyError> {
let entities = vec![Self::tenant_entity(tenant), Self::capsule_entity(record)];
let mut forbidden = Vec::new();
for grant in &record.manifest.capabilities {
let verdict =
self.authorize_grant(tenant, &record.capsule_id, entities.clone(), grant)?;
if !verdict.allowed {
forbidden.push(grant.clone());
}
}
Ok(forbidden)
}
pub(crate) fn authorize_use(
&self,
tenant: &str,
capsule_id: &CapsuleId,
grant: &CapabilityGrant,
) -> Result<Verdict, CapsulePolicyError> {
self.decide(
tenant,
ACTION_USE,
entity_uid("Capsule", capsule_id.as_str())?,
vec![
Self::tenant_entity(tenant),
json!({
"uid": {"type": "Capsule", "id": capsule_id.as_str()},
"attrs": {},
"parents": [],
}),
],
grant_context(grant),
)
}
pub(crate) fn authorize_overlay(
&self,
tenant: &str,
overlay: &CapsuleOverlay,
target: Option<&CapsuleRecord>,
) -> Result<Verdict, CapsulePolicyError> {
let (resource, entities, widens, capsule_name) = match target {
Some(record) => (
entity_uid("Capsule", record.capsule_id.as_str())?,
vec![Self::tenant_entity(tenant), Self::capsule_entity(record)],
!grants_beyond(&overlay.capabilities, &record.manifest.capabilities).is_empty(),
record.manifest.identity.name.clone(),
),
None => (
entity_uid("Tenant", tenant)?,
vec![Self::tenant_entity(tenant)],
false,
String::new(),
),
};
self.decide(
tenant,
ACTION_ATTACH,
resource,
entities,
json!({
"name": overlay.name,
"targets": overlay.targets.clone().unwrap_or_default(),
"capsule": capsule_name,
"widens": widens,
"grant_kinds": overlay
.capabilities
.iter()
.map(kind_name)
.collect::<Vec<_>>(),
}),
)
}
}
pub(crate) fn derive_capsule_policy_version(text: &str) -> String {
format!("cedar-{}", &sha256_hex(text.as_bytes())[..12])
}
pub(crate) fn validate_capsule_policy_version(version: &str) -> Result<(), String> {
let valid = !version.is_empty()
&& version.len() <= 128
&& version
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.'));
if !valid {
return Err(format!(
"invalid capsule policy version `{version}` (allowed: [A-Za-z0-9._-], 1..=128 chars)"
));
}
Ok(())
}
struct CachedEngine {
version: String,
engine: CedarEngine,
}
pub struct CapsulePolicyPlane {
engines: RwLock<std::collections::HashMap<String, CachedEngine>>,
}
impl std::fmt::Debug for CapsulePolicyPlane {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let tenants: Vec<String> = self
.engines
.read()
.map(|engines| engines.keys().cloned().collect())
.unwrap_or_default();
f.debug_struct("CapsulePolicyPlane")
.field("cached_tenants", &tenants)
.finish()
}
}
impl Default for CapsulePolicyPlane {
fn default() -> Self {
Self::new()
}
}
impl CapsulePolicyPlane {
pub fn new() -> Self {
Self {
engines: RwLock::new(std::collections::HashMap::new()),
}
}
pub fn install(
&self,
tenant: &str,
version: &str,
policy_text: &str,
) -> Result<(), CapsulePolicyError> {
let engine = CedarEngine::parse(policy_text)?;
let mut engines = self
.engines
.write()
.unwrap_or_else(|poisoned| poisoned.into_inner());
engines.insert(
tenant.to_string(),
CachedEngine {
version: version.to_string(),
engine,
},
);
Ok(())
}
pub fn clear(&self, tenant: &str) {
let mut engines = self
.engines
.write()
.unwrap_or_else(|poisoned| poisoned.into_inner());
engines.remove(tenant);
}
pub fn cached_version(&self, tenant: &str) -> Option<String> {
self.engines
.read()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.get(tenant)
.map(|cached| cached.version.clone())
}
pub fn rechecker(self: &Arc<Self>, tenant: &str) -> Arc<dyn GrantRecheck> {
Arc::new(PlaneRecheck {
plane: Arc::clone(self),
tenant: tenant.to_string(),
})
}
pub(crate) async fn refresh(
&self,
store: &Arc<dyn ServerStore>,
tenant: &str,
) -> Result<(), String> {
match store.active_capsule_policy(tenant).await? {
Some(record) => self
.install(tenant, &record.version, &record.policy_text)
.map_err(|e| {
format!(
"active capsule policy `{}` for tenant `{tenant}` no longer parses: {e}",
record.version
)
}),
None => {
self.clear(tenant);
Ok(())
}
}
}
}
#[derive(Debug)]
struct PlaneRecheck {
plane: Arc<CapsulePolicyPlane>,
tenant: String,
}
impl GrantRecheck for PlaneRecheck {
fn recheck(
&self,
capsule_id: &CapsuleId,
grant: &CapabilityGrant,
) -> Option<RecheckDenial> {
let engines = self
.plane
.engines
.read()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let cached = engines.get(&self.tenant)?;
let kind = kind_name(grant);
match cached.engine.authorize_use(&self.tenant, capsule_id, grant) {
Ok(verdict) if verdict.allowed => None,
Ok(verdict) => Some(RecheckDenial {
policy_version: cached.version.clone(),
detail: format!(
"policy version `{}` forbids the `{kind}` grant for tenant `{}` \
(deciding policies: {})",
cached.version,
self.tenant,
verdict.reasons.join(", ")
),
}),
Err(error) => Some(RecheckDenial {
policy_version: cached.version.clone(),
detail: format!(
"policy version `{}` failed to evaluate the `{kind}` recheck ({error}) — \
refusing closed",
cached.version
),
}),
}
}
}
#[derive(Debug, Default)]
pub(crate) struct AdmissionOutcome {
pub(crate) policy_version: Option<String>,
pub(crate) overlays: Option<Vec<String>>,
pub(crate) effective_grants: Option<BTreeSet<CapabilityGrant>>,
pub(crate) clamped_budget: Option<ResourceBudget>,
}
#[derive(Debug)]
pub(crate) enum AdmissionRefusal {
Policy {
version: String,
forbidden: Vec<CapabilityGrant>,
detail: String,
},
Budget {
field: &'static str,
declared: String,
bound: String,
},
Internal(String),
}
fn tightest_u64(
layers: &[Option<&ResourceBudget>],
pick: impl Fn(&ResourceBudget) -> Option<u64>,
) -> Option<u64> {
layers
.iter()
.filter_map(|layer| layer.and_then(&pick))
.min()
}
fn tightest_cost(layers: &[Option<&ResourceBudget>]) -> Option<f64> {
layers
.iter()
.filter_map(|layer| layer.and_then(|budget| budget.max_cost_usd))
.reduce(f64::min)
}
pub(crate) async fn compose_admission(
store: &Arc<dyn ServerStore>,
plane: &Arc<CapsulePolicyPlane>,
tenant: &str,
record: &CapsuleRecord,
run_budget: Option<&ResourceBudget>,
tenant_ceiling: Option<&ResourceBudget>,
) -> Result<AdmissionOutcome, AdmissionRefusal> {
let mut policy_version = None;
if let Some(active) = store
.active_capsule_policy(tenant)
.await
.map_err(AdmissionRefusal::Internal)?
{
let engine = CedarEngine::parse(&active.policy_text).map_err(|e| {
AdmissionRefusal::Internal(format!(
"active capsule policy `{}` no longer parses: {e}",
active.version
))
})?;
let verdict = engine
.authorize_admission(tenant, record)
.map_err(|e| AdmissionRefusal::Internal(e.to_string()))?;
if !verdict.allowed {
return Err(AdmissionRefusal::Policy {
version: active.version.clone(),
forbidden: Vec::new(),
detail: format!(
"policy version `{}` refuses to admit capsule `{}` (identity `{}` \
version `{}`) to tenant `{tenant}` (deciding policies: {})",
active.version,
record.capsule_id,
record.manifest.identity.name,
record.manifest.version,
verdict.reasons.join(", ")
),
});
}
let forbidden = engine
.forbidden_grants(tenant, record)
.map_err(|e| AdmissionRefusal::Internal(e.to_string()))?;
if !forbidden.is_empty() {
let kinds: Vec<&str> = forbidden.iter().map(kind_name).collect();
return Err(AdmissionRefusal::Policy {
version: active.version.clone(),
forbidden,
detail: format!(
"policy version `{}` forbids grants the manifest declares ({}) for \
tenant `{tenant}` — a capsule may declare fewer grants than policy \
permits, never more",
active.version,
kinds.join(", ")
),
});
}
plane
.install(tenant, &active.version, &active.policy_text)
.map_err(|e| AdmissionRefusal::Internal(e.to_string()))?;
policy_version = Some(active.version);
}
let mut tenant_overlays = store
.list_capsule_overlays(tenant)
.await
.map_err(AdmissionRefusal::Internal)?;
tenant_overlays.sort_by(|a, b| a.overlay.name.cmp(&b.overlay.name));
let mut overlays_applied = Vec::new();
let mut effective = record.manifest.capabilities.clone();
for overlay_record in &tenant_overlays {
if overlay_record
.overlay
.applies_to(&record.manifest.identity.name)
{
effective = overlay_record.overlay.effective_grants(&effective);
overlays_applied.push(overlay_record.overlay.name.clone());
}
}
let (overlays, effective_grants) = if overlays_applied.is_empty() {
(None, None)
} else {
(Some(overlays_applied), Some(effective))
};
let declared = &record.manifest.budget;
let layers = [run_budget, tenant_ceiling];
let mut clamped = declared.clone();
for layer in layers.iter().flatten() {
clamped = clamped.clamp(layer);
}
if let (Some(want), Some(bound)) = (
declared.max_tokens,
tightest_u64(&layers, |budget| budget.max_tokens),
) {
if want > bound {
return Err(AdmissionRefusal::Budget {
field: "max_tokens",
declared: want.to_string(),
bound: bound.to_string(),
});
}
}
if let (Some(want), Some(bound)) = (declared.max_cost_usd, tightest_cost(&layers)) {
if want > bound {
return Err(AdmissionRefusal::Budget {
field: "max_cost_usd",
declared: want.to_string(),
bound: bound.to_string(),
});
}
}
let clamped_budget = if &clamped != declared {
Some(clamped)
} else {
None
};
Ok(AdmissionOutcome {
policy_version,
overlays,
effective_grants,
clamped_budget,
})
}
pub(crate) async fn authorize_registration(
store: &Arc<dyn ServerStore>,
plane: &Arc<CapsulePolicyPlane>,
tenant: &str,
record: &CapsuleRecord,
) -> Result<(), AdmissionRefusal> {
let Some(active) = store
.active_capsule_policy(tenant)
.await
.map_err(AdmissionRefusal::Internal)?
else {
return Ok(());
};
let engine = CedarEngine::parse(&active.policy_text).map_err(|e| {
AdmissionRefusal::Internal(format!(
"active capsule policy `{}` no longer parses: {e}",
active.version
))
})?;
let verdict = engine
.authorize_admission(tenant, record)
.map_err(|e| AdmissionRefusal::Internal(e.to_string()))?;
if !verdict.allowed {
return Err(AdmissionRefusal::Policy {
version: active.version.clone(),
forbidden: Vec::new(),
detail: format!(
"policy version `{}` refuses to admit capsule `{}` to tenant `{tenant}` \
(deciding policies: {})",
active.version,
record.capsule_id,
verdict.reasons.join(", ")
),
});
}
let forbidden = engine
.forbidden_grants(tenant, record)
.map_err(|e| AdmissionRefusal::Internal(e.to_string()))?;
if !forbidden.is_empty() {
let kinds: Vec<&str> = forbidden.iter().map(kind_name).collect();
return Err(AdmissionRefusal::Policy {
version: active.version.clone(),
forbidden,
detail: format!(
"policy version `{}` forbids grants the manifest declares ({}) for tenant \
`{tenant}`",
active.version,
kinds.join(", ")
),
});
}
plane
.install(tenant, &active.version, &active.policy_text)
.map_err(|e| AdmissionRefusal::Internal(e.to_string()))?;
Ok(())
}
pub(crate) async fn authorize_overlay_attach(
store: &Arc<dyn ServerStore>,
tenant: &str,
overlay: &CapsuleOverlay,
) -> Result<(), AdmissionRefusal> {
let Some(active) = store
.active_capsule_policy(tenant)
.await
.map_err(AdmissionRefusal::Internal)?
else {
return Ok(());
};
let engine = CedarEngine::parse(&active.policy_text).map_err(|e| {
AdmissionRefusal::Internal(format!(
"active capsule policy `{}` no longer parses: {e}",
active.version
))
})?;
let capsules = store
.list_capsules(tenant)
.await
.map_err(AdmissionRefusal::Internal)?;
let mut matched = false;
for record in &capsules {
if !overlay.applies_to(&record.manifest.identity.name) {
continue;
}
matched = true;
let verdict = engine
.authorize_overlay(tenant, overlay, Some(record))
.map_err(|e| AdmissionRefusal::Internal(e.to_string()))?;
if !verdict.allowed {
return Err(AdmissionRefusal::Policy {
version: active.version.clone(),
forbidden: Vec::new(),
detail: format!(
"policy version `{}` refuses overlay `{}` against capsule `{}` \
(identity `{}`) for tenant `{tenant}` (deciding policies: {})",
active.version,
overlay.name,
record.capsule_id,
record.manifest.identity.name,
verdict.reasons.join(", ")
),
});
}
}
if !matched {
let verdict = engine
.authorize_overlay(tenant, overlay, None)
.map_err(|e| AdmissionRefusal::Internal(e.to_string()))?;
if !verdict.allowed {
return Err(AdmissionRefusal::Policy {
version: active.version.clone(),
forbidden: Vec::new(),
detail: format!(
"policy version `{}` refuses overlay `{}` for tenant `{tenant}` \
(deciding policies: {})",
active.version,
overlay.name,
verdict.reasons.join(", ")
),
});
}
}
Ok(())
}
pub(crate) async fn load_config_policies(store: Arc<dyn ServerStore>, files: Vec<PathBuf>) {
for file in files {
let text = match std::fs::read_to_string(&file) {
Ok(text) => text,
Err(error) => {
tracing::warn!(path = %file.display(), %error, "capsule policy file unreadable; skipped");
continue;
}
};
if let Err(error) = CedarEngine::parse(&text) {
tracing::warn!(path = %file.display(), %error, "capsule policy file does not parse; skipped");
continue;
}
let record = CapsulePolicyRecord {
version: derive_capsule_policy_version(&text),
policy_text: text,
registered_at: Utc::now(),
};
match store
.put_capsule_policy(crate::auth::DEFAULT_TENANT, &record)
.await
{
Ok(CapsulePolicyWrite::Created) => {
tracing::info!(
path = %file.display(),
version = %record.version,
"registered config-file capsule policy (inactive until activated)"
);
}
Ok(CapsulePolicyWrite::Converged) => {}
Ok(CapsulePolicyWrite::Conflict) => {
tracing::warn!(
path = %file.display(),
version = %record.version,
"capsule policy version names a different body; config file skipped"
);
}
Err(error) => {
tracing::warn!(path = %file.display(), %error, "failed to register capsule policy file");
}
}
}
}
pub(crate) async fn preload_active_policies(
store: Arc<dyn ServerStore>,
plane: Arc<CapsulePolicyPlane>,
) {
match store.list_active_capsule_policies().await {
Ok(actives) => {
for (tenant, record) in actives {
if let Err(error) = plane.install(&tenant, &record.version, &record.policy_text)
{
tracing::warn!(
%tenant,
version = %record.version,
%error,
"active capsule policy failed to parse at preload; the tenant's \
rechecks stay unenforced until the next admission"
);
}
}
}
Err(error) => {
tracing::warn!(%error, "capsule policy preload failed; rechecks start uncached")
}
}
}
pub(crate) fn activation(version: &str) -> CapsulePolicyActivation {
CapsulePolicyActivation {
version: version.to_string(),
activated_at: Utc::now(),
}
}
pub(crate) fn prospective_record(
capsule_id: CapsuleId,
manifest: &CapsuleManifest,
) -> CapsuleRecord {
CapsuleRecord {
capsule_id,
manifest: manifest.clone(),
registered_at: Utc::now(),
}
}
}
#[cfg(not(feature = "capsules"))]
pub(crate) fn plane_unavailable() -> crate::ApiError {
crate::ApiError::new(
axum::http::StatusCode::SERVICE_UNAVAILABLE,
"capsule_policy_unavailable",
"the capsule policy plane requires the `capsules` feature — rebuild rusty-agent-server \
with `--features capsules`; capsule workloads fail closed rather than running \
ungoverned"
.into(),
)
}