Skip to main content

vellaveto_types/
posture.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4//
5// Copyright 2026 Paolo Vella
6// SPDX-License-Identifier: MPL-2.0
7
8use serde::{Deserialize, Serialize};
9
10/// Scope attached to posture responses.
11#[derive(Debug, Clone, Serialize, Deserialize)]
12#[serde(deny_unknown_fields)]
13pub struct PostureScope {
14    /// Scope kind (`global` or `tenant`).
15    pub kind: String,
16    /// Tenant identifier when the response is tenant-scoped.
17    #[serde(default, skip_serializing_if = "Option::is_none")]
18    pub tenant: Option<String>,
19}
20
21impl PostureScope {
22    /// Build a global posture scope.
23    pub fn global() -> Self {
24        Self {
25            kind: "global".to_string(),
26            tenant: None,
27        }
28    }
29
30    /// Build a tenant-scoped posture scope.
31    pub fn tenant(tenant: impl Into<String>) -> Self {
32        Self {
33            kind: "tenant".to_string(),
34            tenant: Some(tenant.into()),
35        }
36    }
37
38    /// Return true when this scope is global.
39    pub fn is_global(&self) -> bool {
40        self.tenant.is_none()
41    }
42}
43
44/// Per-category score within the aggregate security posture response.
45#[derive(Debug, Clone, Serialize, Deserialize)]
46#[serde(deny_unknown_fields)]
47pub struct PostureCategoryScore {
48    /// Category identifier (for example: governance, runtime, supply_chain).
49    pub name: String,
50    /// Aggregate score for the category, in percent.
51    pub score_percent: f32,
52    /// Number of framework inputs used to compute the category.
53    pub inputs: usize,
54}
55
56/// Coverage or readiness score for a single framework in the posture view.
57#[derive(Debug, Clone, Serialize, Deserialize)]
58#[serde(deny_unknown_fields)]
59pub struct PostureFrameworkScore {
60    /// Framework display name.
61    pub name: String,
62    /// Coverage or readiness score for the framework, in percent.
63    pub score_percent: f32,
64    /// Whether the framework-specific reporting is enabled in the current config.
65    pub enabled: bool,
66}
67
68/// High-level security posture score for the active Vellaveto deployment.
69#[derive(Debug, Clone, Serialize, Deserialize)]
70#[serde(deny_unknown_fields)]
71pub struct SecurityPostureScore {
72    /// Report generation timestamp (RFC 3339).
73    pub generated_at: String,
74    /// Scope used to generate the posture score.
75    pub scope: PostureScope,
76    /// Aggregate score across the category breakdown.
77    pub overall_score_percent: f32,
78    /// Qualitative tier derived from the overall score.
79    pub tier: String,
80    /// Category breakdown used to compute the overall score.
81    pub categories: Vec<PostureCategoryScore>,
82    /// Framework-level inputs that feed the posture score.
83    pub frameworks: Vec<PostureFrameworkScore>,
84}
85
86/// Maximum number of items in posture collections.
87const MAX_POSTURE_ITEMS: usize = 500;
88
89/// Maximum length for string fields in posture types.
90const MAX_POSTURE_STRING_LEN: usize = 1024;
91
92impl SecurityPostureScore {
93    /// SECURITY (R239-TYP-1): Validate posture score for NaN/Infinity and bounds.
94    pub fn validate(&self) -> Result<(), String> {
95        fn check_percent(name: &str, v: f32) -> Result<(), String> {
96            if !v.is_finite() || !(0.0..=100.0).contains(&v) {
97                return Err(format!("{name} {v} is not in [0.0, 100.0]"));
98            }
99            Ok(())
100        }
101        check_percent("overall_score_percent", self.overall_score_percent)?;
102        if self.categories.len() > MAX_POSTURE_ITEMS {
103            return Err(format!(
104                "categories count {} exceeds max {MAX_POSTURE_ITEMS}",
105                self.categories.len()
106            ));
107        }
108        for c in &self.categories {
109            check_percent("category score_percent", c.score_percent)?;
110        }
111        if self.frameworks.len() > MAX_POSTURE_ITEMS {
112            return Err(format!(
113                "frameworks count {} exceeds max {MAX_POSTURE_ITEMS}",
114                self.frameworks.len()
115            ));
116        }
117        for f in &self.frameworks {
118            check_percent("framework score_percent", f.score_percent)?;
119        }
120        if self.generated_at.len() > MAX_POSTURE_STRING_LEN {
121            return Err("generated_at too long".to_string());
122        }
123        // SECURITY (R243-TYP-3): Validate string content — these flow into
124        // API responses, dashboards, and audit trails.
125        if crate::core::has_dangerous_chars(&self.generated_at) {
126            return Err("generated_at contains control or format characters".to_string());
127        }
128        if self.tier.len() > MAX_POSTURE_STRING_LEN {
129            return Err("tier too long".to_string());
130        }
131        if crate::core::has_dangerous_chars(&self.tier) {
132            return Err("tier contains control or format characters".to_string());
133        }
134        if self.scope.kind.len() > MAX_POSTURE_STRING_LEN
135            || crate::core::has_dangerous_chars(&self.scope.kind)
136        {
137            return Err("scope.kind invalid".to_string());
138        }
139        if let Some(ref tenant) = self.scope.tenant {
140            if tenant.len() > MAX_POSTURE_STRING_LEN || crate::core::has_dangerous_chars(tenant) {
141                return Err("scope.tenant invalid".to_string());
142            }
143        }
144        for c in &self.categories {
145            if c.name.len() > MAX_POSTURE_STRING_LEN || crate::core::has_dangerous_chars(&c.name) {
146                return Err("category name invalid".to_string());
147            }
148        }
149        for f in &self.frameworks {
150            if f.name.len() > MAX_POSTURE_STRING_LEN || crate::core::has_dangerous_chars(&f.name) {
151                return Err("framework name invalid".to_string());
152            }
153        }
154        Ok(())
155    }
156}
157
158impl PostureGapReport {
159    /// SECURITY (R239-TYP-1): Validate gap report for NaN/Infinity and bounds.
160    pub fn validate(&self) -> Result<(), String> {
161        if !self.overall_coverage_percent.is_finite()
162            || self.overall_coverage_percent < 0.0
163            || self.overall_coverage_percent > 100.0
164        {
165            return Err(format!(
166                "overall_coverage_percent {} is not in [0.0, 100.0]",
167                self.overall_coverage_percent
168            ));
169        }
170        if self.critical_gaps.len() > MAX_POSTURE_ITEMS {
171            return Err(format!(
172                "critical_gaps count {} exceeds max {MAX_POSTURE_ITEMS}",
173                self.critical_gaps.len()
174            ));
175        }
176        if self.recommendations.len() > MAX_POSTURE_ITEMS {
177            return Err(format!(
178                "recommendations count {} exceeds max {MAX_POSTURE_ITEMS}",
179                self.recommendations.len()
180            ));
181        }
182        if self.high_priority_focus_areas.len() > MAX_POSTURE_ITEMS {
183            return Err(format!(
184                "high_priority_focus_areas count {} exceeds max {MAX_POSTURE_ITEMS}",
185                self.high_priority_focus_areas.len()
186            ));
187        }
188        // SECURITY (R243-TYP-3): Validate string content.
189        if self.generated_at.len() > MAX_POSTURE_STRING_LEN
190            || crate::core::has_dangerous_chars(&self.generated_at)
191        {
192            return Err("generated_at invalid".to_string());
193        }
194        if let Some(ref tenant) = self.scope.tenant {
195            if tenant.len() > MAX_POSTURE_STRING_LEN || crate::core::has_dangerous_chars(tenant) {
196                return Err("scope.tenant invalid".to_string());
197            }
198        }
199        for gap in &self.critical_gaps {
200            for (name, val) in [
201                ("framework", &gap.framework),
202                ("item_id", &gap.item_id),
203                ("severity", &gap.severity),
204                ("description", &gap.description),
205            ] {
206                if val.len() > MAX_POSTURE_STRING_LEN || crate::core::has_dangerous_chars(val) {
207                    return Err(format!("critical_gap {name} invalid"));
208                }
209            }
210        }
211        for (i, rec) in self.recommendations.iter().enumerate() {
212            if rec.len() > MAX_POSTURE_STRING_LEN || crate::core::has_dangerous_chars(rec) {
213                return Err(format!("recommendations[{i}] invalid"));
214            }
215        }
216        for (i, area) in self.high_priority_focus_areas.iter().enumerate() {
217            if area.len() > MAX_POSTURE_STRING_LEN || crate::core::has_dangerous_chars(area) {
218                return Err(format!("high_priority_focus_areas[{i}] invalid"));
219            }
220        }
221        Ok(())
222    }
223}
224
225/// A normalized coverage summary for a framework in the control matrix view.
226#[derive(Debug, Clone, Serialize, Deserialize)]
227#[serde(deny_unknown_fields)]
228pub struct ControlCoverageSummary {
229    /// Framework display name.
230    pub framework: String,
231    /// Total controls/techniques/items for the framework.
232    pub total_items: usize,
233    /// Covered controls/techniques/items for the framework.
234    pub covered_items: usize,
235    /// Percent of covered items in the framework.
236    pub coverage_percent: f32,
237}
238
239/// Consolidated control coverage matrix used by posture dashboards.
240#[derive(Debug, Clone, Serialize, Deserialize)]
241#[serde(deny_unknown_fields)]
242pub struct ControlCoverageMatrix {
243    /// Report generation timestamp (RFC 3339).
244    pub generated_at: String,
245    /// Scope used to generate the control coverage matrix.
246    pub scope: PostureScope,
247    /// Weighted aggregate coverage across the listed frameworks.
248    pub overall_coverage_percent: f32,
249    /// Per-framework control coverage summaries.
250    pub frameworks: Vec<ControlCoverageSummary>,
251    /// Short operator-facing notes that explain how to interpret the matrix.
252    pub highlights: Vec<String>,
253}
254
255impl ControlCoverageMatrix {
256    /// SECURITY (R243-TYP-3): Validate coverage matrix for NaN/Infinity, bounds, and string content.
257    pub fn validate(&self) -> Result<(), String> {
258        if !self.overall_coverage_percent.is_finite()
259            || !(0.0..=100.0).contains(&self.overall_coverage_percent)
260        {
261            return Err(format!(
262                "overall_coverage_percent {} is not in [0.0, 100.0]",
263                self.overall_coverage_percent
264            ));
265        }
266        if self.frameworks.len() > MAX_POSTURE_ITEMS {
267            return Err(format!(
268                "frameworks count {} exceeds max {MAX_POSTURE_ITEMS}",
269                self.frameworks.len()
270            ));
271        }
272        if self.highlights.len() > MAX_POSTURE_ITEMS {
273            return Err(format!(
274                "highlights count {} exceeds max {MAX_POSTURE_ITEMS}",
275                self.highlights.len()
276            ));
277        }
278        if self.generated_at.len() > MAX_POSTURE_STRING_LEN
279            || crate::core::has_dangerous_chars(&self.generated_at)
280        {
281            return Err("generated_at invalid".to_string());
282        }
283        if let Some(ref tenant) = self.scope.tenant {
284            if tenant.len() > MAX_POSTURE_STRING_LEN || crate::core::has_dangerous_chars(tenant) {
285                return Err("scope.tenant invalid".to_string());
286            }
287        }
288        for f in &self.frameworks {
289            if !f.coverage_percent.is_finite() || !(0.0..=100.0).contains(&f.coverage_percent) {
290                return Err(format!(
291                    "framework coverage_percent {} is not in [0.0, 100.0]",
292                    f.coverage_percent
293                ));
294            }
295            if f.framework.len() > MAX_POSTURE_STRING_LEN
296                || crate::core::has_dangerous_chars(&f.framework)
297            {
298                return Err("framework name invalid".to_string());
299            }
300        }
301        for (i, h) in self.highlights.iter().enumerate() {
302            if h.len() > MAX_POSTURE_STRING_LEN || crate::core::has_dangerous_chars(h) {
303                return Err(format!("highlights[{i}] invalid"));
304            }
305        }
306        Ok(())
307    }
308}
309
310/// A normalized remediation gap in the posture API.
311#[derive(Debug, Clone, Serialize, Deserialize)]
312#[serde(deny_unknown_fields)]
313pub struct PostureGap {
314    /// Framework where the gap appears.
315    pub framework: String,
316    /// Gap identifier within the framework.
317    pub item_id: String,
318    /// Severity label (for example: High, Medium).
319    pub severity: String,
320    /// Human-readable description of the gap.
321    pub description: String,
322}
323
324/// Prioritized remediation gaps derived from the broader control matrix.
325#[derive(Debug, Clone, Serialize, Deserialize)]
326#[serde(deny_unknown_fields)]
327pub struct PostureGapReport {
328    /// Report generation timestamp (RFC 3339).
329    pub generated_at: String,
330    /// Scope used to generate the remediation queue.
331    pub scope: PostureScope,
332    /// Weighted aggregate coverage across the sources used in this report.
333    pub overall_coverage_percent: f32,
334    /// Highest-priority gaps to address.
335    pub critical_gaps: Vec<PostureGap>,
336    /// Actionable remediation guidance.
337    pub recommendations: Vec<String>,
338    /// A compact list of themes that need immediate attention.
339    pub high_priority_focus_areas: Vec<String>,
340}
341
342/// Posture-focused export that combines a compliance evidence pack with the
343/// current posture score and remediation focus areas.
344#[derive(Debug, Clone, Serialize, Deserialize)]
345#[serde(deny_unknown_fields)]
346pub struct PostureEvidencePackExport {
347    /// Report generation timestamp (RFC 3339).
348    pub generated_at: String,
349    /// Evidence pack framework identifier.
350    pub framework: String,
351    /// Scope used for the posture context.
352    pub scope: PostureScope,
353    /// Aggregate posture at export time.
354    pub posture: SecurityPostureScore,
355    /// Highest-priority remediation themes.
356    pub high_priority_focus_areas: Vec<String>,
357    /// Framework-specific evidence pack payload.
358    pub evidence_pack: serde_json::Value,
359}
360
361impl PostureEvidencePackExport {
362    /// SECURITY (R243-TYP-3): Validate evidence pack export.
363    pub fn validate(&self) -> Result<(), String> {
364        if self.generated_at.len() > MAX_POSTURE_STRING_LEN
365            || crate::core::has_dangerous_chars(&self.generated_at)
366        {
367            return Err("generated_at invalid".to_string());
368        }
369        if self.framework.len() > MAX_POSTURE_STRING_LEN
370            || crate::core::has_dangerous_chars(&self.framework)
371        {
372            return Err("framework invalid".to_string());
373        }
374        if let Some(ref tenant) = self.scope.tenant {
375            if tenant.len() > MAX_POSTURE_STRING_LEN || crate::core::has_dangerous_chars(tenant) {
376                return Err("scope.tenant invalid".to_string());
377            }
378        }
379        self.posture.validate()?;
380        if self.high_priority_focus_areas.len() > MAX_POSTURE_ITEMS {
381            return Err(format!(
382                "high_priority_focus_areas count {} exceeds max {MAX_POSTURE_ITEMS}",
383                self.high_priority_focus_areas.len()
384            ));
385        }
386        for (i, area) in self.high_priority_focus_areas.iter().enumerate() {
387            if area.len() > MAX_POSTURE_STRING_LEN || crate::core::has_dangerous_chars(area) {
388                return Err(format!("high_priority_focus_areas[{i}] invalid"));
389            }
390        }
391        Ok(())
392    }
393}