Skip to main content

vellaveto_types/
task.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
8//! MCP 2025-11-25 compliance types and Phase 11 secure task primitives.
9
10use serde::{Deserialize, Serialize};
11use std::fmt;
12
13/// Maximum number of metadata entries in `TaskCreateParams`.
14const MAX_TASK_METADATA_ENTRIES: usize = 64;
15
16/// Parameters for the MCP 2025-11-25 `tasks/create` method.
17///
18/// The `tasks/create` method allows clients to explicitly create a new async task
19/// for a specified tool invocation. The server assigns a task ID and begins
20/// executing the tool in the background.
21#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
22#[serde(deny_unknown_fields)]
23pub struct TaskCreateParams {
24    /// The tool to invoke for this task.
25    pub tool: String,
26    /// Arguments to pass to the tool.
27    #[serde(default)]
28    pub arguments: serde_json::Value,
29    /// Optional client-supplied task ID. If omitted, the server generates one.
30    #[serde(default, skip_serializing_if = "Option::is_none")]
31    pub task_id: Option<String>,
32    /// Optional metadata for the task (e.g., labels, priority hints).
33    #[serde(default, skip_serializing_if = "Option::is_none")]
34    pub metadata: Option<serde_json::Map<String, serde_json::Value>>,
35}
36
37impl TaskCreateParams {
38    /// Maximum length for `tool` field (bytes).
39    const MAX_TOOL_LEN: usize = 256;
40    /// Maximum length for `task_id` field (bytes).
41    const MAX_TASK_ID_LEN: usize = 256;
42    /// Maximum serialized size for `arguments` (bytes).
43    const MAX_ARGUMENTS_SIZE: usize = 1_048_576; // 1 MiB
44    /// Maximum length for individual metadata keys (bytes).
45    const MAX_METADATA_KEY_LEN: usize = 256;
46    /// Maximum serialized size for individual metadata values (bytes).
47    const MAX_METADATA_VALUE_SIZE: usize = 8192;
48
49    /// Validate structural bounds on all fields.
50    ///
51    /// SECURITY: Prevents memory exhaustion and control character injection
52    /// from untrusted `tasks/create` payloads.
53    pub fn validate(&self) -> Result<(), String> {
54        // Validate tool
55        if self.tool.is_empty() {
56            return Err("TaskCreateParams tool must not be empty".to_string());
57        }
58        if self.tool.len() > Self::MAX_TOOL_LEN {
59            return Err(format!(
60                "TaskCreateParams tool length {} exceeds max {}",
61                self.tool.len(),
62                Self::MAX_TOOL_LEN,
63            ));
64        }
65        if crate::core::has_dangerous_chars(&self.tool) {
66            return Err("TaskCreateParams tool contains control or format characters".to_string());
67        }
68
69        // Validate arguments size
70        let args_size = serde_json::to_string(&self.arguments)
71            .map(|s| s.len())
72            .unwrap_or(0);
73        if args_size > Self::MAX_ARGUMENTS_SIZE {
74            return Err(format!(
75                "TaskCreateParams arguments serialized size {} exceeds max {}",
76                args_size,
77                Self::MAX_ARGUMENTS_SIZE,
78            ));
79        }
80
81        // Validate optional task_id
82        if let Some(ref tid) = self.task_id {
83            if tid.is_empty() {
84                return Err("TaskCreateParams task_id must not be empty when provided".to_string());
85            }
86            if tid.len() > Self::MAX_TASK_ID_LEN {
87                return Err(format!(
88                    "TaskCreateParams task_id length {} exceeds max {}",
89                    tid.len(),
90                    Self::MAX_TASK_ID_LEN,
91                ));
92            }
93            if crate::core::has_dangerous_chars(tid) {
94                return Err(
95                    "TaskCreateParams task_id contains control or format characters".to_string(),
96                );
97            }
98        }
99
100        // Validate metadata
101        if let Some(ref meta) = self.metadata {
102            if meta.len() > MAX_TASK_METADATA_ENTRIES {
103                return Err(format!(
104                    "TaskCreateParams metadata entry count {} exceeds max {}",
105                    meta.len(),
106                    MAX_TASK_METADATA_ENTRIES,
107                ));
108            }
109            for (key, value) in meta {
110                if key.len() > Self::MAX_METADATA_KEY_LEN {
111                    return Err(format!(
112                        "TaskCreateParams metadata key length {} exceeds max {}",
113                        key.len(),
114                        Self::MAX_METADATA_KEY_LEN,
115                    ));
116                }
117                if crate::core::has_dangerous_chars(key) {
118                    return Err(
119                        "TaskCreateParams metadata key contains control or format characters"
120                            .to_string(),
121                    );
122                }
123                let val_size = serde_json::to_string(value).map(|s| s.len()).unwrap_or(0);
124                if val_size > Self::MAX_METADATA_VALUE_SIZE {
125                    return Err(format!(
126                        "TaskCreateParams metadata value size {} exceeds max {}",
127                        val_size,
128                        Self::MAX_METADATA_VALUE_SIZE,
129                    ));
130                }
131            }
132        }
133
134        Ok(())
135    }
136}
137
138/// Status of an async MCP task for lifecycle tracking.
139///
140/// MCP 2025-11-25 introduces async tasks that run in the background.
141/// This enum tracks the current state for policy enforcement and audit.
142#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
143#[serde(rename_all = "snake_case")]
144#[serde(deny_unknown_fields)]
145pub enum TaskStatus {
146    /// Task has been accepted but not yet started.
147    #[default]
148    Pending,
149    /// Task is currently executing.
150    Running,
151    /// Task completed successfully.
152    Completed,
153    /// Task failed with an error.
154    Failed { reason: String },
155    /// Task was cancelled by request.
156    Cancelled,
157    /// Task expired due to timeout.
158    Expired,
159}
160
161impl TaskStatus {
162    /// Maximum length for the `reason` field in `Failed` variant.
163    const MAX_REASON_LEN: usize = 4096;
164
165    /// Validate structural bounds on variant fields.
166    ///
167    /// SECURITY (R243-TYP-2): The `Failed { reason }` string flows through
168    /// `Display` into audit logs and API responses. Without validation,
169    /// control characters or oversized strings can corrupt log output.
170    pub fn validate(&self) -> Result<(), String> {
171        if let TaskStatus::Failed { reason } = self {
172            if reason.len() > Self::MAX_REASON_LEN {
173                return Err(format!(
174                    "TaskStatus::Failed reason length {} exceeds max {}",
175                    reason.len(),
176                    Self::MAX_REASON_LEN,
177                ));
178            }
179            if crate::core::has_dangerous_chars(reason) {
180                return Err(
181                    "TaskStatus::Failed reason contains control or format characters".to_string(),
182                );
183            }
184        }
185        Ok(())
186    }
187}
188
189impl fmt::Display for TaskStatus {
190    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191        match self {
192            TaskStatus::Pending => write!(f, "pending"),
193            TaskStatus::Running => write!(f, "running"),
194            TaskStatus::Completed => write!(f, "completed"),
195            TaskStatus::Failed { reason } => write!(f, "failed: {reason}"),
196            TaskStatus::Cancelled => write!(f, "cancelled"),
197            TaskStatus::Expired => write!(f, "expired"),
198        }
199    }
200}
201
202/// A tracked async MCP task for lifecycle management.
203///
204/// Vellaveto tracks task state to enforce policies on:
205/// - Maximum concurrent tasks per session/agent
206/// - Task duration limits
207/// - Cancellation authorization (self-cancel only vs. any agent)
208#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
209#[serde(deny_unknown_fields)]
210pub struct TrackedTask {
211    /// Unique task identifier from the MCP server.
212    pub task_id: String,
213    /// Tool that created this task.
214    pub tool: String,
215    /// Function that created this task.
216    pub function: String,
217    /// Current task status.
218    pub status: TaskStatus,
219    /// ISO 8601 timestamp when the task was created.
220    pub created_at: String,
221    /// ISO 8601 timestamp when the task expires (if set).
222    #[serde(default, skip_serializing_if = "Option::is_none")]
223    pub expires_at: Option<String>,
224    /// Agent ID that created this task (for cancellation authorization).
225    #[serde(default, skip_serializing_if = "Option::is_none")]
226    pub created_by: Option<String>,
227    /// Session ID this task belongs to.
228    #[serde(default, skip_serializing_if = "Option::is_none")]
229    pub session_id: Option<String>,
230}
231
232impl TrackedTask {
233    /// Maximum length for `task_id` (bytes).
234    const MAX_TASK_ID_LEN: usize = 256;
235    /// Maximum length for `tool` (bytes).
236    const MAX_TOOL_LEN: usize = 256;
237    /// Maximum length for `function` (bytes).
238    const MAX_FUNCTION_LEN: usize = 256;
239    /// Maximum length for ISO 8601 timestamp fields (bytes).
240    const MAX_TIMESTAMP_LEN: usize = 64;
241    /// Maximum length for `created_by` and `session_id` (bytes).
242    const MAX_ID_FIELD_LEN: usize = 256;
243
244    /// Returns true if the task is in a terminal state.
245    pub fn is_terminal(&self) -> bool {
246        matches!(
247            self.status,
248            TaskStatus::Completed
249                | TaskStatus::Failed { .. }
250                | TaskStatus::Cancelled
251                | TaskStatus::Expired
252        )
253    }
254
255    /// Returns true if the task is active (pending or running).
256    pub fn is_active(&self) -> bool {
257        matches!(self.status, TaskStatus::Pending | TaskStatus::Running)
258    }
259
260    /// Validate structural bounds on fields.
261    ///
262    /// SECURITY (FIND-R53-P3-002): Prevents memory exhaustion and control character
263    /// injection from untrusted `TrackedTask` payloads.
264    pub fn validate(&self) -> Result<(), String> {
265        if self.task_id.is_empty() {
266            return Err("TrackedTask task_id must not be empty".to_string());
267        }
268        if self.task_id.len() > Self::MAX_TASK_ID_LEN {
269            return Err(format!(
270                "TrackedTask task_id length {} exceeds max {}",
271                self.task_id.len(),
272                Self::MAX_TASK_ID_LEN,
273            ));
274        }
275        if crate::core::has_dangerous_chars(&self.task_id) {
276            return Err("TrackedTask task_id contains control or format characters".to_string());
277        }
278        // SECURITY (R243-TYP-2): Validate nested TaskStatus (Failed reason).
279        self.status
280            .validate()
281            .map_err(|e| format!("TrackedTask status: {e}"))?;
282        if self.tool.is_empty() {
283            return Err("TrackedTask tool must not be empty".to_string());
284        }
285        if self.tool.len() > Self::MAX_TOOL_LEN {
286            return Err(format!(
287                "TrackedTask tool length {} exceeds max {}",
288                self.tool.len(),
289                Self::MAX_TOOL_LEN,
290            ));
291        }
292        if crate::core::has_dangerous_chars(&self.tool) {
293            return Err("TrackedTask tool contains control or format characters".to_string());
294        }
295        if self.function.is_empty() {
296            return Err("TrackedTask function must not be empty".to_string());
297        }
298        if self.function.len() > Self::MAX_FUNCTION_LEN {
299            return Err(format!(
300                "TrackedTask function length {} exceeds max {}",
301                self.function.len(),
302                Self::MAX_FUNCTION_LEN,
303            ));
304        }
305        if crate::core::has_dangerous_chars(&self.function) {
306            return Err("TrackedTask function contains control or format characters".to_string());
307        }
308        if self.created_at.len() > Self::MAX_TIMESTAMP_LEN {
309            return Err(format!(
310                "TrackedTask created_at length {} exceeds max {}",
311                self.created_at.len(),
312                Self::MAX_TIMESTAMP_LEN,
313            ));
314        }
315        // SECURITY (FIND-R203-002): Reject control/format chars and validate ISO 8601 format.
316        if crate::core::has_dangerous_chars(&self.created_at) {
317            return Err("TrackedTask created_at contains control or format characters".to_string());
318        }
319        if !self.created_at.is_empty() {
320            crate::time_util::parse_iso8601_secs(&self.created_at)
321                .map_err(|e| format!("TrackedTask created_at is not valid ISO 8601: {e}"))?;
322        }
323        if let Some(ref ea) = self.expires_at {
324            if ea.len() > Self::MAX_TIMESTAMP_LEN {
325                return Err(format!(
326                    "TrackedTask expires_at length {} exceeds max {}",
327                    ea.len(),
328                    Self::MAX_TIMESTAMP_LEN,
329                ));
330            }
331            // SECURITY (FIND-R203-002): Reject control/format chars and validate ISO 8601 format.
332            if crate::core::has_dangerous_chars(ea) {
333                return Err(
334                    "TrackedTask expires_at contains control or format characters".to_string(),
335                );
336            }
337            if !ea.is_empty() {
338                crate::time_util::parse_iso8601_secs(ea)
339                    .map_err(|e| format!("TrackedTask expires_at is not valid ISO 8601: {e}"))?;
340            }
341        }
342        if let Some(ref cb) = self.created_by {
343            if cb.len() > Self::MAX_ID_FIELD_LEN {
344                return Err(format!(
345                    "TrackedTask created_by length {} exceeds max {}",
346                    cb.len(),
347                    Self::MAX_ID_FIELD_LEN,
348                ));
349            }
350            if cb
351                .chars()
352                .any(|c| c.is_control() || crate::core::is_unicode_format_char(c))
353            {
354                return Err(
355                    "TrackedTask created_by contains control or format characters".to_string(),
356                );
357            }
358        }
359        if let Some(ref sid) = self.session_id {
360            if sid.len() > Self::MAX_ID_FIELD_LEN {
361                return Err(format!(
362                    "TrackedTask session_id length {} exceeds max {}",
363                    sid.len(),
364                    Self::MAX_ID_FIELD_LEN,
365                ));
366            }
367            if sid
368                .chars()
369                .any(|c| c.is_control() || crate::core::is_unicode_format_char(c))
370            {
371                return Err(
372                    "TrackedTask session_id contains control or format characters".to_string(),
373                );
374            }
375        }
376        Ok(())
377    }
378}
379
380/// A state transition in a task's hash chain for tamper detection.
381///
382/// Each transition records the previous hash, new state, and produces
383/// a new hash, forming an append-only chain that detects tampering.
384#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
385#[serde(deny_unknown_fields)]
386pub struct TaskStateTransition {
387    /// Sequence number in the hash chain (0-indexed).
388    pub sequence: u64,
389    /// SHA-256 hash of the previous transition (empty string for first).
390    pub prev_hash: String,
391    /// The new task status after this transition.
392    pub new_status: TaskStatus,
393    /// ISO 8601 timestamp of this transition.
394    pub timestamp: String,
395    /// Agent ID that triggered this transition.
396    #[serde(default, skip_serializing_if = "Option::is_none")]
397    pub triggered_by: Option<String>,
398    /// `SHA-256` hash of this transition (computed from `prev_hash` + `new_status` + timestamp).
399    pub hash: String,
400}
401
402impl TaskStateTransition {
403    /// Maximum hash field length (SHA-256 hex = 64 chars, with margin).
404    const MAX_HASH_LEN: usize = 256;
405    /// Maximum timestamp field length.
406    const MAX_TIMESTAMP_LEN: usize = 64;
407
408    /// Validate bounds on deserialized data.
409    ///
410    /// Checks all string fields for length bounds and control characters.
411    pub fn validate(&self) -> Result<(), String> {
412        if self.hash.len() > Self::MAX_HASH_LEN {
413            return Err(format!(
414                "TaskStateTransition hash length {} exceeds max {}",
415                self.hash.len(),
416                Self::MAX_HASH_LEN,
417            ));
418        }
419        if self.prev_hash.len() > Self::MAX_HASH_LEN {
420            return Err(format!(
421                "TaskStateTransition prev_hash length {} exceeds max {}",
422                self.prev_hash.len(),
423                Self::MAX_HASH_LEN,
424            ));
425        }
426        if self.timestamp.len() > Self::MAX_TIMESTAMP_LEN {
427            return Err(format!(
428                "TaskStateTransition timestamp length {} exceeds max {}",
429                self.timestamp.len(),
430                Self::MAX_TIMESTAMP_LEN,
431            ));
432        }
433        // SECURITY (FIND-R203-002): Reject control/format chars in timestamp.
434        if crate::core::has_dangerous_chars(&self.timestamp) {
435            return Err(
436                "TaskStateTransition timestamp contains control or format characters".to_string(),
437            );
438        }
439        if let Some(ref tb) = self.triggered_by {
440            if tb.len() > MAX_ENTRY_LEN {
441                return Err(format!(
442                    "TaskStateTransition triggered_by length {} exceeds max {}",
443                    tb.len(),
444                    MAX_ENTRY_LEN,
445                ));
446            }
447            // SECURITY (FIND-R112-005): Reject Unicode format characters in addition to control chars.
448            if crate::core::has_dangerous_chars(tb) {
449                return Err(
450                    "TaskStateTransition triggered_by contains control or format characters"
451                        .to_string(),
452                );
453            }
454        }
455        Ok(())
456    }
457}
458
459/// Maximum byte length for individual entries in `state_chain` hashes and `seen_nonces`.
460pub const MAX_ENTRY_LEN: usize = 256;
461
462/// A secure task with encryption and integrity protection.
463///
464/// Extends `TrackedTask` with:
465/// - Encrypted state data (`ChaCha20-Poly1305`)
466/// - Hash chain for tamper detection
467/// - Resume token for authenticated task resumption
468/// - Replay protection via nonces
469#[derive(Clone, Serialize, Deserialize, PartialEq)]
470#[serde(deny_unknown_fields)]
471pub struct SecureTask {
472    /// The underlying tracked task.
473    pub task: TrackedTask,
474    /// Encrypted task state/result data (base64-encoded ciphertext).
475    /// Only present when task has state to protect.
476    #[serde(default, skip_serializing_if = "Option::is_none")]
477    pub encrypted_state: Option<String>,
478    /// Nonce used for encryption (base64-encoded, 12 bytes for ChaCha20-Poly1305).
479    #[serde(default, skip_serializing_if = "Option::is_none")]
480    pub encryption_nonce: Option<String>,
481    /// Hash chain of state transitions for tamper detection.
482    #[serde(default)]
483    pub state_chain: Vec<TaskStateTransition>,
484    /// HMAC-SHA256 resume token (hex-encoded) for authenticated resumption.
485    /// Generated on task creation, verified on resume requests.
486    #[serde(default, skip_serializing_if = "Option::is_none")]
487    pub resume_token: Option<String>,
488    /// Nonces seen for replay protection (hex-encoded).
489    /// Prevents replaying old task resume/cancel requests.
490    #[serde(default)]
491    pub seen_nonces: Vec<String>,
492    /// Maximum number of nonces to track (FIFO eviction).
493    /// Capped at `MAX_NONCES_CAP` (10,000) to prevent memory exhaustion.
494    #[serde(
495        default = "default_max_nonces",
496        deserialize_with = "deserialize_capped_max_nonces"
497    )]
498    pub max_nonces: usize,
499}
500
501/// Absolute upper bound for `max_nonces` to prevent memory exhaustion.
502pub const MAX_NONCES_CAP: usize = 10_000;
503
504/// SECURITY (FIND-R49-001): Maximum number of state chain entries to prevent
505/// unbounded growth from repeated status transitions.
506pub const MAX_STATE_CHAIN: usize = 1_000;
507
508fn default_max_nonces() -> usize {
509    1000
510}
511
512fn deserialize_capped_max_nonces<'de, D>(deserializer: D) -> Result<usize, D::Error>
513where
514    D: serde::Deserializer<'de>,
515{
516    let value = usize::deserialize(deserializer)?;
517    Ok(value.min(MAX_NONCES_CAP))
518}
519
520impl SecureTask {
521    /// Create a new secure task from a tracked task.
522    pub fn new(task: TrackedTask) -> Self {
523        Self {
524            task,
525            encrypted_state: None,
526            encryption_nonce: None,
527            state_chain: Vec::new(),
528            resume_token: None,
529            seen_nonces: Vec::new(),
530            max_nonces: default_max_nonces(),
531        }
532    }
533
534    /// Check if a nonce has been seen (replay detection).
535    pub fn is_nonce_seen(&self, nonce: &str) -> bool {
536        self.seen_nonces.iter().any(|n| n == nonce)
537    }
538
539    /// Record a nonce as seen.
540    /// Enforces `MAX_NONCES_CAP` regardless of `max_nonces` field value.
541    /// SECURITY (FIND-R60-007): Truncates nonce to `MAX_ENTRY_LEN` bytes at
542    /// runtime to match the `validate()` bound and prevent memory exhaustion
543    /// from attacker-controlled nonce values.
544    pub fn record_nonce(&mut self, nonce: String) {
545        let effective_max = self.max_nonces.min(MAX_NONCES_CAP);
546        if self.seen_nonces.len() >= effective_max {
547            self.seen_nonces.remove(0); // FIFO eviction
548        }
549        // Enforce MAX_ENTRY_LEN at runtime, not just in validate().
550        // SECURITY (FIND-R104-001): Walk back to a char boundary to avoid
551        // a panic on multi-byte UTF-8 sequences straddling the limit.
552        let nonce = if nonce.len() > MAX_ENTRY_LEN {
553            let mut end = MAX_ENTRY_LEN;
554            while end > 0 && !nonce.is_char_boundary(end) {
555                end -= 1;
556            }
557            nonce[..end].to_string()
558        } else {
559            nonce
560        };
561        self.seen_nonces.push(nonce);
562    }
563
564    /// Get the latest hash in the state chain.
565    pub fn latest_hash(&self) -> Option<&str> {
566        self.state_chain.last().map(|t| t.hash.as_str())
567    }
568
569    /// Get the current sequence number.
570    pub fn current_sequence(&self) -> u64 {
571        self.state_chain.last().map_or(0, |t| t.sequence)
572    }
573
574    /// Validate bounds on deserialized data.
575    pub fn validate(&self) -> Result<(), String> {
576        // SECURITY (FIND-R67-FC-002): Validate the inner TrackedTask first.
577        self.task
578            .validate()
579            .map_err(|e| format!("SecureTask inner task: {e}"))?;
580
581        if self.state_chain.len() > MAX_STATE_CHAIN {
582            return Err(format!(
583                "SecureTask state_chain length {} exceeds max {}",
584                self.state_chain.len(),
585                MAX_STATE_CHAIN
586            ));
587        }
588        if self.seen_nonces.len() > MAX_NONCES_CAP {
589            return Err(format!(
590                "SecureTask seen_nonces length {} exceeds max {}",
591                self.seen_nonces.len(),
592                MAX_NONCES_CAP
593            ));
594        }
595        for (i, nonce) in self.seen_nonces.iter().enumerate() {
596            if nonce.len() > MAX_ENTRY_LEN {
597                return Err(format!(
598                    "SecureTask seen_nonces[{}] length {} exceeds max {}",
599                    i,
600                    nonce.len(),
601                    MAX_ENTRY_LEN
602                ));
603            }
604        }
605        for (i, transition) in self.state_chain.iter().enumerate() {
606            // SECURITY (FIND-R67-MV-001): Delegate to TaskStateTransition::validate()
607            // which checks all fields including hash, prev_hash, timestamp, triggered_by.
608            transition
609                .validate()
610                .map_err(|e| format!("SecureTask state_chain[{i}]: {e}"))?;
611        }
612        Ok(())
613    }
614}
615
616impl fmt::Debug for SecureTask {
617    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
618        f.debug_struct("SecureTask")
619            .field("task", &self.task)
620            .field("encrypted_state", &self.encrypted_state)
621            .field("encryption_nonce", &self.encryption_nonce)
622            .field("state_chain", &self.state_chain)
623            .field(
624                "resume_token",
625                &self.resume_token.as_ref().map(|_| "[REDACTED]"),
626            )
627            .field("seen_nonces", &self.seen_nonces)
628            .field("max_nonces", &self.max_nonces)
629            .finish()
630    }
631}
632
633/// A checkpoint of task state for verification.
634///
635/// Checkpoints are signed snapshots that can be used to verify
636/// task state integrity at a specific point in time.
637#[derive(Clone, Serialize, Deserialize, PartialEq)]
638#[serde(deny_unknown_fields)]
639pub struct TaskCheckpoint {
640    /// Unique checkpoint identifier.
641    pub checkpoint_id: String,
642    /// Task ID this checkpoint belongs to.
643    pub task_id: String,
644    /// Sequence number in the state chain at checkpoint time.
645    pub sequence: u64,
646    /// Hash of the state chain at checkpoint time.
647    pub state_hash: String,
648    /// ISO 8601 timestamp of checkpoint creation.
649    pub created_at: String,
650    /// Ed25519 signature of the checkpoint (hex-encoded).
651    pub signature: String,
652    /// Public key used to sign (hex-encoded).
653    pub public_key: String,
654}
655
656/// SECURITY (FIND-R53-001): Custom Debug redacts `signature` and `public_key`
657/// to prevent secret leakage in logs/debug output.
658impl fmt::Debug for TaskCheckpoint {
659    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
660        f.debug_struct("TaskCheckpoint")
661            .field("checkpoint_id", &self.checkpoint_id)
662            .field("task_id", &self.task_id)
663            .field("sequence", &self.sequence)
664            .field("state_hash", &self.state_hash)
665            .field("created_at", &self.created_at)
666            .field("signature", &"[REDACTED]")
667            .field("public_key", &"[REDACTED]")
668            .finish()
669    }
670}
671
672impl TaskCheckpoint {
673    /// Maximum length for `checkpoint_id` (bytes).
674    const MAX_CHECKPOINT_ID_LEN: usize = 256;
675    /// Maximum length for `task_id` (bytes).
676    const MAX_TASK_ID_LEN: usize = 256;
677    /// Maximum length for `state_hash` (bytes).
678    const MAX_HASH_LEN: usize = 256;
679    /// Maximum length for ISO 8601 timestamp fields (bytes).
680    const MAX_TIMESTAMP_LEN: usize = 64;
681    /// Maximum length for hex-encoded signature (bytes).
682    const MAX_SIGNATURE_LEN: usize = 512;
683    /// Maximum length for hex-encoded public key (bytes).
684    const MAX_PUBLIC_KEY_LEN: usize = 512;
685
686    /// Validate structural bounds on fields.
687    ///
688    /// SECURITY (FIND-R53-P3-003): Prevents memory exhaustion and control character
689    /// injection from untrusted `TaskCheckpoint` payloads.
690    pub fn validate(&self) -> Result<(), String> {
691        if self.checkpoint_id.is_empty() {
692            return Err("TaskCheckpoint checkpoint_id must not be empty".to_string());
693        }
694        if self.checkpoint_id.len() > Self::MAX_CHECKPOINT_ID_LEN {
695            return Err(format!(
696                "TaskCheckpoint checkpoint_id length {} exceeds max {}",
697                self.checkpoint_id.len(),
698                Self::MAX_CHECKPOINT_ID_LEN,
699            ));
700        }
701        if crate::core::has_dangerous_chars(&self.checkpoint_id) {
702            return Err(
703                "TaskCheckpoint checkpoint_id contains control or format characters".to_string(),
704            );
705        }
706        if self.task_id.is_empty() {
707            return Err("TaskCheckpoint task_id must not be empty".to_string());
708        }
709        if self.task_id.len() > Self::MAX_TASK_ID_LEN {
710            return Err(format!(
711                "TaskCheckpoint task_id length {} exceeds max {}",
712                self.task_id.len(),
713                Self::MAX_TASK_ID_LEN,
714            ));
715        }
716        if crate::core::has_dangerous_chars(&self.task_id) {
717            return Err("TaskCheckpoint task_id contains control or format characters".to_string());
718        }
719        if self.state_hash.len() > Self::MAX_HASH_LEN {
720            return Err(format!(
721                "TaskCheckpoint state_hash length {} exceeds max {}",
722                self.state_hash.len(),
723                Self::MAX_HASH_LEN,
724            ));
725        }
726        if self.created_at.len() > Self::MAX_TIMESTAMP_LEN {
727            return Err(format!(
728                "TaskCheckpoint created_at length {} exceeds max {}",
729                self.created_at.len(),
730                Self::MAX_TIMESTAMP_LEN,
731            ));
732        }
733        // SECURITY (FIND-R224-003): Validate state_hash, created_at, signature, and
734        // public_key for dangerous characters. These fields could be used for log
735        // injection or identity confusion if control/format characters are present.
736        if crate::core::has_dangerous_chars(&self.state_hash) {
737            return Err(
738                "TaskCheckpoint state_hash contains control or format characters".to_string(),
739            );
740        }
741        if crate::core::has_dangerous_chars(&self.created_at) {
742            return Err(
743                "TaskCheckpoint created_at contains control or format characters".to_string(),
744            );
745        }
746        if self.signature.len() > Self::MAX_SIGNATURE_LEN {
747            return Err(format!(
748                "TaskCheckpoint signature length {} exceeds max {}",
749                self.signature.len(),
750                Self::MAX_SIGNATURE_LEN,
751            ));
752        }
753        if crate::core::has_dangerous_chars(&self.signature) {
754            return Err(
755                "TaskCheckpoint signature contains control or format characters".to_string(),
756            );
757        }
758        if self.public_key.len() > Self::MAX_PUBLIC_KEY_LEN {
759            return Err(format!(
760                "TaskCheckpoint public_key length {} exceeds max {}",
761                self.public_key.len(),
762                Self::MAX_PUBLIC_KEY_LEN,
763            ));
764        }
765        if crate::core::has_dangerous_chars(&self.public_key) {
766            return Err(
767                "TaskCheckpoint public_key contains control or format characters".to_string(),
768            );
769        }
770        Ok(())
771    }
772}
773
774/// Request to resume a task with authentication.
775#[derive(Clone, Serialize, Deserialize)]
776#[serde(deny_unknown_fields)]
777pub struct TaskResumeRequest {
778    /// Task ID to resume.
779    pub task_id: String,
780    /// Resume token for authentication.
781    pub resume_token: String,
782    /// Unique nonce for replay protection (hex-encoded).
783    pub nonce: String,
784    /// Agent ID requesting the resume.
785    #[serde(default, skip_serializing_if = "Option::is_none")]
786    pub agent_id: Option<String>,
787}
788
789impl TaskResumeRequest {
790    /// Maximum length for `task_id` (bytes).
791    const MAX_TASK_ID_LEN: usize = 256;
792    /// Maximum length for `resume_token` (bytes).
793    const MAX_RESUME_TOKEN_LEN: usize = 512;
794    /// Maximum length for `nonce` (bytes).
795    const MAX_NONCE_LEN: usize = 256;
796    /// Maximum length for `agent_id` (bytes).
797    const MAX_AGENT_ID_LEN: usize = 256;
798
799    /// Validate structural bounds on all fields.
800    ///
801    /// SECURITY (R243-TYP-1): `task_id` is used as a HashMap key in
802    /// `SecureTaskManager`, `nonce` is stored in `seen_nonces`, and
803    /// `resume_token` is compared in constant-time. Without validation,
804    /// oversized or control-character-laden strings cause memory exhaustion
805    /// and log injection.
806    pub fn validate(&self) -> Result<(), String> {
807        if self.task_id.is_empty() {
808            return Err("TaskResumeRequest task_id must not be empty".to_string());
809        }
810        if self.task_id.len() > Self::MAX_TASK_ID_LEN {
811            return Err(format!(
812                "TaskResumeRequest task_id length {} exceeds max {}",
813                self.task_id.len(),
814                Self::MAX_TASK_ID_LEN,
815            ));
816        }
817        if crate::core::has_dangerous_chars(&self.task_id) {
818            return Err(
819                "TaskResumeRequest task_id contains control or format characters".to_string(),
820            );
821        }
822        if self.resume_token.is_empty() {
823            return Err("TaskResumeRequest resume_token must not be empty".to_string());
824        }
825        if self.resume_token.len() > Self::MAX_RESUME_TOKEN_LEN {
826            return Err(format!(
827                "TaskResumeRequest resume_token length {} exceeds max {}",
828                self.resume_token.len(),
829                Self::MAX_RESUME_TOKEN_LEN,
830            ));
831        }
832        if crate::core::has_dangerous_chars(&self.resume_token) {
833            return Err(
834                "TaskResumeRequest resume_token contains control or format characters".to_string(),
835            );
836        }
837        if self.nonce.is_empty() {
838            return Err("TaskResumeRequest nonce must not be empty".to_string());
839        }
840        if self.nonce.len() > Self::MAX_NONCE_LEN {
841            return Err(format!(
842                "TaskResumeRequest nonce length {} exceeds max {}",
843                self.nonce.len(),
844                Self::MAX_NONCE_LEN,
845            ));
846        }
847        if crate::core::has_dangerous_chars(&self.nonce) {
848            return Err(
849                "TaskResumeRequest nonce contains control or format characters".to_string(),
850            );
851        }
852        if let Some(ref aid) = self.agent_id {
853            if aid.len() > Self::MAX_AGENT_ID_LEN {
854                return Err(format!(
855                    "TaskResumeRequest agent_id length {} exceeds max {}",
856                    aid.len(),
857                    Self::MAX_AGENT_ID_LEN,
858                ));
859            }
860            if crate::core::has_dangerous_chars(aid) {
861                return Err(
862                    "TaskResumeRequest agent_id contains control or format characters".to_string(),
863                );
864            }
865        }
866        Ok(())
867    }
868}
869
870impl fmt::Debug for TaskResumeRequest {
871    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
872        f.debug_struct("TaskResumeRequest")
873            .field("task_id", &self.task_id)
874            .field("resume_token", &"[REDACTED]")
875            .field("nonce", &self.nonce)
876            .field("agent_id", &self.agent_id)
877            .finish()
878    }
879}
880
881/// Result of a task resume attempt.
882#[derive(Debug, Clone, Serialize, Deserialize)]
883#[serde(deny_unknown_fields)]
884pub struct TaskResumeResult {
885    /// Whether the resume was authorized.
886    pub authorized: bool,
887    /// The task if authorized.
888    #[serde(default, skip_serializing_if = "Option::is_none")]
889    pub task: Option<SecureTask>,
890    /// Decrypted state data if authorized and available.
891    #[serde(default, skip_serializing_if = "Option::is_none")]
892    pub decrypted_state: Option<serde_json::Value>,
893    /// Reason for denial if not authorized.
894    #[serde(default, skip_serializing_if = "Option::is_none")]
895    pub denial_reason: Option<String>,
896}
897
898impl TaskResumeResult {
899    /// Maximum length for `denial_reason` field.
900    const MAX_DENIAL_REASON_LEN: usize = 4096;
901
902    /// Validate structural bounds on deserialized data.
903    ///
904    /// SECURITY (FIND-R216-012): Validates nested SecureTask and denial_reason
905    /// to prevent oversized or injection-prone strings.
906    pub fn validate(&self) -> Result<(), String> {
907        if let Some(ref task) = self.task {
908            task.validate()
909                .map_err(|e| format!("TaskResumeResult task: {e}"))?;
910        }
911        if let Some(ref reason) = self.denial_reason {
912            if reason.len() > Self::MAX_DENIAL_REASON_LEN {
913                return Err(format!(
914                    "TaskResumeResult denial_reason length {} exceeds max {}",
915                    reason.len(),
916                    Self::MAX_DENIAL_REASON_LEN,
917                ));
918            }
919            if crate::core::has_dangerous_chars(reason) {
920                return Err(
921                    "TaskResumeResult denial_reason contains control or format characters"
922                        .to_string(),
923                );
924            }
925        }
926        Ok(())
927    }
928}
929
930/// Result of validating a task's state chain integrity.
931#[derive(Debug, Clone, Serialize, Deserialize)]
932#[serde(deny_unknown_fields)]
933pub struct TaskIntegrityResult {
934    /// Whether the state chain is valid.
935    pub valid: bool,
936    /// Number of transitions verified.
937    pub transitions_verified: u64,
938    /// First broken transition index if invalid.
939    #[serde(default, skip_serializing_if = "Option::is_none")]
940    pub first_broken_at: Option<u64>,
941    /// Reason for failure if invalid.
942    #[serde(default, skip_serializing_if = "Option::is_none")]
943    pub failure_reason: Option<String>,
944}
945
946impl TaskIntegrityResult {
947    /// Maximum length for `failure_reason` field.
948    const MAX_FAILURE_REASON_LEN: usize = 4096;
949
950    /// Validate structural bounds on deserialized data.
951    ///
952    /// SECURITY (FIND-R216-012): Validates failure_reason to prevent oversized
953    /// or injection-prone strings.
954    pub fn validate(&self) -> Result<(), String> {
955        if let Some(ref reason) = self.failure_reason {
956            if reason.len() > Self::MAX_FAILURE_REASON_LEN {
957                return Err(format!(
958                    "TaskIntegrityResult failure_reason length {} exceeds max {}",
959                    reason.len(),
960                    Self::MAX_FAILURE_REASON_LEN,
961                ));
962            }
963            if crate::core::has_dangerous_chars(reason) {
964                return Err(
965                    "TaskIntegrityResult failure_reason contains control or format characters"
966                        .to_string(),
967                );
968            }
969        }
970        Ok(())
971    }
972}
973
974/// Statistics about secure task management.
975#[derive(Debug, Clone, Default, Serialize, Deserialize)]
976#[serde(deny_unknown_fields)]
977pub struct SecureTaskStats {
978    /// Total secure tasks tracked.
979    pub total_tasks: usize,
980    /// Tasks with encrypted state.
981    pub encrypted_tasks: usize,
982    /// Total state transitions recorded.
983    pub total_transitions: u64,
984    /// Checkpoints created.
985    pub checkpoints_created: u64,
986    /// Resume attempts.
987    pub resume_attempts: u64,
988    /// Successful resumes.
989    pub resume_successes: u64,
990    /// Replay attacks blocked.
991    pub replay_attacks_blocked: u64,
992    /// Integrity violations detected.
993    pub integrity_violations: u64,
994}
995
996impl SecureTaskStats {
997    /// Validate structural invariants.
998    ///
999    /// SECURITY (FIND-R216-012): Currently all fields are bounded integer types,
1000    /// but provided for forward-compatibility and API consistency.
1001    pub fn validate(&self) -> Result<(), String> {
1002        // All fields are u64/usize — no string bounds to check.
1003        Ok(())
1004    }
1005}