vellaveto-types 6.1.1

Core type definitions for Vellaveto policy engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//
// Copyright 2026 Paolo Vella
// SPDX-License-Identifier: MPL-2.0

//! Governance types for Shadow AI Discovery and Least Agency Enforcement (Phase 26).
//!
//! These types support:
//! - **Shadow AI Discovery (26.1):** Passive detection of unregistered agents,
//!   unapproved tools, and unknown MCP servers from traffic patterns.
//! - **Least Agency Enforcement (26.2):** Auto-revocation of unused permissions
//!   with audit event emission.

use serde::{Deserialize, Serialize};
use std::collections::HashSet;

// ═══════════════════════════════════════════════════════════════════════════════
// ENFORCEMENT MODE
// ═══════════════════════════════════════════════════════════════════════════════

/// Enforcement mode for governance controls.
///
/// - `Monitor`: Log findings but do not block (default, safe rollout).
/// - `Enforce`: Actively deny or revoke based on governance policy.
///
/// # Default: `Monitor` (intentional)
///
/// The default is `Monitor` (fail-open for governance) to support gradual
/// rollout. Organizations should switch to `Enforce` once governance policies
/// have been validated in monitoring mode. This is intentionally different
/// from the core policy engine's fail-closed default — governance findings
/// are informational until the operator explicitly opts into enforcement.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum EnforcementMode {
    #[default]
    Monitor,
    Enforce,
}

// ═══════════════════════════════════════════════════════════════════════════════
// SHADOW AI DISCOVERY TYPES (Phase 26.1)
// ═══════════════════════════════════════════════════════════════════════════════

/// An agent observed in traffic that is not in the registered agent list.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UnregisteredAgent {
    pub agent_id: String,
    pub first_seen: String,
    pub last_seen: String,
    pub request_count: u64,
    pub tools_used: HashSet<String>,
    pub risk_score: f64,
}

impl UnregisteredAgent {
    /// Maximum number of tools tracked per unregistered agent.
    const MAX_TOOLS_USED: usize = 1000;
    /// Maximum length for `agent_id` field.
    ///
    /// SECURITY (FIND-R113-014): Bound string fields.
    const MAX_AGENT_ID_LEN: usize = 256;
    /// Maximum length for timestamp fields (`first_seen`, `last_seen`).
    ///
    /// SECURITY (FIND-R113-014): Bound string fields.
    const MAX_TIMESTAMP_LEN: usize = 64;
    /// Maximum length for individual tool name entries in `tools_used`.
    ///
    /// SECURITY (FIND-R113-014): Bound per-entry lengths.
    const MAX_TOOL_NAME_LEN: usize = 256;

    /// Validate structural invariants: finite scores, range checks, collection bounds.
    ///
    /// SECURITY (FIND-P2-007): Non-finite risk_score could bypass threshold
    /// comparisons (NaN comparisons always return false).
    /// SECURITY (FIND-R49-008): Bound inner HashSet to prevent memory abuse.
    /// SECURITY (FIND-R113-014): Control/format char validation on string fields.
    pub fn validate(&self) -> Result<(), String> {
        if self.agent_id.len() > Self::MAX_AGENT_ID_LEN {
            return Err(format!(
                "UnregisteredAgent agent_id length {} exceeds max {}",
                self.agent_id.len(),
                Self::MAX_AGENT_ID_LEN
            ));
        }
        if self.first_seen.len() > Self::MAX_TIMESTAMP_LEN {
            return Err(format!(
                "UnregisteredAgent '{}' first_seen length {} exceeds max {}",
                self.agent_id,
                self.first_seen.len(),
                Self::MAX_TIMESTAMP_LEN
            ));
        }
        if self.last_seen.len() > Self::MAX_TIMESTAMP_LEN {
            return Err(format!(
                "UnregisteredAgent '{}' last_seen length {} exceeds max {}",
                self.agent_id,
                self.last_seen.len(),
                Self::MAX_TIMESTAMP_LEN
            ));
        }
        // SECURITY (FIND-R113-014): Control/format char validation.
        if crate::core::has_dangerous_chars(&self.agent_id) {
            return Err(
                "UnregisteredAgent agent_id contains control or format characters".to_string(),
            );
        }
        if crate::core::has_dangerous_chars(&self.first_seen) {
            return Err(
                "UnregisteredAgent first_seen contains control or format characters".to_string(),
            );
        }
        if crate::core::has_dangerous_chars(&self.last_seen) {
            return Err(
                "UnregisteredAgent last_seen contains control or format characters".to_string(),
            );
        }
        if !self.risk_score.is_finite() {
            return Err(format!(
                "UnregisteredAgent '{}' has non-finite risk_score: {}",
                self.agent_id, self.risk_score
            ));
        }
        // SECURITY (FIND-R51-001): Validate risk_score is in documented [0.0, 1.0] range.
        if self.risk_score < 0.0 || self.risk_score > 1.0 {
            return Err(format!(
                "UnregisteredAgent '{}' risk_score must be in [0.0, 1.0], got {}",
                self.agent_id, self.risk_score
            ));
        }
        if self.tools_used.len() > Self::MAX_TOOLS_USED {
            return Err(format!(
                "UnregisteredAgent '{}' tools_used count {} exceeds max {}",
                self.agent_id,
                self.tools_used.len(),
                Self::MAX_TOOLS_USED
            ));
        }
        // SECURITY (FIND-R113-014): Per-entry length bounds on tools_used.
        // SECURITY (FIND-R158-001): Per-entry control/format char validation.
        for tool in &self.tools_used {
            if tool.len() > Self::MAX_TOOL_NAME_LEN {
                return Err(format!(
                    "UnregisteredAgent '{}' tools_used entry length {} exceeds max {}",
                    self.agent_id,
                    tool.len(),
                    Self::MAX_TOOL_NAME_LEN
                ));
            }
            if crate::has_dangerous_chars(tool) {
                return Err(format!(
                    "UnregisteredAgent '{}' tools_used entry contains control or format characters",
                    self.agent_id
                ));
            }
        }
        Ok(())
    }

    /// Deprecated alias for [`UnregisteredAgent::validate()`].
    #[deprecated(since = "4.0.1", note = "renamed to validate()")]
    pub fn validate_finite(&self) -> Result<(), String> {
        self.validate()
    }
}

/// A tool observed in traffic that is not in the approved tools list.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UnapprovedTool {
    pub tool_name: String,
    pub first_seen: String,
    pub request_count: u64,
    pub requesting_agents: HashSet<String>,
}

impl UnapprovedTool {
    /// Maximum number of requesting agents tracked per unapproved tool.
    const MAX_REQUESTING_AGENTS: usize = 1000;
    /// Maximum length for `tool_name` field.
    ///
    /// SECURITY (FIND-R113-014): Bound string fields.
    const MAX_TOOL_NAME_LEN: usize = 256;
    /// Maximum length for `first_seen` timestamp field.
    ///
    /// SECURITY (FIND-R113-014): Bound string fields.
    const MAX_TIMESTAMP_LEN: usize = 64;
    /// Maximum length for individual agent name entries in `requesting_agents`.
    ///
    /// SECURITY (FIND-R113-014): Bound per-entry lengths.
    const MAX_AGENT_NAME_LEN: usize = 256;

    /// Validate structural bounds, control/format character safety, and per-entry lengths.
    ///
    /// SECURITY (FIND-R49-008): Validate inner HashSet bounds.
    /// SECURITY (FIND-R113-014): Control/format char validation on string fields.
    pub fn validate(&self) -> Result<(), String> {
        if self.tool_name.len() > Self::MAX_TOOL_NAME_LEN {
            return Err(format!(
                "UnapprovedTool tool_name length {} exceeds max {}",
                self.tool_name.len(),
                Self::MAX_TOOL_NAME_LEN
            ));
        }
        if self.first_seen.len() > Self::MAX_TIMESTAMP_LEN {
            return Err(format!(
                "UnapprovedTool '{}' first_seen length {} exceeds max {}",
                self.tool_name,
                self.first_seen.len(),
                Self::MAX_TIMESTAMP_LEN
            ));
        }
        // SECURITY (FIND-R113-014): Control/format char validation.
        if crate::core::has_dangerous_chars(&self.tool_name) {
            return Err(
                "UnapprovedTool tool_name contains control or format characters".to_string(),
            );
        }
        if crate::core::has_dangerous_chars(&self.first_seen) {
            return Err(
                "UnapprovedTool first_seen contains control or format characters".to_string(),
            );
        }
        if self.requesting_agents.len() > Self::MAX_REQUESTING_AGENTS {
            return Err(format!(
                "UnapprovedTool '{}' requesting_agents count {} exceeds max {}",
                self.tool_name,
                self.requesting_agents.len(),
                Self::MAX_REQUESTING_AGENTS
            ));
        }
        // SECURITY (FIND-R113-014): Per-entry length bounds on requesting_agents.
        // SECURITY (FIND-R158-001): Per-entry control/format char validation.
        for agent in &self.requesting_agents {
            if agent.len() > Self::MAX_AGENT_NAME_LEN {
                return Err(format!(
                    "UnapprovedTool '{}' requesting_agents entry length {} exceeds max {}",
                    self.tool_name,
                    agent.len(),
                    Self::MAX_AGENT_NAME_LEN
                ));
            }
            if crate::has_dangerous_chars(agent) {
                return Err(format!(
                    "UnapprovedTool '{}' requesting_agents entry contains control or format characters",
                    self.tool_name
                ));
            }
        }
        Ok(())
    }
}

/// An MCP server observed in traffic that is not in the known servers list.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UnknownMcpServer {
    pub server_id: String,
    pub first_seen: String,
    pub connection_count: u64,
    pub advertised_tools: HashSet<String>,
}

impl UnknownMcpServer {
    /// Maximum number of advertised tools tracked per unknown server.
    const MAX_ADVERTISED_TOOLS: usize = 1000;
    /// Maximum length for `server_id` field.
    ///
    /// SECURITY (FIND-R113-014): Bound string fields.
    const MAX_SERVER_ID_LEN: usize = 256;
    /// Maximum length for `first_seen` timestamp field.
    ///
    /// SECURITY (FIND-R113-014): Bound string fields.
    const MAX_TIMESTAMP_LEN: usize = 64;
    /// Maximum length for individual tool name entries in `advertised_tools`.
    ///
    /// SECURITY (FIND-R113-014): Bound per-entry lengths.
    const MAX_TOOL_NAME_LEN: usize = 256;

    /// Validate structural bounds, control/format character safety, and per-entry lengths.
    ///
    /// SECURITY (FIND-R49-008): Validate inner HashSet bounds.
    /// SECURITY (FIND-R113-014): Control/format char validation on string fields.
    pub fn validate(&self) -> Result<(), String> {
        if self.server_id.len() > Self::MAX_SERVER_ID_LEN {
            return Err(format!(
                "UnknownMcpServer server_id length {} exceeds max {}",
                self.server_id.len(),
                Self::MAX_SERVER_ID_LEN
            ));
        }
        if self.first_seen.len() > Self::MAX_TIMESTAMP_LEN {
            return Err(format!(
                "UnknownMcpServer '{}' first_seen length {} exceeds max {}",
                self.server_id,
                self.first_seen.len(),
                Self::MAX_TIMESTAMP_LEN
            ));
        }
        // SECURITY (FIND-R113-014): Control/format char validation.
        if crate::core::has_dangerous_chars(&self.server_id) {
            return Err(
                "UnknownMcpServer server_id contains control or format characters".to_string(),
            );
        }
        if crate::core::has_dangerous_chars(&self.first_seen) {
            return Err(
                "UnknownMcpServer first_seen contains control or format characters".to_string(),
            );
        }
        if self.advertised_tools.len() > Self::MAX_ADVERTISED_TOOLS {
            return Err(format!(
                "UnknownMcpServer '{}' advertised_tools count {} exceeds max {}",
                self.server_id,
                self.advertised_tools.len(),
                Self::MAX_ADVERTISED_TOOLS
            ));
        }
        // SECURITY (FIND-R113-014): Per-entry length bounds on advertised_tools.
        // SECURITY (FIND-R158-001): Per-entry control/format char validation.
        for tool in &self.advertised_tools {
            if tool.len() > Self::MAX_TOOL_NAME_LEN {
                return Err(format!(
                    "UnknownMcpServer '{}' advertised_tools entry length {} exceeds max {}",
                    self.server_id,
                    tool.len(),
                    Self::MAX_TOOL_NAME_LEN
                ));
            }
            if crate::has_dangerous_chars(tool) {
                return Err(format!(
                    "UnknownMcpServer '{}' advertised_tools entry contains control or format characters",
                    self.server_id
                ));
            }
        }
        Ok(())
    }
}

/// Full shadow AI discovery report — inventory of all unregistered entities.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ShadowAiReport {
    pub unregistered_agents: Vec<UnregisteredAgent>,
    pub unapproved_tools: Vec<UnapprovedTool>,
    pub unknown_servers: Vec<UnknownMcpServer>,
    pub total_risk_score: f64,
}

impl ShadowAiReport {
    /// Maximum number of unregistered agents (matches runtime cap).
    const MAX_UNREGISTERED_AGENTS: usize = 1000;
    /// Maximum number of unapproved tools (matches runtime cap).
    const MAX_UNAPPROVED_TOOLS: usize = 500;
    /// Maximum number of unknown servers (matches runtime cap).
    const MAX_UNKNOWN_SERVERS: usize = 100;

    /// Validate structural invariants: finite scores, range checks, collection bounds,
    /// and nested element validation.
    ///
    /// SECURITY (FIND-P2-007): Non-finite total_risk_score could bypass
    /// threshold comparisons. Also validates nested UnregisteredAgent scores.
    /// SECURITY (FIND-R49-007): Validate collection bounds matching runtime caps.
    pub fn validate(&self) -> Result<(), String> {
        if !self.total_risk_score.is_finite() {
            return Err(format!(
                "ShadowAiReport has non-finite total_risk_score: {}",
                self.total_risk_score
            ));
        }
        // SECURITY (FIND-R51-001): Validate total_risk_score is in documented [0.0, 1.0] range.
        if self.total_risk_score < 0.0 || self.total_risk_score > 1.0 {
            return Err(format!(
                "ShadowAiReport total_risk_score must be in [0.0, 1.0], got {}",
                self.total_risk_score
            ));
        }
        if self.unregistered_agents.len() > Self::MAX_UNREGISTERED_AGENTS {
            return Err(format!(
                "ShadowAiReport unregistered_agents count {} exceeds max {}",
                self.unregistered_agents.len(),
                Self::MAX_UNREGISTERED_AGENTS
            ));
        }
        if self.unapproved_tools.len() > Self::MAX_UNAPPROVED_TOOLS {
            return Err(format!(
                "ShadowAiReport unapproved_tools count {} exceeds max {}",
                self.unapproved_tools.len(),
                Self::MAX_UNAPPROVED_TOOLS
            ));
        }
        if self.unknown_servers.len() > Self::MAX_UNKNOWN_SERVERS {
            return Err(format!(
                "ShadowAiReport unknown_servers count {} exceeds max {}",
                self.unknown_servers.len(),
                Self::MAX_UNKNOWN_SERVERS
            ));
        }
        // SECURITY (FIND-R203-004): Use validate() directly — validate_finite() is deprecated.
        for agent in &self.unregistered_agents {
            agent.validate()?;
        }
        for tool in &self.unapproved_tools {
            tool.validate()?;
        }
        for server in &self.unknown_servers {
            server.validate()?;
        }
        Ok(())
    }

    /// Deprecated alias for [`ShadowAiReport::validate()`].
    #[deprecated(since = "4.0.1", note = "renamed to validate()")]
    pub fn validate_finite(&self) -> Result<(), String> {
        self.validate()
    }
}