Skip to main content

appcore_sdk/
capability.rs

1// =============================================================================
2//        #######
3//     ###       ###     F: capability.rs
4//    ##   ## ##   ##    P: AppCore-Runtime
5//         ## ##
6//                       C: 2026/09/25 14:28:37 by dnettoRaw
7//    ##   ## ##   ##    U: 2026/10/15 10:24:40 by dnettoRaw
8//      ###########      S: 1.0.2-rc.1
9// =============================================================================
10
11//! Application capability declarations and command coverage helpers.
12
13use appcore_contracts::CapabilityId;
14use appcore_core::{CommandName, RuntimeResult};
15use serde::{Deserialize, Serialize};
16
17use crate::{AppError, AppResult};
18
19/// Maximum declarations and command mappings retained by one helper.
20pub const MAX_CAPABILITY_ENTRIES: usize = 256;
21
22/// Reusable result shape for authorization owned by the host or application.
23#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
24#[serde(rename_all = "snake_case", tag = "status")]
25pub enum CapabilityOutcome<T> {
26    /// The caller was authenticated and authorized by the owning policy.
27    Authorized(T),
28    /// Authentication is required before the operation can continue.
29    AuthenticationRequired,
30    /// Authentication exists but the owning policy denied the operation.
31    PermissionDenied,
32}
33
34impl<T> CapabilityOutcome<T> {
35    /// Converts the outcome into a result without deciding authorization.
36    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/// Uniform non-business authorization outcomes.
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
47#[serde(rename_all = "snake_case")]
48pub enum CapabilityOutcomeError {
49    /// No valid authentication context was supplied.
50    AuthenticationRequired,
51    /// The owning authorization policy rejected the request.
52    PermissionDenied,
53}
54
55/// Result of checking registered command coverage.
56#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
57pub struct CapabilityCoverage {
58    /// Commands without a capability mapping.
59    pub uncovered_commands: Vec<String>,
60    /// Number of declared capabilities.
61    pub declared_capabilities: usize,
62    /// Number of command mappings.
63    pub command_mappings: usize,
64}
65
66impl CapabilityCoverage {
67    /// Returns whether every supplied command has a capability mapping.
68    #[must_use]
69    pub fn is_complete(&self) -> bool {
70        self.uncovered_commands.is_empty()
71    }
72}
73
74/// Bounded declaration and command-to-capability mapping registry.
75#[derive(Debug, Clone, Default)]
76pub struct CapabilityRegistry {
77    declarations: Vec<CapabilityDeclaration>,
78    command_mappings: Vec<(CommandName, CapabilityId)>,
79}
80
81impl CapabilityRegistry {
82    /// Creates an empty helper registry.
83    pub fn new() -> Self {
84        Self::default()
85    }
86
87    /// Declares one capability, rejecting duplicate identities and overflow.
88    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    /// Maps one command to a previously declared capability.
109    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    /// Returns the immutable capability declarations.
140    pub fn declarations(&self) -> &[CapabilityDeclaration] {
141        &self.declarations
142    }
143
144    /// Returns the capability mapped to a command, when present.
145    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    /// Checks that every registered command has a capability mapping.
153    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
167/// Declares a capability and maps it to a command in one checked operation.
168pub 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
178/// Creates a checked command name for helper and application registration code.
179pub fn command_name(value: impl Into<String>) -> RuntimeResult<CommandName> {
180    CommandName::new(value)
181}
182
183/// Re-export the contract types needed to construct declarations.
184pub 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}