claude-agent 0.2.25

Rust SDK for building AI agents with Anthropic's Claude - Direct API, no CLI dependency
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
//! TOCTOU-safe path resolution using openat() with O_NOFOLLOW.

use std::ffi::{CString, OsStr, OsString};
use std::os::unix::ffi::OsStrExt;
use std::os::unix::io::{AsFd, BorrowedFd, OwnedFd};
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;

use rustix::fs::{Mode, OFlags, openat};
use rustix::io::Errno;

use crate::security::SecurityError;

#[derive(Debug)]
pub struct SafePath {
    root_fd: Arc<OwnedFd>,
    root_path: PathBuf,
    components: Vec<OsString>,
    resolved_path: PathBuf,
    permissive: bool,
}

impl SafePath {
    pub fn resolve(
        root_fd: Arc<OwnedFd>,
        root_path: PathBuf,
        relative_path: &Path,
        max_symlink_depth: u8,
    ) -> Result<Self, SecurityError> {
        let mut components = Vec::new();
        let mut symlink_depth = 0u8;

        for component in relative_path.components() {
            match component {
                Component::ParentDir => {
                    if components.is_empty() {
                        return Err(SecurityError::PathEscape(relative_path.to_path_buf()));
                    }
                    components.pop();
                }
                Component::CurDir | Component::RootDir => {}
                Component::Normal(name) => {
                    components.push(name.to_os_string());
                }
                Component::Prefix(_) => {}
            }
        }

        let mut validated_components = Vec::new();
        let mut current_fd: BorrowedFd<'_> = root_fd.as_fd();
        let mut owned_fds: Vec<OwnedFd> = Vec::new();

        for (i, component) in components.iter().enumerate() {
            let is_last = i == components.len() - 1;

            let c_name = CString::new(component.as_bytes())
                .map_err(|_| SecurityError::InvalidPath("null byte in path".into()))?;

            let flags = if is_last {
                OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC
            } else {
                OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC
            };

            match openat(current_fd, &c_name, flags, Mode::empty()) {
                Ok(fd) => {
                    validated_components.push(component.clone());
                    if !is_last {
                        owned_fds.push(fd);
                        // SAFETY: We just pushed to owned_fds, so last() is guaranteed to be Some
                        current_fd = owned_fds
                            .last()
                            .expect("owned_fds is non-empty after push")
                            .as_fd();
                    } else {
                        drop(fd);
                    }
                }
                Err(Errno::LOOP) | Err(Errno::MLINK) => {
                    symlink_depth += 1;
                    if symlink_depth > max_symlink_depth {
                        return Err(SecurityError::SymlinkDepthExceeded {
                            path: relative_path.to_path_buf(),
                            max: max_symlink_depth,
                        });
                    }

                    let target = rustix::fs::readlinkat(current_fd, &c_name, vec![0u8; 4096])
                        .map_err(|e| {
                            SecurityError::Io(std::io::Error::from_raw_os_error(e.raw_os_error()))
                        })?;

                    let target_path = PathBuf::from(OsStr::from_bytes(target.to_bytes()));
                    if target_path.is_absolute() {
                        if !target_path.starts_with(&root_path) {
                            return Err(SecurityError::AbsoluteSymlink(target_path));
                        }
                        let relative = target_path
                            .strip_prefix(&root_path)
                            .expect("path verified with starts_with");
                        return Self::resolve(
                            Arc::clone(&root_fd),
                            root_path,
                            relative,
                            max_symlink_depth - symlink_depth,
                        );
                    }

                    let mut remaining: Vec<OsString> = target_path
                        .components()
                        .filter_map(|c| match c {
                            Component::Normal(s) => Some(s.to_os_string()),
                            _ => None,
                        })
                        .collect();

                    remaining.extend(components.iter().skip(i + 1).cloned());

                    let new_path: PathBuf = remaining.iter().collect();
                    let current_path: PathBuf = validated_components.iter().collect();
                    let full_path = current_path.join(&new_path);

                    return Self::resolve(
                        Arc::clone(&root_fd),
                        root_path,
                        &full_path,
                        max_symlink_depth - symlink_depth,
                    );
                }
                Err(Errno::NOENT) => {
                    validated_components.push(component.clone());
                    validated_components.extend(components.iter().skip(i + 1).cloned());
                    break;
                }
                Err(e) => {
                    return Err(SecurityError::Io(std::io::Error::from_raw_os_error(
                        e.raw_os_error(),
                    )));
                }
            }
        }

        let resolved_path = root_path.join(validated_components.iter().collect::<PathBuf>());

        Ok(Self {
            root_fd,
            root_path,
            components: validated_components,
            resolved_path,
            permissive: false,
        })
    }

    /// Create a SafePath without validation (for permissive mode).
    /// This bypasses TOCTOU protection but allows symlinks.
    pub fn unchecked(root_fd: Arc<OwnedFd>, resolved_path: PathBuf) -> Self {
        let root_path = PathBuf::from("/");
        let components = resolved_path
            .strip_prefix("/")
            .unwrap_or(&resolved_path)
            .components()
            .filter_map(|c| match c {
                Component::Normal(s) => Some(s.to_os_string()),
                _ => None,
            })
            .collect();

        Self {
            root_fd,
            root_path,
            components,
            resolved_path,
            permissive: true,
        }
    }

    pub fn is_permissive(&self) -> bool {
        self.permissive
    }

    pub fn root_fd(&self) -> BorrowedFd<'_> {
        self.root_fd.as_fd()
    }

    pub fn root_path(&self) -> &Path {
        &self.root_path
    }

    pub fn components(&self) -> &[OsString] {
        &self.components
    }

    pub fn as_path(&self) -> &Path {
        &self.resolved_path
    }

    pub fn filename(&self) -> Option<&OsStr> {
        self.components.last().map(|s| s.as_os_str())
    }

    pub fn parent_components(&self) -> &[OsString] {
        if self.components.is_empty() {
            &[]
        } else {
            &self.components[..self.components.len() - 1]
        }
    }

    pub fn open(&self, flags: OFlags) -> Result<OwnedFd, SecurityError> {
        // In permissive mode, use standard library to handle symlinks
        if self.permissive {
            use std::fs::OpenOptions;
            use std::os::unix::fs::OpenOptionsExt;

            let mut opts = OpenOptions::new();

            if flags.contains(OFlags::RDONLY) && !flags.contains(OFlags::WRONLY) {
                opts.read(true);
            }
            if flags.contains(OFlags::WRONLY) || flags.contains(OFlags::RDWR) {
                opts.write(true);
            }
            if flags.contains(OFlags::RDWR) {
                opts.read(true);
            }
            if flags.contains(OFlags::CREATE) {
                opts.create(true);
            }
            if flags.contains(OFlags::TRUNC) {
                opts.truncate(true);
            }
            if flags.contains(OFlags::APPEND) {
                opts.append(true);
            }

            opts.mode(0o644);

            let file = opts.open(&self.resolved_path).map_err(SecurityError::Io)?;
            return Ok(file.into());
        }

        if self.components.is_empty() {
            let fd = rustix::fs::openat(
                self.root_fd.as_fd(),
                c".",
                flags | OFlags::CLOEXEC,
                Mode::empty(),
            )
            .map_err(|e| SecurityError::Io(std::io::Error::from_raw_os_error(e.raw_os_error())))?;
            return Ok(fd);
        }

        let mut current_fd: BorrowedFd<'_> = self.root_fd.as_fd();
        let mut owned_fds: Vec<OwnedFd> = Vec::new();

        for (i, component) in self.components.iter().enumerate() {
            let is_last = i == self.components.len() - 1;
            let c_name = CString::new(component.as_bytes())
                .map_err(|_| SecurityError::InvalidPath("null byte".into()))?;

            let open_flags = if is_last {
                flags | OFlags::NOFOLLOW | OFlags::CLOEXEC
            } else {
                OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC
            };

            let fd = openat(current_fd, &c_name, open_flags, Mode::from_raw_mode(0o644)).map_err(
                |e| SecurityError::Io(std::io::Error::from_raw_os_error(e.raw_os_error())),
            )?;

            if is_last {
                return Ok(fd);
            }

            owned_fds.push(fd);
            // SAFETY: We just pushed to owned_fds, so last() is guaranteed to be Some
            current_fd = owned_fds
                .last()
                .expect("owned_fds is non-empty after push")
                .as_fd();
        }

        unreachable!("loop always returns on is_last")
    }

    pub fn create_parent_dirs(&self) -> Result<(), SecurityError> {
        if self.components.len() <= 1 {
            return Ok(());
        }

        // In permissive mode, use standard library to handle symlinks
        if self.permissive {
            if let Some(parent) = self.resolved_path.parent() {
                std::fs::create_dir_all(parent)?;
            }
            return Ok(());
        }

        let mut current_fd: BorrowedFd<'_> = self.root_fd.as_fd();
        let mut owned_fds: Vec<OwnedFd> = Vec::new();

        for component in self.parent_components() {
            let c_name = CString::new(component.as_bytes())
                .map_err(|_| SecurityError::InvalidPath("null byte".into()))?;

            match openat(
                current_fd,
                &c_name,
                OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
                Mode::empty(),
            ) {
                Ok(fd) => {
                    owned_fds.push(fd);
                    // SAFETY: We just pushed to owned_fds, so last() is guaranteed to be Some
                    current_fd = owned_fds
                        .last()
                        .expect("owned_fds is non-empty after push")
                        .as_fd();
                }
                Err(Errno::NOENT) => {
                    rustix::fs::mkdirat(current_fd, &c_name, Mode::from_raw_mode(0o755)).map_err(
                        |e| SecurityError::Io(std::io::Error::from_raw_os_error(e.raw_os_error())),
                    )?;

                    let fd = openat(
                        current_fd,
                        &c_name,
                        OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
                        Mode::empty(),
                    )
                    .map_err(|e| {
                        SecurityError::Io(std::io::Error::from_raw_os_error(e.raw_os_error()))
                    })?;

                    owned_fds.push(fd);
                    // SAFETY: We just pushed to owned_fds, so last() is guaranteed to be Some
                    current_fd = owned_fds
                        .last()
                        .expect("owned_fds is non-empty after push")
                        .as_fd();
                }
                Err(e) => {
                    return Err(SecurityError::Io(std::io::Error::from_raw_os_error(
                        e.raw_os_error(),
                    )));
                }
            }
        }

        Ok(())
    }
}

impl Clone for SafePath {
    fn clone(&self) -> Self {
        Self {
            root_fd: Arc::clone(&self.root_fd),
            root_path: self.root_path.clone(),
            components: self.components.clone(),
            resolved_path: self.resolved_path.clone(),
            permissive: self.permissive,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;

    fn open_dir(path: &Path) -> Arc<OwnedFd> {
        let fd = std::fs::File::open(path).unwrap();
        Arc::new(fd.into())
    }

    #[test]
    fn test_resolve_simple() {
        let dir = tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();
        fs::write(root.join("test.txt"), "content").unwrap();

        let root_fd = open_dir(&root);
        let path = SafePath::resolve(root_fd, root.clone(), Path::new("test.txt"), 10).unwrap();

        assert_eq!(path.as_path(), root.join("test.txt"));
    }

    #[test]
    fn test_resolve_nonexistent() {
        let dir = tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();

        let root_fd = open_dir(&root);
        let path = SafePath::resolve(root_fd, root.clone(), Path::new("newfile.txt"), 10).unwrap();

        assert_eq!(path.as_path(), root.join("newfile.txt"));
    }

    #[test]
    fn test_path_traversal_blocked() {
        let dir = tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();

        let root_fd = open_dir(&root);
        let result = SafePath::resolve(root_fd, root, Path::new("../../../etc/passwd"), 10);

        assert!(matches!(result, Err(SecurityError::PathEscape(_))));
    }

    #[test]
    fn test_symlink_within_sandbox() {
        let dir = tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();

        fs::write(root.join("target.txt"), "content").unwrap();
        std::os::unix::fs::symlink("target.txt", root.join("link.txt")).unwrap();

        let root_fd = open_dir(&root);
        let path = SafePath::resolve(root_fd, root.clone(), Path::new("link.txt"), 10).unwrap();

        assert_eq!(path.as_path(), root.join("target.txt"));
    }

    #[test]
    fn test_symlink_depth_limit() {
        let dir = tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();

        for i in 0..15 {
            let target = if i == 14 {
                "final.txt".to_string()
            } else {
                format!("link{}.txt", i + 1)
            };
            std::os::unix::fs::symlink(&target, root.join(format!("link{}.txt", i))).unwrap();
        }
        fs::write(root.join("final.txt"), "content").unwrap();

        let root_fd = open_dir(&root);
        let result = SafePath::resolve(root_fd, root, Path::new("link0.txt"), 10);

        assert!(matches!(
            result,
            Err(SecurityError::SymlinkDepthExceeded { .. })
        ));
    }
}