Skip to main content

strands/vended_interventions/dogwood/
mod.rs

1//! Dogwood policy authorization of tool calls.
2//!
3//! [`DogwoodAuthorization`] evaluates a [Dogwood](https://github.com/dogwood-policy/dogwood)
4//! `.dw` policy set before each tool call and records each allowed call's result afterwards, so
5//! temporal rules (`when temporal { formerly within 1h Action::"search"::response{} }`) can
6//! correlate across calls. A call maps to the principal, `Action::"<tool name>"` (qualified by the
7//! schema's namespace when it has one), `Resource::"agent"`, and `input` (the tool arguments) in
8//! both the Cedar context and the temporal record. It runs `dogwood-language`, the engine behind
9//! Dogwood's WebAssembly build, so decisions and messages match the other Strands SDKs.
10//!
11//! ```
12//! use strands::Agent;
13//! use strands::testing::MockModel;
14//! use strands::types::ToolSpec;
15//! use strands::vended_interventions::dogwood::{DogwoodAuthorization, DogwoodAuthorizationConfig};
16//!
17//! let search = ToolSpec::new("search", "Search for information");
18//! let dogwood = DogwoodAuthorization::new(DogwoodAuthorizationConfig {
19//!     policies: r#"permit(principal, action == Action::"search", resource);"#.into(),
20//!     tools: Some(vec![search]),
21//!     ..Default::default()
22//! })?;
23//! let agent = Agent::builder()
24//!     .model(MockModel::new())
25//!     .interventions([dogwood])
26//!     .printer(false)
27//!     .build()?;
28//! # let _ = agent;
29//! # Ok::<(), strands::Error>(())
30//! ```
31
32use std::collections::{BTreeMap, HashMap, HashSet};
33use std::fmt;
34use std::panic::{AssertUnwindSafe, catch_unwind};
35use std::sync::{LazyLock, Mutex, MutexGuard, PoisonError};
36
37use async_trait::async_trait;
38use dogwood_ops::ops::validate_policies;
39use dogwood_ops::{AuthorizerDecision, Diagnostic, EventInput, OpError, SchemaInputs};
40use regex::Regex;
41use serde::{Deserialize, Serialize};
42
43use crate::agent::InvocationState;
44use crate::clock::Clock;
45use crate::error::{BoxError, Error, Result};
46use crate::hooks::{AfterToolCallEvent, BeforeToolCallEvent};
47use crate::interventions::{InterventionAction, InterventionHandler, InterventionResult, OnError};
48use crate::types::{JsonObject, JsonValue, ToolResultStatus, ToolSpec};
49
50mod engine;
51
52use engine::Engine;
53
54/// The one context group a [`ContextEnricher`] can add.
55const ENRICHED_GROUP: &str = "session";
56
57/// The context group carrying the decision time, `context.system.now`.
58const SYSTEM_GROUP: &str = "system";
59
60/// The event kind that is a decision point.
61const REQUEST: &str = "request";
62
63/// The namespace Dogwood's schema generator emits; it takes no namespace of its own.
64const GENERATED_NAMESPACE: &str = "Drupe";
65
66/// The resource entity Dogwood's schema generator emits, from its MCP-gateway template.
67const GENERATED_RESOURCE: &str = "Gateway";
68
69/// The resource entity a schema declares, matching `CedarAuthorization`.
70const RESOURCE: &str = "Resource";
71
72/// Identifiers Cedar's grammar admits as a namespace and its parser then rejects.
73const CEDAR_RESERVED: [&str; 9] = ["true", "false", "if", "then", "else", "in", "is", "like", "has"];
74
75/// Cedar reserves this prefix for its own types.
76const CEDAR_INTERNAL_PREFIX: &str = "__cedar";
77
78/// An entity declaration with attributes: in a generated schema, an object parameter.
79static PARAMETER_ENTITY: LazyLock<Option<Regex>> = LazyLock::new(|| Regex::new(r"(?m)^(\s*)entity (\w+) = \{").ok());
80
81const NO_PRINCIPAL: &str = "No principal identity found in invocation state";
82const UNUSABLE: &str = "Dogwood authorizer is no longer usable; denying";
83const PANICKED: &str = "Dogwood evaluation panicked; denying";
84
85/// Event field groups, `group -> { field -> value }`.
86type EventGroups = BTreeMap<String, BTreeMap<String, JsonValue>>;
87
88/// A Dogwood entity reference (`EntityRef`).
89#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
90#[non_exhaustive]
91pub struct EntityRef {
92    /// The entity type, namespace included, such as `User` or `Acme::User`.
93    #[serde(rename = "type")]
94    pub entity_type: String,
95    /// The raw, un-escaped entity id.
96    pub id: String,
97}
98
99impl EntityRef {
100    /// An entity reference.
101    pub fn new(entity_type: impl Into<String>, id: impl Into<String>) -> Self {
102        Self {
103            entity_type: entity_type.into(),
104            id: id.into(),
105        }
106    }
107
108    fn to_dogwood(&self) -> dogwood_ops::EntityRef {
109        dogwood_ops::EntityRef {
110            ty: self.entity_type.clone(),
111            id: self.id.clone(),
112        }
113    }
114}
115
116/// An entity supplied to every decision: its identity plus the attributes and direct parents a
117/// policy reads (`EntityInput`).
118#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
119#[non_exhaustive]
120pub struct EntityInput {
121    /// The entity type, namespace included.
122    #[serde(rename = "type")]
123    pub entity_type: String,
124    /// The raw, un-escaped entity id.
125    pub id: String,
126    /// Attributes, `name -> value`, validated against the action schema at decision time.
127    #[serde(default)]
128    pub attrs: JsonObject,
129    /// Direct parents (`memberOf` edges); Cedar computes the transitive closure.
130    #[serde(default)]
131    pub parents: Vec<EntityRef>,
132}
133
134impl EntityInput {
135    /// An entity with no attributes or parents.
136    pub fn new(entity_type: impl Into<String>, id: impl Into<String>) -> Self {
137        Self {
138            entity_type: entity_type.into(),
139            id: id.into(),
140            ..Self::default()
141        }
142    }
143
144    /// Sets the attributes.
145    #[must_use]
146    pub fn with_attrs(mut self, attrs: JsonObject) -> Self {
147        self.attrs = attrs;
148        self
149    }
150
151    /// Sets the direct parents.
152    #[must_use]
153    pub fn with_parents(mut self, parents: impl IntoIterator<Item = EntityRef>) -> Self {
154        self.parents = parents.into_iter().collect();
155        self
156    }
157
158    fn to_dogwood(&self) -> dogwood_ops::EntityInput {
159        dogwood_ops::EntityInput {
160            ty: self.entity_type.clone(),
161            id: self.id.clone(),
162            attrs: self
163                .attrs
164                .iter()
165                .map(|(name, value)| (name.clone(), value.clone()))
166                .collect(),
167            parents: self.parents.iter().map(EntityRef::to_dogwood).collect(),
168        }
169    }
170}
171
172crate::callback::callback! {
173    /// Resolves the principal from the invocation state; `None` denies (fail-closed).
174    pub struct PrincipalResolver(Fn(&InvocationState) -> Result<Option<EntityRef>, BoxError>);
175}
176
177/// What a [`ContextEnricher`] gets.
178#[derive(Debug)]
179#[non_exhaustive]
180pub struct ContextEnricherInput<'a> {
181    /// The tool name.
182    pub tool_name: &'a str,
183    /// The tool input.
184    pub tool_input: &'a JsonValue,
185    /// The caller's invocation state.
186    pub invocation_state: &'a InvocationState,
187}
188
189crate::callback::callback! {
190    /// Adds fields to the `session` group of the Cedar request context, read by a policy as
191    /// `context.session.<field>`. The fields reach `when { .. }` conditions only: the default
192    /// event schema declares a tool's input fields and nothing else, so a temporal predicate
193    /// cannot read them.
194    pub struct ContextEnricher(Fn(&ContextEnricherInput<'_>) -> Result<JsonObject, BoxError>);
195}
196
197/// Settings of a [`DogwoodAuthorization`] (`DogwoodAuthorizationConfig`).
198#[derive(Clone, Default, bon::Builder)]
199pub struct DogwoodAuthorizationConfig {
200    /// Dogwood policy text, or the path of a `.dw` file.
201    #[builder(into)]
202    pub policies: String,
203    /// Tools the action schema is generated from, when no `action_schema` is given. A tool's spec
204    /// is [`Tool::tool_spec`](crate::tools::Tool::tool_spec).
205    pub tools: Option<Vec<ToolSpec>>,
206    /// Cedar action schema text, or the path of a `.cedarschema` file; generated from `tools`
207    /// when unset. The handler reads the namespace from the schema's actions, so the schema must
208    /// declare its user entity as `User` and its resource entity as `Resource`.
209    #[builder(into)]
210    pub action_schema: Option<String>,
211    /// Entities supplied to every decision. Needs `action_schema`: a generated schema declares
212    /// `User` and `Resource` with no attributes and no membership.
213    pub entities: Option<Vec<EntityInput>>,
214    /// The namespace of a generated action schema: `Acme::Action::"search"` instead of
215    /// `Action::"search"`, with the default principal `Acme::User::"anonymous"`. Only valid with
216    /// `tools`.
217    #[builder(into)]
218    pub namespace: Option<String>,
219    /// A fixed principal. Defaults to `User::"anonymous"`, qualified by the schema's namespace.
220    /// Exclusive with `principal_resolver`; against a generated schema its type must be `User`.
221    pub principal: Option<EntityRef>,
222    /// Resolves the principal per call, for multi-tenant agents. Exclusive with `principal`.
223    #[builder(into)]
224    pub principal_resolver: Option<PrincipalResolver>,
225    /// Adds fields to `context.session`.
226    #[builder(into)]
227    pub context_enricher: Option<ContextEnricher>,
228    /// What happens when the resolver or enricher fails. Defaults to [`OnError::Throw`];
229    /// [`OnError::Deny`] fails closed; [`OnError::Proceed`] runs the tool without any check. A
230    /// failed Dogwood decision always denies.
231    pub on_error: Option<OnError>,
232}
233
234impl fmt::Debug for DogwoodAuthorizationConfig {
235    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
236        f.debug_struct("DogwoodAuthorizationConfig")
237            .field("policies", &self.policies)
238            .field("tools", &self.tools)
239            .field("action_schema", &self.action_schema)
240            .field("entities", &self.entities)
241            .field("namespace", &self.namespace)
242            .field("principal", &self.principal)
243            .field("on_error", &self.on_error)
244            .finish_non_exhaustive()
245    }
246}
247
248/// What recording a tool's result needs, captured when the call was allowed.
249struct AllowedCall {
250    tool_name: String,
251    action: String,
252    principal: EntityRef,
253    logged: EventGroups,
254}
255
256struct History {
257    authorizer: Engine,
258    /// Calls decided and allowed, by tool-use id, until their result is recorded.
259    allowed_calls: HashMap<String, AllowedCall>,
260    /// Set by a panic inside the engine, whose state is then not trusted: every later decision
261    /// denies without calling in.
262    unusable: bool,
263}
264
265/// One event's fields before the engine's timestamp is applied.
266struct Fields<'a> {
267    action: &'a str,
268    kind: &'a str,
269    principal: &'a EntityRef,
270    logged: EventGroups,
271    context: EventGroups,
272}
273
274enum Submitted {
275    Decided(Option<AuthorizerDecision>),
276    Failed(String),
277    Panicked,
278}
279
280/// Authorizes each tool call against a Dogwood policy set (`DogwoodAuthorization`).
281///
282/// Holds temporal history, so one instance is one ordered history. Every temporal predicate is
283/// pinned to the deciding principal, so one instance serves many principals without their
284/// histories mixing. History is never pruned; [`reset`](Self::reset) drops every principal's at
285/// once.
286///
287/// A tool's result is not recorded, only the fact that it returned (or failed), so a predicate on
288/// a result field type-checks and then never matches. A condition compares the tool arguments as
289/// the model emitted them, and a generated schema is typed to match: an enum parameter compares
290/// as a string and a number parameter as a whole number.
291pub struct DogwoodAuthorization {
292    history: Mutex<History>,
293    actions_by_tool: HashMap<String, String>,
294    declared_kinds: HashSet<String>,
295    /// Tools whose action context declares `system`, which a conforming request must supply.
296    system_tools: HashSet<String>,
297    resource: EntityRef,
298    default_principal: Option<EntityRef>,
299    /// The only principal type a generated schema admits; `None` for a hand-written schema.
300    principal_type: Option<String>,
301    principal_resolver: Option<PrincipalResolver>,
302    context_enricher: Option<ContextEnricher>,
303    entities: Vec<dogwood_ops::EntityInput>,
304    on_error: OnError,
305    clock: Clock,
306}
307
308impl fmt::Debug for DogwoodAuthorization {
309    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
310        f.debug_struct("DogwoodAuthorization")
311            .field("resource", &self.resource)
312            .field("default_principal", &self.default_principal)
313            .field("principal_type", &self.principal_type)
314            .finish_non_exhaustive()
315    }
316}
317
318impl DogwoodAuthorization {
319    /// A handler with these settings; the policy set is parsed, type-checked and lowered now.
320    ///
321    /// # Errors
322    ///
323    /// Neither `action_schema` nor `tools`; both `principal` and `principal_resolver`;
324    /// non-empty `entities` without `action_schema`; `namespace` with `action_schema`, or a
325    /// namespace that is not `::`-separated Cedar identifiers; a `principal` of a type the
326    /// generated schema does not declare; a missing `.dw` or `.cedarschema` file; a policy set
327    /// that fails to parse or type-check against the schema (`Dogwood policy validation
328    /// failed: ..`).
329    pub fn new(config: DogwoodAuthorizationConfig) -> Result<Self> {
330        let action_schema_source = config.action_schema.clone().filter(|schema| !schema.is_empty());
331        check_config_shape(&config, action_schema_source.is_some())?;
332        check_cedar_namespace(config.namespace.as_deref())?;
333
334        let policies = load_source(&config.policies, ".dw")?;
335        let action_schema = match &action_schema_source {
336            Some(schema) => load_source(schema, ".cedarschema")?,
337            None => apply_namespace(
338                &generate_action_schema(config.tools.as_deref().unwrap_or_default())?,
339                config.namespace.as_deref(),
340            ),
341        };
342        // The one finding a generated schema causes by construction: it cannot declare the
343        // enricher's context group. Everything else is fatal, including a typo in a temporal
344        // predicate.
345        let tolerate_enriched_group = action_schema_source.is_none() && config.context_enricher.is_some();
346        let report = validate_policies(&policies, &SchemaInputs::default(), &action_schema).map_err(dogwood_error)?;
347        check_policy_type_checks(&report.errors, tolerate_enriched_group)?;
348
349        let authorizer = Engine::new(&policies, &action_schema).map_err(dogwood_error)?;
350        let system_tools = tools_with_system_context(&authorizer.cedar_schema_json()?)?;
351        let actions = authorizer.actions();
352        let namespace = namespace_prefix_of(&actions);
353        let actions_by_tool = actions
354            .iter()
355            .map(|action| (tool_name_of(action).to_owned(), action.clone()))
356            .collect();
357        let principal_type = action_schema_source.is_none().then(|| format!("{namespace}User"));
358        let default_principal = match (&config.principal_resolver, config.principal) {
359            (Some(_), _) => None,
360            (None, Some(principal)) => Some(principal),
361            (None, None) => Some(EntityRef::new(format!("{namespace}User"), "anonymous")),
362        };
363        let handler = Self {
364            declared_kinds: authorizer.event_kinds().into_iter().collect(),
365            history: Mutex::new(History {
366                authorizer,
367                allowed_calls: HashMap::new(),
368                unusable: false,
369            }),
370            actions_by_tool,
371            system_tools,
372            resource: EntityRef::new(format!("{namespace}{RESOURCE}"), "agent"),
373            default_principal,
374            principal_type,
375            principal_resolver: config.principal_resolver,
376            context_enricher: config.context_enricher,
377            entities: config
378                .entities
379                .unwrap_or_default()
380                .iter()
381                .map(EntityInput::to_dogwood)
382                .collect(),
383            on_error: config.on_error.unwrap_or_default(),
384            clock: Clock::system(),
385        };
386        if let Some(principal) = &handler.default_principal
387            && !handler.declares_principal_type(&principal.entity_type)
388        {
389            return Err(Error::other(format!(
390                "`principal` must be of type `{}`, got `{}`",
391                handler.principal_type.as_deref().unwrap_or_default(),
392                principal.entity_type
393            )));
394        }
395        Ok(handler)
396    }
397
398    /// Drops the accumulated temporal history of every principal this instance has decided for.
399    pub fn reset(&self) {
400        let mut history = self.history();
401        if history.unusable {
402            return;
403        }
404        // A call allowed against the old history must not record its result into the new one.
405        history.allowed_calls.clear();
406        history.authorizer.reset();
407    }
408
409    #[cfg(test)]
410    fn with_clock(mut self, clock: Clock) -> Self {
411        self.clock = clock;
412        self
413    }
414
415    fn history(&self) -> MutexGuard<'_, History> {
416        self.history.lock().unwrap_or_else(PoisonError::into_inner)
417    }
418
419    fn declares_principal_type(&self, entity_type: &str) -> bool {
420        self.principal_type
421            .as_deref()
422            .is_none_or(|declared| declared == entity_type)
423    }
424
425    fn principal(&self, invocation_state: &InvocationState) -> Result<Option<EntityRef>, BoxError> {
426        match (&self.default_principal, &self.principal_resolver) {
427            (Some(principal), _) => Ok(Some(principal.clone())),
428            (None, Some(resolve)) => resolve(invocation_state),
429            (None, None) => Ok(None),
430        }
431    }
432
433    fn decide(&self, event: &BeforeToolCallEvent) -> InterventionResult<BeforeToolCallEvent> {
434        let tool_use = event.tool_use();
435        {
436            let mut history = self.history();
437            if history.unusable {
438                return Ok(InterventionAction::deny(UNUSABLE));
439            }
440            // Resuming an interrupt fires this event again for a call already in the history.
441            // The tool name is matched too, so an abandoned interrupt's entry cannot wave through
442            // a later call that reuses its id for another tool.
443            let decided = history
444                .allowed_calls
445                .get(&tool_use.tool_use_id)
446                .is_some_and(|call| call.tool_name == tool_use.name);
447            if decided {
448                return Ok(InterventionAction::proceed());
449            }
450            history.allowed_calls.remove(&tool_use.tool_use_id);
451        }
452
453        let principal = self
454            .principal(event.invocation_state())?
455            .filter(|principal| !principal.entity_type.is_empty() && !principal.id.is_empty());
456        let Some(principal) = principal else {
457            return Ok(InterventionAction::deny(NO_PRINCIPAL));
458        };
459        if !self.declares_principal_type(&principal.entity_type) {
460            return Ok(InterventionAction::deny(format!(
461                "Principal type '{}' is not declared by the Dogwood action schema; denying",
462                principal.entity_type
463            )));
464        }
465        let Some(action) = self.actions_by_tool.get(&tool_use.name) else {
466            return Ok(InterventionAction::deny(format!(
467                "Tool '{}' is not declared by the Dogwood action schema; denying",
468                tool_use.name
469            )));
470        };
471
472        let enriched = self.enrich(&tool_use.name, &tool_use.input, event.invocation_state())?;
473        let input = match input_group(&tool_use.input) {
474            Ok(input) => input,
475            Err(error) => return Ok(InterventionAction::deny(format!("Dogwood could not decide: {error}"))),
476        };
477        let logged = EventGroups::from([("input".to_owned(), input)]);
478        let mut context = logged.clone();
479        // No enriched fields means no group: the schema declares none for it.
480        if let Some(enriched) = enriched.filter(|fields| !fields.is_empty()) {
481            context.insert(ENRICHED_GROUP.to_owned(), enriched);
482        }
483
484        let mut history = self.history();
485        let request = self.event(
486            &history,
487            Fields {
488                action,
489                kind: REQUEST,
490                principal: &principal,
491                logged: logged.clone(),
492                context,
493            },
494        );
495        let decision = match self.submit(&mut history, &request) {
496            Submitted::Decided(decision) => decision,
497            Submitted::Failed(error) => {
498                return Ok(InterventionAction::deny(format!("Dogwood could not decide: {error}")));
499            }
500            Submitted::Panicked => return Ok(InterventionAction::deny(PANICKED)),
501        };
502        if let Some(denial) = denial_reason(decision.as_ref(), &tool_use.name) {
503            return Ok(InterventionAction::deny(denial));
504        }
505        history.allowed_calls.insert(
506            tool_use.tool_use_id.clone(),
507            AllowedCall {
508                tool_name: tool_use.name.clone(),
509                action: action.clone(),
510                principal,
511                logged,
512            },
513        );
514        Ok(InterventionAction::proceed())
515    }
516
517    /// Records an allowed call's result as a history-only `response` or `error` event. Runs no
518    /// user code: the principal and fields are the ones the request was decided under.
519    fn record(&self, event: &AfterToolCallEvent) {
520        let tool_use = event.tool_use();
521        let mut history = self.history();
522        let matches = history
523            .allowed_calls
524            .get(&tool_use.tool_use_id)
525            .is_some_and(|call| call.tool_name == tool_use.name);
526        if history.unusable || !matches {
527            return;
528        }
529        let Some(allowed) = history.allowed_calls.remove(&tool_use.tool_use_id) else {
530            return;
531        };
532        // An error status with no error is how the executor reports a call a later handler
533        // blocked; only an attached error proves the tool ran.
534        if event.result().status == ToolResultStatus::Error && event.error().is_none() {
535            return;
536        }
537        let kind = if event.error().is_some() { "error" } else { "response" };
538        if !self.declared_kinds.contains(kind) {
539            return;
540        }
541        let result = self.event(
542            &history,
543            Fields {
544                action: &allowed.action,
545                kind,
546                principal: &allowed.principal,
547                logged: allowed.logged.clone(),
548                context: allowed.logged,
549            },
550        );
551        let failure = match self.submit(&mut history, &result) {
552            Submitted::Decided(_) => return,
553            Submitted::Failed(error) => error,
554            Submitted::Panicked => PANICKED.to_owned(),
555        };
556        // An unrecorded result cannot be enforced, so a later rule keyed on it does not fire.
557        // Failing the tool call that already ran would be worse.
558        tracing::warn!(
559            "tool=<{}>, kind=<{kind}> | dogwood could not record a tool result, {failure}",
560            allowed.tool_name
561        );
562    }
563
564    fn enrich(
565        &self,
566        tool_name: &str,
567        tool_input: &JsonValue,
568        invocation_state: &InvocationState,
569    ) -> Result<Option<BTreeMap<String, JsonValue>>, BoxError> {
570        let Some(enrich) = &self.context_enricher else {
571            return Ok(None);
572        };
573        let empty = JsonValue::Object(JsonObject::new());
574        let tool_input = if tool_input.is_null() { &empty } else { tool_input };
575        let fields = enrich(&ContextEnricherInput {
576            tool_name,
577            tool_input,
578            invocation_state,
579        })?;
580        Ok(Some(fields.into_iter().collect()))
581    }
582
583    fn event(&self, history: &History, fields: Fields<'_>) -> EventInput {
584        let timestamp = self.timestamp(history);
585        let mut context = fields.context;
586        if fields.kind == REQUEST && self.system_tools.contains(tool_name_of(fields.action)) {
587            context.insert(SYSTEM_GROUP.to_owned(), system_group(timestamp));
588        }
589        EventInput {
590            action: fields.action.to_owned(),
591            kind: fields.kind.to_owned(),
592            timestamp,
593            principal: Some(fields.principal.to_dogwood()),
594            resource: Some(self.resource.to_dogwood()),
595            logged: fields.logged,
596            context,
597            entities: self.entities.clone(),
598        }
599    }
600
601    /// Feeds one event to the engine. A panic inside it latches the handler unusable.
602    fn submit(&self, history: &mut History, event: &EventInput) -> Submitted {
603        let authorizer = &mut history.authorizer;
604        match catch_unwind(AssertUnwindSafe(|| authorizer.is_authorized(event))) {
605            Ok(Ok(decision)) => Submitted::Decided(decision),
606            Ok(Err(error)) => Submitted::Failed(error),
607            Err(_) => {
608                history.unusable = true;
609                Submitted::Panicked
610            }
611        }
612    }
613
614    /// Epoch seconds, never going backwards: the engine rejects a timestamp before the previous
615    /// event's, and a system clock can step back.
616    fn timestamp(&self, history: &History) -> i64 {
617        let now = self.clock.now().as_second();
618        now.max(history.authorizer.last_timestamp().unwrap_or(0))
619    }
620}
621
622#[async_trait]
623impl InterventionHandler for DogwoodAuthorization {
624    fn name(&self) -> &str {
625        "dogwood-authorization"
626    }
627
628    fn on_error(&self) -> OnError {
629        self.on_error
630    }
631
632    async fn before_tool_call(&self, event: &mut BeforeToolCallEvent) -> InterventionResult<BeforeToolCallEvent> {
633        self.decide(event)
634    }
635
636    async fn after_tool_call(&self, event: &mut AfterToolCallEvent) -> InterventionResult<AfterToolCallEvent> {
637        self.record(event);
638        Ok(InterventionAction::proceed())
639    }
640}
641
642fn check_config_shape(config: &DogwoodAuthorizationConfig, has_action_schema: bool) -> Result<()> {
643    if config.principal.is_some() && config.principal_resolver.is_some() {
644        return Err(Error::other(
645            "Provide either `principal` or `principal_resolver`, not both",
646        ));
647    }
648    if !has_action_schema && config.tools.is_none() {
649        return Err(Error::other("Provide either `action_schema` or `tools`"));
650    }
651    if !has_action_schema && config.entities.as_ref().is_some_and(|entities| !entities.is_empty()) {
652        return Err(Error::other(
653            "`entities` requires `action_schema`; a generated schema declares no entity attributes",
654        ));
655    }
656    if has_action_schema && config.namespace.is_some() {
657        return Err(Error::other(
658            "`namespace` applies to a generated schema; a hand-written `action_schema` declares its own",
659        ));
660    }
661    Ok(())
662}
663
664/// Rejects an illegal namespace up front; it would otherwise surface as a schema parse error
665/// naming generated text the caller never wrote.
666fn check_cedar_namespace(namespace: Option<&str>) -> Result<()> {
667    let Some(namespace) = namespace else {
668        return Ok(());
669    };
670    let legal = namespace.split("::").all(|segment| {
671        is_cedar_identifier(segment)
672            && !CEDAR_RESERVED.contains(&segment)
673            && !segment.starts_with(CEDAR_INTERNAL_PREFIX)
674    });
675    if legal {
676        return Ok(());
677    }
678    Err(Error::other(format!(
679        "`namespace` must be `::`-separated Cedar identifiers, none of them reserved: '{namespace}'"
680    )))
681}
682
683fn is_cedar_identifier(segment: &str) -> bool {
684    let mut chars = segment.chars();
685    chars
686        .next()
687        .is_some_and(|first| first.is_ascii_alphabetic() || first == '_')
688        && chars.all(|rest| rest.is_ascii_alphanumeric() || rest == '_')
689}
690
691/// Text ending in `extension` is a path to read; anything else is the source itself.
692fn load_source(value: &str, extension: &str) -> Result<String> {
693    if !value.ends_with(extension) {
694        return Ok(value.to_owned());
695    }
696    std::fs::read_to_string(value).map_err(|_| Error::other(format!("Dogwood {extension} file not found: {value}")))
697}
698
699fn generate_action_schema(tools: &[ToolSpec]) -> Result<String> {
700    // The generator needs an input schema on every tool; a spec without one takes no input.
701    let tools: Vec<ToolSpec> = tools
702        .iter()
703        .cloned()
704        .map(|mut tool| {
705            tool.input_schema
706                .get_or_insert_with(|| serde_json::json!({"type": "object", "properties": {}}));
707            tool
708        })
709        .collect();
710    let mut manifest = serde_json::to_value(&tools)?;
711    retype_for_raw_arguments(&mut manifest);
712    let schema = dogwood_ops::mcp_to_cedar_schema(&manifest.to_string()).map_err(dogwood_error)?;
713    Ok(records_for_object_parameters(&rename_resource(&schema)))
714}
715
716/// Declares each object parameter as a common record type instead of the entity type generation
717/// emits: the model sends an object, which conforms to a record and not to an entity reference.
718/// `User` and `Resource` are declared without attributes, so they stay entities.
719fn records_for_object_parameters(schema: &str) -> String {
720    match PARAMETER_ENTITY.as_ref() {
721        Some(entity) => entity.replace_all(schema, "${1}type ${2} = {").into_owned(),
722        None => schema.to_owned(),
723    }
724}
725
726/// Retypes parameters to the JSON a condition compares against. Generation types an `enum`
727/// constraint as an entity type and a `number` as `decimal`, neither of which a raw argument
728/// matches; dropping the constraint generates `String`, and `integer` generates `Long`. Only an
729/// array-valued `enum` and the exact string `number` are rewritten, so a parameter named `enum`
730/// or `type` is untouched.
731fn retype_for_raw_arguments(value: &mut JsonValue) {
732    match value {
733        JsonValue::Object(map) => {
734            if map.get("enum").is_some_and(JsonValue::is_array) {
735                map.shift_remove("enum");
736            }
737            if let Some(number) = map.get_mut("type").filter(|ty| *ty == "number") {
738                *number = JsonValue::from("integer");
739            }
740            map.values_mut().for_each(retype_for_raw_arguments);
741        }
742        JsonValue::Array(items) => items.iter_mut().for_each(retype_for_raw_arguments),
743        _ => {}
744    }
745}
746
747/// Renames the generator's resource entity to the one `CedarAuthorization` uses. Only the
748/// declaration and the action references change: a tool or parameter whose own name contains
749/// the generated name keeps it.
750fn rename_resource(schema: &str) -> String {
751    schema
752        .replacen(
753            &format!("entity {GENERATED_RESOURCE};"),
754            &format!("entity {RESOURCE};"),
755            1,
756        )
757        .replace(
758            &format!("resource: [{GENERATED_RESOURCE}]"),
759            &format!("resource: [{RESOURCE}]"),
760        )
761}
762
763/// Declares a generated schema under `namespace`, or at the top level when there is none. An
764/// object parameter is generated as its own entity type and referenced qualified, so those
765/// references move with the declaration.
766fn apply_namespace(schema: &str, namespace: Option<&str>) -> String {
767    if namespace == Some(GENERATED_NAMESPACE) {
768        return schema.to_owned();
769    }
770    let qualifier = namespace.map_or_else(String::new, |namespace| format!("{namespace}::"));
771    let requalified = schema.replace(&format!("{GENERATED_NAMESPACE}::"), &qualifier);
772    let opening = format!("namespace {GENERATED_NAMESPACE} {{");
773    if let Some(namespace) = namespace {
774        return requalified.replacen(&opening, &format!("namespace {namespace} {{"), 1);
775    }
776    let unwrapped = requalified.replacen(&opening, "", 1);
777    match unwrapped.trim_end().strip_suffix('}') {
778        Some(body) => body.to_owned(),
779        None => unwrapped,
780    }
781}
782
783/// The namespace the schema's actions live in, as a prefix ready to concatenate (`Acme::`), or
784/// empty at the top level.
785fn namespace_prefix_of(actions: &[String]) -> String {
786    let Some(first) = actions.first() else {
787        return String::new();
788    };
789    // The last marker, so a namespace with an `Action` segment of its own stays whole.
790    match first.rfind("::Action::") {
791        Some(index) if index > 0 => first[..index + 2].to_owned(),
792        _ => String::new(),
793    }
794}
795
796/// The tool name in a fully qualified action id: its last `::` segment.
797fn tool_name_of(action: &str) -> &str {
798    action.rsplit("::").next().unwrap_or(action)
799}
800
801/// The tools whose action context declares a `system` group, read from the lowered Cedar schema.
802fn tools_with_system_context(cedar_schema_json: &str) -> Result<HashSet<String>> {
803    let schema: JsonValue = serde_json::from_str(cedar_schema_json)?;
804    let mut tools = HashSet::new();
805    for namespace in schema.as_object().into_iter().flat_map(JsonObject::values) {
806        let actions = namespace.get("actions").and_then(JsonValue::as_object);
807        for (name, action) in actions.into_iter().flatten() {
808            let declares = context_attributes(&action["appliesTo"]["context"], namespace)
809                .is_some_and(|attributes| attributes.contains_key(SYSTEM_GROUP));
810            if declares {
811                tools.insert(name.clone());
812            }
813        }
814    }
815    Ok(tools)
816}
817
818/// A context's attributes: an inline record, or the common type it names in its namespace.
819fn context_attributes<'a>(context: &'a JsonValue, namespace: &'a JsonValue) -> Option<&'a JsonObject> {
820    if let Some(attributes) = context.get("attributes").and_then(JsonValue::as_object) {
821        return Some(attributes);
822    }
823    let name = context
824        .get("name")
825        .or_else(|| context.get("type"))
826        .and_then(JsonValue::as_str)?;
827    namespace.get("commonTypes")?.get(name)?.get("attributes")?.as_object()
828}
829
830/// `{ now: datetime }` for the event time, in Cedar's extension escape.
831fn system_group(timestamp: i64) -> BTreeMap<String, JsonValue> {
832    let now = jiff::Timestamp::from_second(timestamp)
833        .map(|at| at.strftime("%Y-%m-%dT%H:%M:%SZ").to_string())
834        .unwrap_or_default();
835    BTreeMap::from([(
836        "now".to_owned(),
837        serde_json::json!({"__extn": {"fn": "datetime", "arg": now}}),
838    )])
839}
840
841/// The tool input as an event group; absent input is an empty group.
842fn input_group(input: &JsonValue) -> std::result::Result<BTreeMap<String, JsonValue>, serde_json::Error> {
843    if input.is_null() {
844        return Ok(BTreeMap::new());
845    }
846    serde_json::from_value(input.clone())
847}
848
849/// Fails unless every validation error is one a generated schema causes by construction, so a
850/// policy that could only ever deny is rejected here rather than at the first tool call. Cedar
851/// reports the shallowest missing attribute, so an enriched group reads as a bare `session`.
852fn check_policy_type_checks(errors: &[Diagnostic], tolerate_enriched_group: bool) -> Result<()> {
853    let enriched = format!("attribute `{ENRICHED_GROUP}` in context");
854    let fatal: Vec<&str> = errors
855        .iter()
856        .filter(|error| !(tolerate_enriched_group && error.message.contains(&enriched)))
857        .map(|error| error.message.as_str())
858        .collect();
859    if fatal.is_empty() {
860        return Ok(());
861    }
862    Err(Error::other(format!(
863        "Dogwood policy validation failed: {}",
864        fatal.join(", ")
865    )))
866}
867
868/// The denial reason for a decision, or `None` when it allowed.
869fn denial_reason(decision: Option<&AuthorizerDecision>, tool_name: &str) -> Option<String> {
870    // A decision kind always yields a verdict; an absent one fails closed.
871    let Some(decision) = decision else {
872        return Some(format!("No Dogwood decision returned for '{tool_name}'; denying"));
873    };
874    if decision.allowed {
875        return None;
876    }
877    if !decision.errors.is_empty() {
878        return Some(format!("Dogwood evaluation failed: {}", decision.errors.join(", ")));
879    }
880    let rules = &decision.determining_rules;
881    if rules.is_empty() {
882        return Some("Access denied by Dogwood policy".to_owned());
883    }
884    let rules: Vec<String> = rules.iter().map(ToString::to_string).collect();
885    Some(format!("Access denied by Dogwood policy (rule {})", rules.join(", ")))
886}
887
888fn dogwood_error(error: OpError) -> Error {
889    Error::other(error)
890}
891
892#[cfg(test)]
893mod tests;