appcore_sdk/
capability.rs1use appcore_contracts::CapabilityId;
14use appcore_core::{CommandName, RuntimeResult};
15use serde::{Deserialize, Serialize};
16
17use crate::{AppError, AppResult};
18
19pub const MAX_CAPABILITY_ENTRIES: usize = 256;
21
22#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
24#[serde(rename_all = "snake_case", tag = "status")]
25pub enum CapabilityOutcome<T> {
26 Authorized(T),
28 AuthenticationRequired,
30 PermissionDenied,
32}
33
34impl<T> CapabilityOutcome<T> {
35 pub fn into_result(self) -> Result<T, CapabilityOutcomeError> {
37 match self {
38 Self::Authorized(value) => Ok(value),
39 Self::AuthenticationRequired => Err(CapabilityOutcomeError::AuthenticationRequired),
40 Self::PermissionDenied => Err(CapabilityOutcomeError::PermissionDenied),
41 }
42 }
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
47#[serde(rename_all = "snake_case")]
48pub enum CapabilityOutcomeError {
49 AuthenticationRequired,
51 PermissionDenied,
53}
54
55#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
57pub struct CapabilityCoverage {
58 pub uncovered_commands: Vec<String>,
60 pub declared_capabilities: usize,
62 pub command_mappings: usize,
64}
65
66impl CapabilityCoverage {
67 #[must_use]
69 pub fn is_complete(&self) -> bool {
70 self.uncovered_commands.is_empty()
71 }
72}
73
74#[derive(Debug, Clone, Default)]
76pub struct CapabilityRegistry {
77 declarations: Vec<CapabilityDeclaration>,
78 command_mappings: Vec<(CommandName, CapabilityId)>,
79}
80
81impl CapabilityRegistry {
82 pub fn new() -> Self {
84 Self::default()
85 }
86
87 pub fn declare(&mut self, declaration: CapabilityDeclaration) -> AppResult<()> {
89 if self.declarations.len() >= MAX_CAPABILITY_ENTRIES {
90 return Err(AppError::Capability(
91 "capability declaration limit exceeded".to_owned(),
92 ));
93 }
94 if self
95 .declarations
96 .iter()
97 .any(|existing| existing.id() == declaration.id())
98 {
99 return Err(AppError::Capability(format!(
100 "capability `{}` is already declared",
101 declaration.id().as_str()
102 )));
103 }
104 self.declarations.push(declaration);
105 Ok(())
106 }
107
108 pub fn map_command(&mut self, command: CommandName, capability: CapabilityId) -> AppResult<()> {
110 if !self
111 .declarations
112 .iter()
113 .any(|item| item.id() == &capability)
114 {
115 return Err(AppError::Capability(format!(
116 "capability `{}` is not declared",
117 capability.as_str()
118 )));
119 }
120 if self.command_mappings.len() >= MAX_CAPABILITY_ENTRIES {
121 return Err(AppError::Capability(
122 "command mapping limit exceeded".to_owned(),
123 ));
124 }
125 if self
126 .command_mappings
127 .iter()
128 .any(|(existing, _)| existing == &command)
129 {
130 return Err(AppError::Capability(format!(
131 "command `{}` is already mapped",
132 command.as_str()
133 )));
134 }
135 self.command_mappings.push((command, capability));
136 Ok(())
137 }
138
139 pub fn declarations(&self) -> &[CapabilityDeclaration] {
141 &self.declarations
142 }
143
144 pub fn capability_for(&self, command: &CommandName) -> Option<&CapabilityId> {
146 self.command_mappings
147 .iter()
148 .find(|(mapped, _)| mapped == command)
149 .map(|(_, capability)| capability)
150 }
151
152 pub fn coverage(&self, commands: &[CommandName]) -> CapabilityCoverage {
154 let uncovered_commands = commands
155 .iter()
156 .filter(|command| self.capability_for(command).is_none())
157 .map(|command| command.as_str().to_owned())
158 .collect();
159 CapabilityCoverage {
160 uncovered_commands,
161 declared_capabilities: self.declarations.len(),
162 command_mappings: self.command_mappings.len(),
163 }
164 }
165}
166
167pub fn declare_command_capability(
169 registry: &mut CapabilityRegistry,
170 declaration: CapabilityDeclaration,
171 command: CommandName,
172) -> AppResult<()> {
173 let capability = declaration.id().clone();
174 registry.declare(declaration)?;
175 registry.map_command(command, capability)
176}
177
178pub fn command_name(value: impl Into<String>) -> RuntimeResult<CommandName> {
180 CommandName::new(value)
181}
182
183pub use appcore_contracts::{
185 CapabilityClass, CapabilityDeclaration, CapabilityMode, CapabilityVisibility,
186};
187
188#[cfg(test)]
189mod tests {
190 use super::*;
191
192 #[test]
193 fn declaration_mapping_and_coverage_are_bounded() {
194 let id = CapabilityId::new("document.export").unwrap();
195 let declaration = CapabilityDeclaration::new(
196 id.clone(),
197 "1",
198 CapabilityMode::Command,
199 CapabilityVisibility::Local,
200 )
201 .unwrap();
202 let mut registry = CapabilityRegistry::new();
203 declare_command_capability(
204 &mut registry,
205 declaration,
206 command_name("document.export.run").unwrap(),
207 )
208 .unwrap();
209 let commands = vec![
210 command_name("document.export.run").unwrap(),
211 command_name("document.export.preview").unwrap(),
212 ];
213 let coverage = registry.coverage(&commands);
214 assert!(!coverage.is_complete());
215 assert_eq!(coverage.uncovered_commands, vec!["document.export.preview"]);
216 assert_eq!(registry.capability_for(&commands[0]), Some(&id));
217 }
218
219 #[test]
220 fn authorization_outcomes_are_uniform_without_policy_decisions() {
221 assert_eq!(
222 CapabilityOutcome::<()>::AuthenticationRequired.into_result(),
223 Err(CapabilityOutcomeError::AuthenticationRequired)
224 );
225 assert_eq!(CapabilityOutcome::Authorized(7).into_result(), Ok(7));
226 }
227}