Skip to main content

strands/vended_interventions/cedar/
mod.rs

1//! Cedar policy authorization of tool calls.
2//!
3//! [`CedarAuthorization`] evaluates [Cedar](https://cedarpolicy.com) policies before each tool
4//! call. A call maps to the request `principal`, `Action::"<tool name>"`, `Resource::"agent"` and
5//! the context `{ input: <tool input>, session: { hour_utc, call_count, ..enricher } }`. It runs
6//! the native `cedar-policy` engine through the JSON interface of Cedar's WebAssembly build, so
7//! decisions and messages match the other Strands SDKs.
8//!
9//! ```
10//! use strands::Agent;
11//! use strands::testing::MockModel;
12//! use strands::vended_interventions::cedar::{CedarAuthorization, CedarAuthorizationConfig};
13//!
14//! let cedar = CedarAuthorization::new(CedarAuthorizationConfig {
15//!     policies: r#"permit(principal, action == Action::"search", resource);"#.into(),
16//!     ..Default::default()
17//! })?;
18//! let agent = Agent::builder()
19//!     .model(MockModel::new())
20//!     .interventions([cedar])
21//!     .printer(false)
22//!     .build()?;
23//! # let _ = agent;
24//! # Ok::<(), strands::Error>(())
25//! ```
26
27mod 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
46/// The app-state key of the per-tool call counts.
47pub 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/// A Cedar entity reference (`TypeAndId`).
54#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
55#[non_exhaustive]
56pub struct TypeAndId {
57    /// The entity type, such as `User` or `Agent::User`.
58    #[serde(rename = "type")]
59    pub entity_type: String,
60    /// The entity id.
61    pub id: String,
62}
63
64impl TypeAndId {
65    /// An entity reference.
66    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/// A tool for schema generation, in the MCP tool shape (`ToolDefinition`).
75#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
76#[serde(rename_all = "camelCase")]
77#[non_exhaustive]
78pub struct ToolDefinition {
79    /// The tool name, which is the Cedar action id.
80    pub name: String,
81    /// The JSON Schema of the tool input.
82    #[serde(skip_serializing_if = "Option::is_none")]
83    pub input_schema: Option<JsonValue>,
84    /// What the tool does.
85    #[serde(skip_serializing_if = "Option::is_none")]
86    pub description: Option<String>,
87}
88
89impl ToolDefinition {
90    /// A definition with an input schema.
91    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/// Entity data: Cedar entity JSON, or the path of a `.json` file.
111#[derive(Debug, Clone, PartialEq)]
112#[non_exhaustive]
113pub enum CedarEntities {
114    /// Entities in Cedar's JSON format.
115    List(Vec<JsonValue>),
116    /// A JSON file with an array of entities.
117    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    /// Resolves the principal from the invocation state; `None` denies.
146    pub struct PrincipalResolver(Fn(&InvocationState) -> Result<Option<TypeAndId>, BoxError>);
147}
148
149/// What a [`ContextEnricher`] gets.
150#[derive(Debug)]
151#[non_exhaustive]
152pub struct ContextEnricherInput<'a> {
153    /// The tool name.
154    pub tool_name: &'a str,
155    /// The tool input.
156    pub tool_input: &'a JsonValue,
157    /// The caller's invocation state.
158    pub invocation_state: &'a InvocationState,
159}
160
161crate::callback::callback! {
162    /// Adds fields to `context.session`; it cannot overwrite `hour_utc` or
163    /// `call_count`.
164    pub struct ContextEnricher(Fn(&ContextEnricherInput<'_>) -> Result<JsonObject, BoxError>);
165}
166
167/// Settings of a [`CedarAuthorization`] (`CedarAuthorizationConfig`).
168#[derive(Clone, Default, bon::Builder)]
169pub struct CedarAuthorizationConfig {
170    /// Cedar policy text, or the path of a `.cedar` file.
171    #[builder(into)]
172    pub policies: String,
173    /// Tools to generate a validation schema from, when no `schema` is given.
174    pub tools: Option<Vec<ToolDefinition>>,
175    /// Entity data; only needed for entity hierarchies and attributes.
176    #[builder(into)]
177    pub entities: Option<CedarEntities>,
178    /// A Cedar schema to validate the policies against: schema text, or the path of a
179    /// `.cedarschema` file. Generated from `tools` when unset.
180    #[builder(into)]
181    pub schema: Option<String>,
182    /// The namespace of actions and resources: `Agent::Action::"search"` instead of
183    /// `Action::"search"`; generated schemas keep it.
184    #[builder(into)]
185    pub namespace: Option<String>,
186    /// A fixed principal. Defaults to `User::"anonymous"`. Exclusive with `principal_resolver`.
187    pub principal: Option<TypeAndId>,
188    /// Resolves the principal per call, for multi-tenant agents. Exclusive with `principal`.
189    #[builder(into)]
190    pub principal_resolver: Option<PrincipalResolver>,
191    /// Adds fields to `context.session`.
192    #[builder(into)]
193    pub context_enricher: Option<ContextEnricher>,
194    /// What happens when the resolver or enricher fails. Defaults to [`OnError::Throw`];
195    /// [`OnError::Deny`] fails closed; [`OnError::Proceed`] runs the tool without any check.
196    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
213/// Where the policies, entities and schema come from; [`CedarAuthorization::reload`] reads them
214/// again.
215struct 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
228/// Authorizes each tool call against Cedar policies (`CedarAuthorization`).
229///
230/// A denial is the tool result `DENIED: Access denied by Cedar policy[: <details>]`. The per-tool
231/// call counts behind `context.session.call_count` are kept in each agent's app state under
232/// [`CEDAR_AUTHORIZATION_STATE_KEY`], so agents that share one handler (such as a parent and its
233/// subagents) each have their own budget; a denied call does not count.
234pub 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    /// A handler with these settings; policies are parsed and validated now.
257    ///
258    /// # Errors
259    ///
260    /// Both a principal and a resolver; a missing policy, schema or entity file
261    /// (`Cedar policy file not found: <path>`); invalid policies (`Invalid Cedar policy: ..`);
262    /// policies that fail schema validation (`Cedar policy validation failed: ..`); a failed
263    /// schema generation (`Schema generation failed: ..`); an entity without a uid.
264    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        // An empty schema or namespace counts as no schema or namespace.
271        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    /// Clears the agent's rate-limit call counts. Pass the agent's `app_state()`.
299    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    /// Reads the policies, entities and schema again (`reload`), validating before the new ones
306    /// take effect.
307    ///
308    /// # Errors
309    ///
310    /// The same as [`new`](Self::new); the previous policies stay in effect.
311    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
399/// Runs Cedar's `is_authorized` on a JSON authorization call.
400fn 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
463/// The agent's call counts; anything but a map of integers counts as none.
464fn 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
514/// Text ending in `suffix` is a path to read; anything else is the content itself.
515fn 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            // A generated schema knows only the tool inputs, not the handler-injected session
581            // fields, so only action errors (typos in tool names) count.
582            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;