elicitation 0.8.0

Conversational elicitation of strongly-typed Rust values via MCP
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
//! Path byte-level validation foundation.
//!
//! This module provides validated path byte sequences with platform-specific
//! constraints. It forms the foundation for path contract types.

use super::ValidationError;
use super::utf8::Utf8Bytes;

// ============================================================================
// Unix Path Constraints
// ============================================================================
//
// Valid Unix Paths:
//   - Valid UTF-8 encoding (reuse Utf8Bytes!)
//   - No null bytes (\0)
//   - Any other byte allowed
//   - Path separator: /
//   - Absolute: starts with /
//   - Relative: does not start with /
//
// Special paths:
//   - "/" - root directory
//   - "." - current directory
//   - ".." - parent directory
//   - "~" - home directory (shell expansion, not path itself)

// ============================================================================
// PathBytes (Unix)
// ============================================================================

#[cfg(unix)]
/// A validated Unix path (UTF-8 + no null bytes).
///
/// Generic over maximum length for bounded verification.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PathBytes<const MAX_LEN: usize = 4096> {
    utf8: Utf8Bytes<MAX_LEN>,
}

#[cfg(unix)]
impl<const MAX_LEN: usize> PathBytes<MAX_LEN> {
    /// Create from byte slice (Kani-friendly, no Vec allocation).
    ///
    /// # Errors
    ///
    /// Returns `ValidationError::InvalidUtf8` if not valid UTF-8.
    /// Returns `ValidationError::TooLong` if exceeds MAX_LEN.
    /// Returns `ValidationError::PathContainsNull` if contains null bytes.
    pub fn from_slice(bytes: &[u8]) -> Result<Self, ValidationError> {
        let len = bytes.len();

        if len > MAX_LEN {
            return Err(ValidationError::TooLong {
                max: MAX_LEN,
                actual: len,
            });
        }

        // Copy to fixed array (Kani's native domain!)
        let mut fixed = [0u8; MAX_LEN];
        fixed[..len].copy_from_slice(bytes);

        // Validate UTF-8 (reuse existing foundation!)
        let utf8 = Utf8Bytes::new(fixed, len)?;

        // Then check for null bytes
        #[cfg(kani)]
        {
            // Under Kani: symbolic validation (trust stdlib string handling)
            let has_null: bool = kani::any();
            if has_null {
                return Err(ValidationError::PathContainsNull);
            }
        }
        #[cfg(not(kani))]
        {
            // Production: actual validation
            if has_null_byte(utf8.as_str()) {
                return Err(ValidationError::PathContainsNull);
            }
        }

        Ok(Self { utf8 })
    }

    /// Create from Vec (user-facing API, delegates to from_slice).
    ///
    /// # Errors
    ///
    /// Returns `ValidationError::InvalidUtf8` if not valid UTF-8.
    /// Returns `ValidationError::TooLong` if exceeds MAX_LEN.
    /// Returns `ValidationError::PathContainsNull` if contains null bytes.
    pub fn new(bytes: Vec<u8>) -> Result<Self, ValidationError> {
        Self::from_slice(&bytes)
    }

    /// Get the path as a string slice.
    pub fn as_str(&self) -> &str {
        self.utf8.as_str()
    }

    /// Get the path as bytes.
    pub fn as_bytes(&self) -> &[u8] {
        self.utf8.as_str().as_bytes()
    }

    /// Get the length in bytes.
    pub fn len(&self) -> usize {
        self.utf8.len()
    }

    /// Check if the path is empty.
    pub fn is_empty(&self) -> bool {
        self.utf8.is_empty()
    }

    /// Check if this is an absolute path (starts with /).
    pub fn is_absolute(&self) -> bool {
        is_absolute(self.as_str())
    }

    /// Check if this is a relative path (does not start with /).
    pub fn is_relative(&self) -> bool {
        !self.is_absolute()
    }

    /// Check if this is the root directory (/).
    pub fn is_root(&self) -> bool {
        self.as_str() == "/"
    }
}

impl<const MAX_LEN: usize> std::fmt::Display for PathBytes<MAX_LEN> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.utf8)
    }
}

// ============================================================================
// Validation Functions
// ============================================================================

/// Check if string contains null bytes.
pub fn has_null_byte(s: &str) -> bool {
    let bytes = s.as_bytes();
    let len = bytes.len();

    // Manual loop with explicit bound to help Kani
    let mut i = 0;
    while i < len {
        if bytes[i] == 0 {
            return true;
        }
        i += 1;
    }
    false
}

/// Check if path is absolute (starts with /).
#[cfg(unix)]
pub fn is_absolute(path: &str) -> bool {
    let bytes = path.as_bytes();
    !bytes.is_empty() && bytes[0] == b'/'
}

/// Check if path is relative (does not start with /).
#[cfg(unix)]
pub fn is_relative(path: &str) -> bool {
    !is_absolute(path)
}

// ============================================================================
// Contract Types
// ============================================================================

#[cfg(unix)]
/// A Unix path guaranteed to be absolute (starts with /).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PathAbsolute<const MAX_LEN: usize = 4096>(PathBytes<MAX_LEN>);

#[cfg(unix)]
impl<const MAX_LEN: usize> PathAbsolute<MAX_LEN> {
    /// Create from byte slice (Kani-friendly).
    ///
    /// # Errors
    ///
    /// Returns validation errors from PathBytes, plus:
    /// Returns `ValidationError::PathNotAbsolute` if path doesn't start with /.
    pub fn from_slice(bytes: &[u8]) -> Result<Self, ValidationError> {
        let path = PathBytes::from_slice(bytes)?;

        #[cfg(kani)]
        {
            // Under Kani: symbolic absolute check (trust path property logic)
            let is_rel: bool = kani::any();
            if is_rel {
                // Can't call path.to_string() - just return error without payload
                return Err(ValidationError::PathNotAbsolute(String::new()));
            }
        }
        #[cfg(not(kani))]
        {
            // Production: actual check
            if !path.is_absolute() {
                return Err(ValidationError::PathNotAbsolute(path.to_string()));
            }
        }

        Ok(Self(path))
    }

    /// Create from Vec (user-facing API).
    ///
    /// # Errors
    ///
    /// Returns validation errors from PathBytes, plus:
    /// Returns `ValidationError::PathNotAbsolute` if path doesn't start with /.
    pub fn new(bytes: Vec<u8>) -> Result<Self, ValidationError> {
        Self::from_slice(&bytes)
    }

    /// Get the underlying PathBytes.
    pub fn get(&self) -> &PathBytes<MAX_LEN> {
        &self.0
    }

    /// Get the path as a string slice.
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }

    /// Unwrap into the underlying PathBytes.
    pub fn into_inner(self) -> PathBytes<MAX_LEN> {
        self.0
    }
}

#[cfg(unix)]
/// A Unix path guaranteed to be relative (does not start with /).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PathRelative<const MAX_LEN: usize = 4096>(PathBytes<MAX_LEN>);

#[cfg(unix)]
impl<const MAX_LEN: usize> PathRelative<MAX_LEN> {
    /// Create from byte slice (Kani-friendly).
    ///
    /// # Errors
    ///
    /// Returns validation errors from PathBytes, plus:
    /// Returns `ValidationError::PathNotRelative` if path starts with /.
    pub fn from_slice(bytes: &[u8]) -> Result<Self, ValidationError> {
        let path = PathBytes::from_slice(bytes)?;

        #[cfg(kani)]
        {
            // Under Kani: symbolic relative check (trust path property logic)
            let is_abs: bool = kani::any();
            if is_abs {
                // Can't call path.to_string() - just return error without payload
                return Err(ValidationError::PathNotRelative(String::new()));
            }
        }
        #[cfg(not(kani))]
        {
            // Production: actual check
            if !path.is_relative() {
                return Err(ValidationError::PathNotRelative(path.to_string()));
            }
        }

        Ok(Self(path))
    }

    /// Create from Vec (user-facing API).
    ///
    /// # Errors
    ///
    /// Returns validation errors from PathBytes, plus:
    /// Returns `ValidationError::PathNotRelative` if path starts with /.
    pub fn new(bytes: Vec<u8>) -> Result<Self, ValidationError> {
        Self::from_slice(&bytes)
    }

    /// Get the underlying PathBytes.
    pub fn get(&self) -> &PathBytes<MAX_LEN> {
        &self.0
    }

    /// Get the path as a string slice.
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }

    /// Unwrap into the underlying PathBytes.
    pub fn into_inner(self) -> PathBytes<MAX_LEN> {
        self.0
    }
}

#[cfg(unix)]
/// A Unix path guaranteed to be non-empty.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PathNonEmpty<const MAX_LEN: usize = 4096>(PathBytes<MAX_LEN>);

#[cfg(unix)]
impl<const MAX_LEN: usize> PathNonEmpty<MAX_LEN> {
    /// Create from byte slice (Kani-friendly).
    ///
    /// # Errors
    ///
    /// Returns validation errors from PathBytes, plus:
    /// Returns `ValidationError::EmptyString` if path is empty.
    pub fn from_slice(bytes: &[u8]) -> Result<Self, ValidationError> {
        let path = PathBytes::from_slice(bytes)?;

        if path.is_empty() {
            return Err(ValidationError::EmptyString);
        }

        Ok(Self(path))
    }

    /// Create from Vec (user-facing API).
    ///
    /// # Errors
    ///
    /// Returns validation errors from PathBytes, plus:
    /// Returns `ValidationError::EmptyString` if path is empty.
    pub fn new(bytes: Vec<u8>) -> Result<Self, ValidationError> {
        Self::from_slice(&bytes)
    }

    /// Get the underlying PathBytes.
    pub fn get(&self) -> &PathBytes<MAX_LEN> {
        &self.0
    }

    /// Get the path as a string slice.
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }

    /// Unwrap into the underlying PathBytes.
    pub fn into_inner(self) -> PathBytes<MAX_LEN> {
        self.0
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(all(test, unix))]
mod tests {
    use super::*;

    #[test]
    fn test_valid_unix_path() {
        let bytes = b"/home/user/file.txt".to_vec();
        let path = PathBytes::<4096>::new(bytes);
        assert!(path.is_ok());
        assert_eq!(path.unwrap().as_str(), "/home/user/file.txt");
    }

    #[test]
    fn test_path_with_null_rejected() {
        let bytes = b"/home/\0user/file.txt".to_vec();
        let path = PathBytes::<4096>::new(bytes);
        assert!(path.is_err());
    }

    #[test]
    fn test_invalid_utf8_rejected() {
        let bytes = vec![0xFF, 0xFE]; // Invalid UTF-8
        let path = PathBytes::<4096>::new(bytes);
        assert!(path.is_err());
    }

    #[test]
    fn test_absolute_path_detection() {
        let bytes = b"/home/user".to_vec();
        let path = PathBytes::<4096>::new(bytes).unwrap();
        assert!(path.is_absolute());
        assert!(!path.is_relative());
    }

    #[test]
    fn test_relative_path_detection() {
        let bytes = b"home/user".to_vec();
        let path = PathBytes::<4096>::new(bytes).unwrap();
        assert!(path.is_relative());
        assert!(!path.is_absolute());
    }

    #[test]
    fn test_root_path() {
        let bytes = b"/".to_vec();
        let path = PathBytes::<4096>::new(bytes).unwrap();
        assert!(path.is_root());
        assert!(path.is_absolute());
    }

    #[test]
    fn test_path_absolute_construction() {
        let bytes = b"/home/user".to_vec();
        let abs = PathAbsolute::<4096>::new(bytes);
        assert!(abs.is_ok());

        let bytes = b"home/user".to_vec();
        let abs = PathAbsolute::<4096>::new(bytes);
        assert!(abs.is_err());
    }

    #[test]
    fn test_path_relative_construction() {
        let bytes = b"home/user".to_vec();
        let rel = PathRelative::<4096>::new(bytes);
        assert!(rel.is_ok());

        let bytes = b"/home/user".to_vec();
        let rel = PathRelative::<4096>::new(bytes);
        assert!(rel.is_err());
    }

    #[test]
    fn test_path_nonempty_construction() {
        let bytes = b"/home".to_vec();
        let nonempty = PathNonEmpty::<4096>::new(bytes);
        assert!(nonempty.is_ok());

        let bytes = b"".to_vec();
        let nonempty = PathNonEmpty::<4096>::new(bytes);
        assert!(nonempty.is_err());
    }

    #[test]
    fn test_special_paths() {
        // Current directory
        let bytes = b".".to_vec();
        let path = PathBytes::<4096>::new(bytes).unwrap();
        assert!(path.is_relative());

        // Parent directory
        let bytes = b"..".to_vec();
        let path = PathBytes::<4096>::new(bytes).unwrap();
        assert!(path.is_relative());

        // Relative with ..
        let bytes = b"../parent".to_vec();
        let path = PathBytes::<4096>::new(bytes).unwrap();
        assert!(path.is_relative());
    }
}