1use 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
54const ENRICHED_GROUP: &str = "session";
56
57const SYSTEM_GROUP: &str = "system";
59
60const REQUEST: &str = "request";
62
63const GENERATED_NAMESPACE: &str = "Drupe";
65
66const GENERATED_RESOURCE: &str = "Gateway";
68
69const RESOURCE: &str = "Resource";
71
72const CEDAR_RESERVED: [&str; 9] = ["true", "false", "if", "then", "else", "in", "is", "like", "has"];
74
75const CEDAR_INTERNAL_PREFIX: &str = "__cedar";
77
78static 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
85type EventGroups = BTreeMap<String, BTreeMap<String, JsonValue>>;
87
88#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
90#[non_exhaustive]
91pub struct EntityRef {
92 #[serde(rename = "type")]
94 pub entity_type: String,
95 pub id: String,
97}
98
99impl EntityRef {
100 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#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
119#[non_exhaustive]
120pub struct EntityInput {
121 #[serde(rename = "type")]
123 pub entity_type: String,
124 pub id: String,
126 #[serde(default)]
128 pub attrs: JsonObject,
129 #[serde(default)]
131 pub parents: Vec<EntityRef>,
132}
133
134impl EntityInput {
135 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 #[must_use]
146 pub fn with_attrs(mut self, attrs: JsonObject) -> Self {
147 self.attrs = attrs;
148 self
149 }
150
151 #[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 pub struct PrincipalResolver(Fn(&InvocationState) -> Result<Option<EntityRef>, BoxError>);
175}
176
177#[derive(Debug)]
179#[non_exhaustive]
180pub struct ContextEnricherInput<'a> {
181 pub tool_name: &'a str,
183 pub tool_input: &'a JsonValue,
185 pub invocation_state: &'a InvocationState,
187}
188
189crate::callback::callback! {
190 pub struct ContextEnricher(Fn(&ContextEnricherInput<'_>) -> Result<JsonObject, BoxError>);
195}
196
197#[derive(Clone, Default, bon::Builder)]
199pub struct DogwoodAuthorizationConfig {
200 #[builder(into)]
202 pub policies: String,
203 pub tools: Option<Vec<ToolSpec>>,
206 #[builder(into)]
210 pub action_schema: Option<String>,
211 pub entities: Option<Vec<EntityInput>>,
214 #[builder(into)]
218 pub namespace: Option<String>,
219 pub principal: Option<EntityRef>,
222 #[builder(into)]
224 pub principal_resolver: Option<PrincipalResolver>,
225 #[builder(into)]
227 pub context_enricher: Option<ContextEnricher>,
228 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
248struct AllowedCall {
250 tool_name: String,
251 action: String,
252 principal: EntityRef,
253 logged: EventGroups,
254}
255
256struct History {
257 authorizer: Engine,
258 allowed_calls: HashMap<String, AllowedCall>,
260 unusable: bool,
263}
264
265struct 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
280pub struct DogwoodAuthorization {
292 history: Mutex<History>,
293 actions_by_tool: HashMap<String, String>,
294 declared_kinds: HashSet<String>,
295 system_tools: HashSet<String>,
297 resource: EntityRef,
298 default_principal: Option<EntityRef>,
299 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 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 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 pub fn reset(&self) {
400 let mut history = self.history();
401 if history.unusable {
402 return;
403 }
404 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 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 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 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 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 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 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 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
664fn 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
691fn 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 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
716fn 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
726fn 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
747fn 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
763fn 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
783fn namespace_prefix_of(actions: &[String]) -> String {
786 let Some(first) = actions.first() else {
787 return String::new();
788 };
789 match first.rfind("::Action::") {
791 Some(index) if index > 0 => first[..index + 2].to_owned(),
792 _ => String::new(),
793 }
794}
795
796fn tool_name_of(action: &str) -> &str {
798 action.rsplit("::").next().unwrap_or(action)
799}
800
801fn 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
818fn 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
830fn 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
841fn 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
849fn 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
868fn denial_reason(decision: Option<&AuthorizerDecision>, tool_name: &str) -> Option<String> {
870 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;