1mod schema_generator;
28
29use std::fmt;
30use std::path::PathBuf;
31use std::sync::{PoisonError, RwLock};
32
33use async_trait::async_trait;
34use cedar_policy::ffi::{AuthorizationCall, ValidationCall, check_parse_policy_set_json, is_authorized, validate};
35use indexmap::IndexMap;
36use serde::{Deserialize, Serialize};
37use serde_json::json;
38
39use crate::agent::InvocationState;
40use crate::error::{BoxError, Error, Result};
41use crate::hooks::BeforeToolCallEvent;
42use crate::interventions::{InterventionAction, InterventionHandler, InterventionResult, OnError};
43use crate::state_store::StateStore;
44use crate::types::{JsonObject, JsonValue, ToolSpec};
45
46pub const CEDAR_AUTHORIZATION_STATE_KEY: &str = "cedar-authorization";
48
49const NO_PRINCIPAL: &str = "No principal identity found in invocation state";
50const INVALID_ENTITY: &str = "Invalid entity: each entity must have a uid with type and id";
51const ACTION_ERRORS: [&str; 2] = ["unrecognized action", "unable to find an applicable action"];
52
53#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
55#[non_exhaustive]
56pub struct TypeAndId {
57 #[serde(rename = "type")]
59 pub entity_type: String,
60 pub id: String,
62}
63
64impl TypeAndId {
65 pub fn new(entity_type: impl Into<String>, id: impl Into<String>) -> Self {
67 Self {
68 entity_type: entity_type.into(),
69 id: id.into(),
70 }
71 }
72}
73
74#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
76#[serde(rename_all = "camelCase")]
77#[non_exhaustive]
78pub struct ToolDefinition {
79 pub name: String,
81 #[serde(skip_serializing_if = "Option::is_none")]
83 pub input_schema: Option<JsonValue>,
84 #[serde(skip_serializing_if = "Option::is_none")]
86 pub description: Option<String>,
87}
88
89impl ToolDefinition {
90 pub fn new(name: impl Into<String>, input_schema: JsonValue) -> Self {
92 Self {
93 name: name.into(),
94 input_schema: Some(input_schema),
95 description: None,
96 }
97 }
98}
99
100impl From<ToolSpec> for ToolDefinition {
101 fn from(spec: ToolSpec) -> Self {
102 Self {
103 name: spec.name,
104 input_schema: spec.input_schema,
105 description: Some(spec.description),
106 }
107 }
108}
109
110#[derive(Debug, Clone, PartialEq)]
112#[non_exhaustive]
113pub enum CedarEntities {
114 List(Vec<JsonValue>),
116 File(PathBuf),
118}
119
120impl From<Vec<JsonValue>> for CedarEntities {
121 fn from(entities: Vec<JsonValue>) -> Self {
122 Self::List(entities)
123 }
124}
125
126impl From<PathBuf> for CedarEntities {
127 fn from(path: PathBuf) -> Self {
128 Self::File(path)
129 }
130}
131
132impl From<&str> for CedarEntities {
133 fn from(path: &str) -> Self {
134 Self::File(path.into())
135 }
136}
137
138impl From<String> for CedarEntities {
139 fn from(path: String) -> Self {
140 Self::File(path.into())
141 }
142}
143
144crate::callback::callback! {
145 pub struct PrincipalResolver(Fn(&InvocationState) -> Result<Option<TypeAndId>, BoxError>);
147}
148
149#[derive(Debug)]
151#[non_exhaustive]
152pub struct ContextEnricherInput<'a> {
153 pub tool_name: &'a str,
155 pub tool_input: &'a JsonValue,
157 pub invocation_state: &'a InvocationState,
159}
160
161crate::callback::callback! {
162 pub struct ContextEnricher(Fn(&ContextEnricherInput<'_>) -> Result<JsonObject, BoxError>);
165}
166
167#[derive(Clone, Default, bon::Builder)]
169pub struct CedarAuthorizationConfig {
170 #[builder(into)]
172 pub policies: String,
173 pub tools: Option<Vec<ToolDefinition>>,
175 #[builder(into)]
177 pub entities: Option<CedarEntities>,
178 #[builder(into)]
181 pub schema: Option<String>,
182 #[builder(into)]
185 pub namespace: Option<String>,
186 pub principal: Option<TypeAndId>,
188 #[builder(into)]
190 pub principal_resolver: Option<PrincipalResolver>,
191 #[builder(into)]
193 pub context_enricher: Option<ContextEnricher>,
194 pub on_error: Option<OnError>,
197}
198
199impl fmt::Debug for CedarAuthorizationConfig {
200 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
201 f.debug_struct("CedarAuthorizationConfig")
202 .field("policies", &self.policies)
203 .field("tools", &self.tools)
204 .field("entities", &self.entities)
205 .field("schema", &self.schema)
206 .field("namespace", &self.namespace)
207 .field("principal", &self.principal)
208 .field("on_error", &self.on_error)
209 .finish_non_exhaustive()
210 }
211}
212
213struct Sources {
216 policies: String,
217 entities: Option<CedarEntities>,
218 schema: Option<String>,
219 tools: Option<Vec<ToolDefinition>>,
220 namespace: Option<String>,
221}
222
223struct Loaded {
224 policies: String,
225 entities: Vec<JsonValue>,
226}
227
228pub struct CedarAuthorization {
235 sources: Sources,
236 loaded: RwLock<Loaded>,
237 principal: Option<TypeAndId>,
238 principal_resolver: Option<PrincipalResolver>,
239 context_enricher: Option<ContextEnricher>,
240 on_error: OnError,
241 action_type: String,
242 resource: TypeAndId,
243}
244
245impl fmt::Debug for CedarAuthorization {
246 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
247 f.debug_struct("CedarAuthorization")
248 .field("principal", &self.principal)
249 .field("action_type", &self.action_type)
250 .field("resource", &self.resource)
251 .finish_non_exhaustive()
252 }
253}
254
255impl CedarAuthorization {
256 pub fn new(config: CedarAuthorizationConfig) -> Result<Self> {
265 if config.principal.is_some() && config.principal_resolver.is_some() {
266 return Err(Error::other(
267 "Provide either `principal` or `principal_resolver`, not both",
268 ));
269 }
270 let sources = Sources {
272 policies: config.policies,
273 entities: config.entities,
274 schema: config.schema.filter(|schema| !schema.is_empty()),
275 tools: config.tools,
276 namespace: config.namespace.filter(|namespace| !namespace.is_empty()),
277 };
278 let loaded = sources.load()?;
279 let namespace = sources.namespace.as_deref();
280 let principal = match (&config.principal_resolver, config.principal) {
281 (Some(_), _) => None,
282 (None, Some(principal)) => Some(principal),
283 (None, None) => Some(TypeAndId::new(qualify(namespace, "User"), "anonymous")),
284 };
285 let resource_id = if namespace.is_some() { "default" } else { "agent" };
286 Ok(Self {
287 action_type: qualify(namespace, "Action"),
288 resource: TypeAndId::new(qualify(namespace, "Resource"), resource_id),
289 sources,
290 loaded: RwLock::new(loaded),
291 principal,
292 principal_resolver: config.principal_resolver,
293 context_enricher: config.context_enricher,
294 on_error: config.on_error.unwrap_or_default(),
295 })
296 }
297
298 pub fn reset_call_counts(&self, app_state: &StateStore) {
300 if let Err(error) = app_state.set(CEDAR_AUTHORIZATION_STATE_KEY, json!({})) {
301 tracing::warn!("error=<{error}> | failed to reset the cedar call counts");
302 }
303 }
304
305 pub fn reload(&self) -> Result<()> {
312 let loaded = self.sources.load()?;
313 *self.loaded.write().unwrap_or_else(PoisonError::into_inner) = loaded;
314 Ok(())
315 }
316
317 fn principal(&self, invocation_state: &InvocationState) -> Result<Option<TypeAndId>, BoxError> {
318 match (&self.principal, &self.principal_resolver) {
319 (Some(principal), _) => Ok(Some(principal.clone())),
320 (None, Some(resolve)) => resolve(invocation_state),
321 (None, None) => Ok(None),
322 }
323 }
324
325 fn authorize(&self, event: &BeforeToolCallEvent) -> InterventionResult<BeforeToolCallEvent> {
326 let principal = self
327 .principal(event.invocation_state())?
328 .filter(|principal| !principal.entity_type.is_empty() && !principal.id.is_empty());
329 let Some(principal) = principal else {
330 return Ok(InterventionAction::deny(NO_PRINCIPAL));
331 };
332 let tool_name = event.tool_use().name.as_str();
333 let app_state = event.agent().app_state();
334 let call_count = increment_call_count(app_state, tool_name);
335 let tool_input = match &event.tool_use().input {
336 JsonValue::Null => json!({}),
337 input => input.clone(),
338 };
339 let mut session = match &self.context_enricher {
340 Some(enrich) => enrich(&ContextEnricherInput {
341 tool_name,
342 tool_input: &tool_input,
343 invocation_state: event.invocation_state(),
344 })?,
345 None => JsonObject::new(),
346 };
347 session.insert("hour_utc".to_owned(), utc_hour().into());
348 session.insert("call_count".to_owned(), call_count.into());
349
350 let call = {
351 let loaded = self.loaded.read().unwrap_or_else(PoisonError::into_inner);
352 json!({
353 "principal": principal,
354 "action": {"type": self.action_type, "id": tool_name},
355 "resource": self.resource,
356 "context": {"input": tool_input, "session": session},
357 "policies": {"staticPolicies": loaded.policies},
358 "entities": loaded.entities,
359 })
360 };
361 match evaluate(call) {
362 Decision::Allow => Ok(InterventionAction::proceed()),
363 Decision::Deny(reason) => {
364 decrement_call_count(app_state, tool_name);
365 Ok(InterventionAction::deny(reason))
366 }
367 }
368 }
369}
370
371#[async_trait]
372impl InterventionHandler for CedarAuthorization {
373 fn name(&self) -> &str {
374 "cedar-authorization"
375 }
376
377 fn on_error(&self) -> OnError {
378 self.on_error
379 }
380
381 async fn before_tool_call(&self, event: &mut BeforeToolCallEvent) -> InterventionResult<BeforeToolCallEvent> {
382 self.authorize(event)
383 }
384}
385
386enum Decision {
387 Allow,
388 Deny(String),
389}
390
391fn messages(errors: &[JsonValue], pointer: &str) -> Vec<String> {
392 errors
393 .iter()
394 .filter_map(|error| error.pointer(pointer).and_then(JsonValue::as_str))
395 .map(str::to_owned)
396 .collect()
397}
398
399fn evaluate(call: JsonValue) -> Decision {
401 let answer = match serde_json::from_value::<AuthorizationCall>(call) {
402 Ok(call) => is_authorized(call),
403 Err(error) => return Decision::Deny(format!("Cedar evaluation failed: {error}")),
404 };
405 let answer = serde_json::to_value(answer).unwrap_or(JsonValue::Null);
406 if !matches!(answer.get("type").and_then(JsonValue::as_str), Some("success")) {
407 let errors = answer
408 .get("errors")
409 .and_then(JsonValue::as_array)
410 .cloned()
411 .unwrap_or_default();
412 return Decision::Deny(format!(
413 "Cedar evaluation failed: {}",
414 messages(&errors, "/message").join(", ")
415 ));
416 }
417 let response = &answer["response"];
418 if response["decision"] == "allow" {
419 return Decision::Allow;
420 }
421 let reasons = response["diagnostics"]["reason"]
422 .as_array()
423 .map(|reasons| {
424 reasons
425 .iter()
426 .filter_map(JsonValue::as_str)
427 .map(str::to_owned)
428 .collect::<Vec<_>>()
429 })
430 .unwrap_or_default();
431 let errors = response["diagnostics"]["errors"]
432 .as_array()
433 .cloned()
434 .unwrap_or_default();
435 let details: Vec<String> = reasons
436 .into_iter()
437 .chain(messages(&errors, "/error/message"))
438 .filter(|detail| !detail.is_empty())
439 .collect();
440 if details.is_empty() {
441 return Decision::Deny("Access denied by Cedar policy".to_owned());
442 }
443 Decision::Deny(format!("Access denied by Cedar policy: {}", details.join(", ")))
444}
445
446fn increment_call_count(app_state: &StateStore, tool_name: &str) -> i64 {
447 let mut counts = stored_counts(app_state);
448 let next = counts.get(tool_name).copied().unwrap_or(0) + 1;
449 counts.insert(tool_name.to_owned(), next);
450 store_counts(app_state, &counts);
451 next
452}
453
454fn decrement_call_count(app_state: &StateStore, tool_name: &str) {
455 let mut counts = stored_counts(app_state);
456 let Some(current) = counts.get_mut(tool_name).filter(|current| **current > 0) else {
457 return;
458 };
459 *current -= 1;
460 store_counts(app_state, &counts);
461}
462
463fn stored_counts(app_state: &StateStore) -> IndexMap<String, i64> {
465 app_state
466 .get(CEDAR_AUTHORIZATION_STATE_KEY)
467 .ok()
468 .flatten()
469 .unwrap_or_default()
470}
471
472fn store_counts(app_state: &StateStore, counts: &IndexMap<String, i64>) {
473 if let Err(error) = app_state.set(CEDAR_AUTHORIZATION_STATE_KEY, counts) {
474 tracing::warn!("error=<{error}> | failed to store the cedar call counts");
475 }
476}
477
478fn qualify(namespace: Option<&str>, name: &str) -> String {
479 match namespace {
480 Some(namespace) => format!("{namespace}::{name}"),
481 None => name.to_owned(),
482 }
483}
484
485fn utc_hour() -> i64 {
486 jiff::Timestamp::now().as_second().rem_euclid(86_400) / 3_600
487}
488
489impl Sources {
490 fn load(&self) -> Result<Loaded> {
491 let policies = load_policies(&self.policies)?;
492 let entities = load_entities(self.entities.as_ref())?;
493 let (schema, generated) = match (&self.schema, &self.tools) {
494 (Some(schema), _) => (Some(load_schema(schema)?), false),
495 (None, Some(tools)) => (
496 Some(schema_generator::generate_schema(tools, self.namespace.as_deref())?),
497 true,
498 ),
499 (None, None) => (None, false),
500 };
501 validate_policies(&policies, schema.as_deref(), generated)?;
502 Ok(Loaded { policies, entities })
503 }
504}
505
506fn load_policies(policies: &str) -> Result<String> {
507 load_file_if(policies, ".cedar", "Cedar policy file not found")
508}
509
510fn load_schema(schema: &str) -> Result<String> {
511 load_file_if(schema, ".cedarschema", "Cedar schema file not found")
512}
513
514fn load_file_if(text: &str, suffix: &str, missing: &str) -> Result<String> {
516 if !text.ends_with(suffix) {
517 return Ok(text.to_owned());
518 }
519 std::fs::read_to_string(text).map_err(|_| Error::other(format!("{missing}: {text}")))
520}
521
522fn load_entities(entities: Option<&CedarEntities>) -> Result<Vec<JsonValue>> {
523 let entities = match entities {
524 None => return Ok(Vec::new()),
525 Some(CedarEntities::List(entities)) => entities.clone(),
526 Some(CedarEntities::File(path)) => serde_json::from_str(&std::fs::read_to_string(path)?)?,
527 };
528 for entity in &entities {
529 let uid = entity.get("uid").ok_or_else(|| Error::other(INVALID_ENTITY))?;
530 let uid = uid.get("__entity").unwrap_or(uid);
531 let present = |field: &str| {
532 uid.get(field)
533 .and_then(JsonValue::as_str)
534 .is_some_and(|value| !value.is_empty())
535 };
536 if !present("type") || !present("id") {
537 return Err(Error::other(INVALID_ENTITY));
538 }
539 }
540 Ok(entities)
541}
542
543fn validate_policies(policies: &str, schema: Option<&str>, generated: bool) -> Result<()> {
544 let parsed = check_parse_policy_set_json(json!({"staticPolicies": policies}))?;
545 if parsed.get("type").and_then(JsonValue::as_str) != Some("success") {
546 let errors = parsed
547 .get("errors")
548 .and_then(JsonValue::as_array)
549 .cloned()
550 .unwrap_or_default();
551 return Err(Error::other(format!(
552 "Invalid Cedar policy: {}",
553 messages(&errors, "/message").join(", ")
554 )));
555 }
556 let Some(schema) = schema.filter(|schema| !schema.is_empty()) else {
557 return Ok(());
558 };
559 let call: ValidationCall = serde_json::from_value(json!({
560 "schema": schema,
561 "policies": {"staticPolicies": policies},
562 }))?;
563 let answer = serde_json::to_value(validate(call))?;
564 let failed = |errors: Vec<String>| Error::other(format!("Cedar policy validation failed: {}", errors.join(", ")));
565 if !matches!(answer.get("type").and_then(JsonValue::as_str), Some("success")) {
566 let errors = answer
567 .get("errors")
568 .and_then(JsonValue::as_array)
569 .cloned()
570 .unwrap_or_default();
571 return Err(failed(messages(&errors, "/message")));
572 }
573 let errors: Vec<String> = answer["validationErrors"]
574 .as_array()
575 .cloned()
576 .unwrap_or_default()
577 .iter()
578 .filter_map(|error| {
579 let message = error.pointer("/error/message")?.as_str()?;
580 let relevant = !generated || ACTION_ERRORS.iter().any(|needle| message.contains(needle));
583 relevant.then(|| format!("{}: {message}", error["policyId"].as_str().unwrap_or_default()))
584 })
585 .collect();
586 if errors.is_empty() {
587 return Ok(());
588 }
589 Err(failed(errors))
590}
591
592#[cfg(test)]
593mod tests;