aft-base 0.67.1

Shared foundation for Agent Foundational Toolkit
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
//! Private store creation, independent of the process umask. These helpers are
//! for AFT-owned state, never for edits or restorations in the user's project.

use std::fs::{self, File, OpenOptions};
use std::io::{self, Write};
use std::path::{Path, PathBuf};

#[cfg(unix)]
pub const DIR_MODE: u32 = 0o700;
#[cfg(unix)]
pub(crate) const FILE_MODE: u32 = 0o600;

/// Ancestor descriptors need lookup and metadata, not directory enumeration.
/// Linux O_PATH is allowed by Landlock without READ_DIR: keep walking from `/`
/// with O_NOFOLLOW rather than skipping ancestors the sandbox cannot read.
/// Ownership and symlink checks still run on the pinned descriptors. The final
/// directory/file is opened normally before any read, chmod, or fsync.
#[cfg(unix)]
pub(crate) fn ancestor_dir_flags() -> libc::c_int {
    #[cfg(target_os = "linux")]
    let access = libc::O_PATH;
    #[cfg(not(target_os = "linux"))]
    let access = libc::O_RDONLY;
    access | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC
}

pub fn create_dir_all(path: impl AsRef<Path>) -> io::Result<()> {
    let path = path.as_ref();
    if let Some(access) = crate::cache_location::pin_cache_path(path)? {
        access.directory(true)?;
        return Ok(());
    }
    crate::cache_location::refuse_new_durable_cache_entry(path)?;
    let mut builder = fs::DirBuilder::new();
    builder.recursive(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::DirBuilderExt;
        builder.mode(DIR_MODE);
    }
    builder.create(path)
}

pub fn create_dir(path: &Path) -> io::Result<()> {
    if let Some(access) = crate::cache_location::pin_cache_path(path)? {
        let (parent, name) = access.parent()?;
        let child = parent.repair_create_dir(&name)?;
        return child.repair_check_boundary(&access.root, &[]);
    }
    crate::cache_location::refuse_new_durable_cache_entry(path)?;
    #[allow(unused_mut)]
    let mut builder = fs::DirBuilder::new();
    #[cfg(unix)]
    {
        use std::os::unix::fs::DirBuilderExt;
        builder.mode(DIR_MODE);
    }
    builder.create(path)
}

pub fn options() -> OpenOptions {
    #[allow(unused_mut)]
    let mut options = OpenOptions::new();
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.mode(FILE_MODE);
    }
    options
}

pub fn executable_options() -> OpenOptions {
    #[allow(unused_mut)]
    let mut options = options();
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.mode(DIR_MODE);
    }
    options
}

pub fn write_executable(path: &Path, contents: &[u8]) -> io::Result<()> {
    if let Some(access) = crate::cache_location::pin_cache_path(path)? {
        let (parent, name) = access.parent()?;
        let mut file = parent.repair_create_file(&name)?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            file.set_permissions(fs::Permissions::from_mode(DIR_MODE))?;
        }
        return file.write_all(contents);
    }
    executable_options()
        .write(true)
        .create(true)
        .truncate(true)
        .open(path)?
        .write_all(contents)
}

pub fn create(path: impl AsRef<Path>) -> io::Result<File> {
    if let Some(access) = crate::cache_location::pin_cache_path(path.as_ref())? {
        let (parent, name) = access.parent()?;
        return parent.repair_create_file(&name);
    }
    crate::cache_location::refuse_new_durable_cache_entry(path.as_ref())?;
    options().write(true).create(true).truncate(true).open(path)
}

pub fn write(path: impl AsRef<Path>, contents: impl AsRef<[u8]>) -> io::Result<()> {
    create(path)?.write_all(contents.as_ref())
}

/// Open a storage root and protect its immediate domains, without traversing
/// histories or indexes. Existing files need no walk behind a private directory.
pub fn open_root(root: &Path) -> io::Result<()> {
    create_dir_all(root)?;
    tighten_root(root);
    Ok(())
}

pub fn tighten_root(root: &Path) {
    tighten_within(root, root);
    #[cfg(unix)]
    if let Ok(entries) = root_entries(root) {
        for entry in entries.flatten() {
            if entry.file_type().is_ok_and(|kind| kind.is_dir()) {
                tighten_within(root, &entry.path());
            }
        }
    }
}

#[cfg(unix)]
fn root_entries(root: &Path) -> io::Result<fs::ReadDir> {
    #[cfg(any(test, feature = "test-support"))]
    ROOT_LISTINGS.with(|count| count.set(count.get() + 1));
    fs::read_dir(root)
}

#[cfg(all(any(test, feature = "test-support"), unix))]
thread_local! {
    static ROOT_LISTINGS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

#[cfg(all(any(test, feature = "test-support"), unix))]
pub fn root_listings_for_test() -> usize {
    ROOT_LISTINGS.with(std::cell::Cell::get)
}

#[cfg(all(test, unix))]
mod directory_tests {
    use super::*;
    use std::os::unix::fs::PermissionsExt;

    #[test]
    fn private_storage_root_repairs_domains_but_open_dir_does_not_list() {
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path().join("state");
        let domain = root.join("domain");
        fs::create_dir_all(&domain).unwrap();
        fs::set_permissions(&root, fs::Permissions::from_mode(0o755)).unwrap();
        fs::set_permissions(&domain, fs::Permissions::from_mode(0o755)).unwrap();
        let before = root_listings_for_test();
        open_dir(&root, &root).unwrap();
        assert_eq!(root_listings_for_test(), before);
        assert_eq!(
            fs::metadata(&root).unwrap().permissions().mode() & 0o777,
            0o700
        );
        assert_eq!(
            fs::metadata(&domain).unwrap().permissions().mode() & 0o777,
            0o755
        );
        open_root(&root).unwrap();
        assert_eq!(root_listings_for_test(), before + 1);
        assert_eq!(
            fs::metadata(&domain).unwrap().permissions().mode() & 0o777,
            0o700
        );
    }
}

/// Protect only the ancestors of the domain/per-root directory being opened.
/// No chmod is attempted above `root`, or through a symlink inside the store.
pub fn open_dir(root: &Path, path: &Path) -> io::Result<()> {
    create_dir_all(path)?;
    tighten_open_dir(root, path);
    Ok(())
}

pub fn tighten_open_dir(root: &Path, path: &Path) {
    tighten_within(root, root);
    if let Ok(relative) = path.strip_prefix(root) {
        let mut current = root.to_path_buf();
        for component in relative.components() {
            if !matches!(component, std::path::Component::Normal(_)) {
                break;
            }
            current.push(component);
            tighten_within(root, &current);
        }
    }
}

/// Keyed caches normally have `<root>/<domain>/<key>` layout. Explicit cache
/// paths used by embedding callers are their own boundary, not a reason to
/// chmod two arbitrary parents outside AFT's storage.
pub fn open_keyed_dir(path: &Path, domain: &str) -> io::Result<()> {
    let root = path
        .parent()
        .filter(|parent| parent.file_name().is_some_and(|name| name == domain))
        .and_then(Path::parent)
        .unwrap_or(path);
    open_dir(root, path)
}

pub fn tighten_keyed_dir(path: &Path, domain: &str) {
    let root = path
        .parent()
        .filter(|parent| parent.file_name().is_some_and(|name| name == domain))
        .and_then(Path::parent)
        .unwrap_or(path);
    tighten_open_dir(root, path);
}

#[cfg(unix)]
fn tighten_within(root: &Path, path: &Path) {
    use std::os::fd::{AsRawFd, FromRawFd};
    use std::os::unix::ffi::OsStrExt;
    use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
    let result = (|| -> io::Result<()> {
        let relative = path.strip_prefix(root).map_err(io::Error::other)?;
        // Open each component relative to its pinned parent. O_NOFOLLOW on just
        // the final path would still chmod a target through a symlinked ancestor.
        let mut directory = OpenOptions::new()
            .read(true)
            .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC)
            .open(root)?;
        for component in relative.components() {
            let std::path::Component::Normal(name) = component else {
                return Ok(());
            };
            let name = std::ffi::CString::new(name.as_bytes()).map_err(io::Error::other)?;
            let fd = unsafe {
                libc::openat(
                    directory.as_raw_fd(),
                    name.as_ptr(),
                    libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
                )
            };
            if fd < 0 {
                return Err(io::Error::last_os_error());
            }
            directory = unsafe { File::from_raw_fd(fd) };
        }
        if directory.metadata()?.permissions().mode() & 0o077 != 0 {
            directory.set_permissions(fs::Permissions::from_mode(DIR_MODE))?;
        }
        Ok(())
    })();
    if let Err(error) = result {
        if error.kind() == io::ErrorKind::NotFound {
            return;
        }
        // A symlink is intentionally left alone, not a failed permission repair.
        if matches!(error.raw_os_error(), Some(libc::ELOOP | libc::ENOTDIR)) {
            return;
        }
        warn_once(path, &error);
    }
}

#[cfg(not(unix))]
fn tighten_within(_root: &Path, _path: &Path) {}

#[cfg(unix)]
fn warn_once(path: &Path, error: &io::Error) {
    use std::collections::HashSet;
    use std::sync::{Mutex, OnceLock};
    static WARNED: OnceLock<Mutex<HashSet<std::path::PathBuf>>> = OnceLock::new();
    if WARNED
        .get_or_init(Mutex::default)
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .insert(path.to_path_buf())
    {
        log::warn!(
            "could not tighten private storage {}: {error}; continuing",
            path.display()
        );
    }
}

/// SQLite derives WAL/SHM modes from the database. Reserve the database before
/// SQLite's first writable open, but never create a file for a read-only open.
pub fn prepare_sqlite(path: &Path, flags: rusqlite::OpenFlags) -> rusqlite::Result<()> {
    // With SQLITE_OPEN_URI, a name starting with `file:` is a URI, not a
    // filesystem path, so the cache-location checks must look at the file it
    // names. Handing them the URI text instead skips them on Unix (its
    // "ancestors" are relative names that do not exist) and fails outright on
    // Windows, where a name containing `:` or `?` is invalid (os error 123),
    // not missing.
    if flags.contains(rusqlite::OpenFlags::SQLITE_OPEN_URI) {
        match sqlite_uri_target(path) {
            Some(SqliteUriTarget::File(file)) => return prepare_sqlite_file(&file, flags, true),
            Some(SqliteUriTarget::NoFile) => return Ok(()),
            None => {}
        }
    }
    prepare_sqlite_file(path, flags, false)
}

/// `from_uri` is set when `path` was decoded from a `file:` URI. Such opens
/// get the cache-location checks but, as before those checks existed, no
/// reservation or permission repair outside a cache root: the URI callers
/// prepare the plain path themselves before opening it.
fn prepare_sqlite_file(
    path: &Path,
    flags: rusqlite::OpenFlags,
    from_uri: bool,
) -> rusqlite::Result<()> {
    let access = if flags.contains(rusqlite::OpenFlags::SQLITE_OPEN_MEMORY) {
        None
    } else {
        crate::cache_location::pin_cache_path(path)
            .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?
    };
    if let Some(access) = access {
        let result = (|| -> io::Result<()> {
            access.root.repair_validate_descendants(&access.relative)?;
            let (parent, name) = access.parent()?;
            let file = if flags.contains(rusqlite::OpenFlags::SQLITE_OPEN_CREATE) {
                match parent.repair_new_file(&name) {
                    Ok(file) => file,
                    Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
                        parent.repair_read_file(&name)?
                    }
                    Err(error) => return Err(error),
                }
            } else {
                parent.repair_read_file(&name)?
            };
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                if file.metadata()?.permissions().mode() & 0o077 != 0 {
                    file.set_permissions(fs::Permissions::from_mode(FILE_MODE))?;
                }
            }
            #[cfg(not(unix))]
            let _ = file;
            Ok(())
        })();
        return result.map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)));
    }
    crate::cache_location::check_cache_access(path)
        .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;
    if flags.intersects(
        rusqlite::OpenFlags::SQLITE_OPEN_CREATE | rusqlite::OpenFlags::SQLITE_OPEN_READ_WRITE,
    ) && !flags.contains(rusqlite::OpenFlags::SQLITE_OPEN_MEMORY)
    {
        crate::cache_location::refuse_durable_cache_write(path)
            .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;
    }
    #[cfg(unix)]
    if !from_uri
        && !flags.contains(rusqlite::OpenFlags::SQLITE_OPEN_MEMORY)
        && !path.as_os_str().is_empty()
        && path != Path::new(":memory:")
        && !path.to_string_lossy().starts_with("file:")
    {
        if flags.contains(rusqlite::OpenFlags::SQLITE_OPEN_CREATE) {
            match options().write(true).create_new(true).open(path) {
                Ok(_) => {}
                Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
                    tighten_sqlite_file(path)
                }
                Err(error) => return Err(rusqlite::Error::ToSqlConversionFailure(Box::new(error))),
            }
        } else {
            // Even a read-only schema peek can create the WAL index when its
            // parent is writable, so repair the selected database before it.
            tighten_sqlite_file(path);
        }
    }
    #[cfg(not(unix))]
    let _ = (path, flags, from_uri);
    Ok(())
}

/// What a SQLite `file:` URI opens (see <https://sqlite.org/uri.html>).
#[derive(Debug, PartialEq, Eq)]
enum SqliteUriTarget {
    /// A database file at this filesystem path.
    File(PathBuf),
    /// An in-memory or temporary database: nothing on disk to check.
    NoFile,
}

/// Decode a SQLite `file:` URI into the database it opens, or `None` when
/// `path` is not such a URI. Covers the forms AFT builds for read-only opens
/// (`file:///C:/...`, `file:///abs/...`, `file:relative`) with percent-encoding
/// and a query string.
fn sqlite_uri_target(path: &Path) -> Option<SqliteUriTarget> {
    let text = path.to_str()?;
    let rest = text.strip_prefix("file:")?;
    let end = rest.find(['?', '#']).unwrap_or(rest.len());
    let (encoded, tail) = rest.split_at(end);
    let query = tail
        .strip_prefix('?')
        .map(|query| query.split('#').next().unwrap_or_default())
        .unwrap_or_default();
    if query
        .split('&')
        .any(|param| param.eq_ignore_ascii_case("mode=memory"))
    {
        return Some(SqliteUriTarget::NoFile);
    }
    // `file://authority/path`: SQLite accepts an empty or `localhost`
    // authority; any other host is kept as a network (UNC) name.
    let encoded = match encoded.strip_prefix("//") {
        Some(after) => {
            let slash = after.find('/').unwrap_or(after.len());
            let (authority, path) = after.split_at(slash);
            if authority.is_empty() || authority.eq_ignore_ascii_case("localhost") {
                path.to_string()
            } else {
                format!("//{after}")
            }
        }
        None => encoded.to_string(),
    };
    let decoded = percent_decode(&encoded);
    if decoded.is_empty() || decoded == ":memory:" {
        return Some(SqliteUriTarget::NoFile);
    }
    #[cfg(windows)]
    let decoded = {
        // `/C:/dir/db` names drive C:; SQLite drops the leading slash too.
        let bytes = decoded.as_bytes();
        let decoded = if bytes.len() >= 3
            && bytes[0] == b'/'
            && bytes[1].is_ascii_alphabetic()
            && bytes[2] == b':'
        {
            decoded[1..].to_string()
        } else if decoded.starts_with(r"/\\") {
            // `/\\?\C:\...` is a verbatim (`\\?\`) or UNC path whose
            // backslashes the URI kept percent-encoded, as the call-graph
            // store's read-only URI spells long and resolved paths. SQLite
            // drops the leading slash before opening it.
            decoded[1..].to_string()
        } else {
            decoded
        };
        // Restore the separators the URI form replaced: a verbatim `\\?\`
        // path only accepts backslashes.
        decoded.replace('/', "\\")
    };
    Some(SqliteUriTarget::File(PathBuf::from(decoded)))
}

fn percent_decode(text: &str) -> String {
    let bytes = text.as_bytes();
    let mut decoded = Vec::with_capacity(bytes.len());
    let mut index = 0;
    while index < bytes.len() {
        let hex = |byte: u8| (byte as char).to_digit(16);
        if bytes[index] == b'%' && index + 2 < bytes.len() {
            if let (Some(high), Some(low)) = (hex(bytes[index + 1]), hex(bytes[index + 2])) {
                decoded.push((high * 16 + low) as u8);
                index += 3;
                continue;
            }
        }
        decoded.push(bytes[index]);
        index += 1;
    }
    String::from_utf8_lossy(&decoded).into_owned()
}

/// Repair the one database being opened so newly created sidecars cannot
/// inherit an old public mode. No directory or sibling file is changed here.
#[cfg(unix)]
fn tighten_sqlite_file(path: &Path) {
    use std::os::fd::{AsRawFd, FromRawFd};
    use std::os::unix::ffi::OsStrExt;
    use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
    // Already-private databases are the hot path. No chmod is needed, so one
    // lstat avoids reopening every ancestor on each read connection.
    if fs::symlink_metadata(path)
        .is_ok_and(|metadata| !metadata.is_file() || metadata.permissions().mode() & 0o077 == 0)
    {
        return;
    }
    let result = (|| -> io::Result<()> {
        let absolute = if path.is_absolute() {
            path.to_path_buf()
        } else {
            std::env::current_dir()?.join(path)
        };
        let mut handle = OpenOptions::new()
            .read(true)
            .custom_flags(ancestor_dir_flags())
            .open("/")?;
        let components: Vec<_> = absolute.components().collect();
        for (index, component) in components.iter().enumerate().skip(1) {
            let std::path::Component::Normal(name) = component else {
                return Ok(());
            };
            let name = std::ffi::CString::new(name.as_bytes()).map_err(io::Error::other)?;
            let flags = if index + 1 == components.len() {
                libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_CLOEXEC
            } else {
                ancestor_dir_flags()
            };
            let fd = unsafe { libc::openat(handle.as_raw_fd(), name.as_ptr(), flags) };
            if fd < 0 {
                return Err(io::Error::last_os_error());
            }
            handle = unsafe { File::from_raw_fd(fd) };
        }
        let metadata = handle.metadata()?;
        if metadata.is_file() && metadata.permissions().mode() & 0o077 != 0 {
            handle.set_permissions(fs::Permissions::from_mode(FILE_MODE))?;
        }
        Ok(())
    })();
    if let Err(error) = result {
        if !matches!(
            error.raw_os_error(),
            Some(libc::ELOOP | libc::ENOTDIR | libc::ENOENT)
        ) {
            warn_once(path, &error);
        }
    }
}

/// Extract a newly downloaded debug archive without trusting its stored modes.
/// Streaming each member into our own file handle avoids unzip/ditto restoring
/// public archive permissions, and treats archived symlinks as inert data.
#[cfg(unix)]
pub fn extract_zip(archive: &Path, destination: &Path) -> io::Result<()> {
    use std::process::{Command, Stdio};
    let listing = Command::new("unzip").arg("-Z1").arg(archive).output()?;
    if !listing.status.success() {
        return Err(io::Error::other("could not list debug archive"));
    }
    let members = std::str::from_utf8(&listing.stdout).map_err(io::Error::other)?;
    for member in members.lines() {
        let relative = Path::new(member);
        if relative.is_absolute()
            || relative
                .components()
                .any(|component| !matches!(component, std::path::Component::Normal(_)))
        {
            return Err(io::Error::other("debug archive member escapes destination"));
        }
        let path = destination.join(relative);
        if member.ends_with('/') {
            create_dir_all(&path)?;
        } else {
            if let Some(parent) = path.parent() {
                create_dir_all(parent)?;
            }
            let file = options().write(true).create_new(true).open(&path)?;
            let status = Command::new("unzip")
                .arg("-p")
                .arg(archive)
                .arg(member)
                .stdin(Stdio::null())
                .stdout(Stdio::from(file))
                .stderr(Stdio::null())
                .status()?;
            if !status.success() {
                return Err(io::Error::other("could not extract debug archive member"));
            }
        }
    }
    Ok(())
}

#[cfg(test)]
mod sqlite_uri_tests {
    use super::{sqlite_uri_target, SqliteUriTarget};
    use std::path::{Path, PathBuf};

    fn target(uri: &str) -> Option<SqliteUriTarget> {
        sqlite_uri_target(Path::new(uri))
    }

    #[test]
    fn plain_paths_are_not_uris() {
        assert_eq!(target("/var/aft/callgraph/x.sqlite"), None);
        assert_eq!(target(r"C:\Users\aft\x.sqlite"), None);
        assert_eq!(target(":memory:"), None);
    }

    #[test]
    fn memory_and_temporary_uris_name_no_file() {
        assert_eq!(target("file::memory:"), Some(SqliteUriTarget::NoFile));
        assert_eq!(
            target("file::memory:?cache=shared"),
            Some(SqliteUriTarget::NoFile)
        );
        assert_eq!(
            target("file:shared-db?mode=memory&cache=shared"),
            Some(SqliteUriTarget::NoFile)
        );
        assert_eq!(target("file:?mode=ro"), Some(SqliteUriTarget::NoFile));
    }

    #[test]
    fn relative_uri_decodes_percent_escapes() {
        assert_eq!(
            target("file:dir/name%20with%20space%231.sqlite?mode=ro"),
            Some(SqliteUriTarget::File(PathBuf::from(if cfg!(windows) {
                r"dir\name with space#1.sqlite"
            } else {
                "dir/name with space#1.sqlite"
            })))
        );
    }

    #[cfg(unix)]
    #[test]
    fn absolute_unix_uri_names_its_path() {
        assert_eq!(
            target("file:///private/var/aft/db%231.sqlite?mode=ro"),
            Some(SqliteUriTarget::File(PathBuf::from(
                "/private/var/aft/db#1.sqlite"
            )))
        );
        assert_eq!(
            target("file://localhost/tmp/x.sqlite"),
            Some(SqliteUriTarget::File(PathBuf::from("/tmp/x.sqlite")))
        );
    }

    #[cfg(windows)]
    #[test]
    fn windows_uris_name_drive_verbatim_and_unc_paths() {
        assert_eq!(
            target("file:///C:/Users/RUNNER~1/name%20x/db.sqlite?mode=ro"),
            Some(SqliteUriTarget::File(PathBuf::from(
                r"C:\Users\RUNNER~1\name x\db.sqlite"
            )))
        );
        // A verbatim path keeps its prefix, spelled with backslashes again.
        assert_eq!(
            target("file:////%3F/C:/Users/aft/db.sqlite?mode=ro"),
            Some(SqliteUriTarget::File(PathBuf::from(
                r"\\?\C:\Users\aft\db.sqlite"
            )))
        );
        // The call-graph store's read-only URI keeps a verbatim path's
        // backslashes percent-encoded after one leading slash.
        assert_eq!(
            target("file:///%5C%5C%3F%5CC:%5CUsers%5Caft%5Cdb%231.sqlite?mode=ro"),
            Some(SqliteUriTarget::File(PathBuf::from(
                r"\\?\C:\Users\aft\db#1.sqlite"
            )))
        );
        assert_eq!(
            target("file://server/share/db.sqlite"),
            Some(SqliteUriTarget::File(PathBuf::from(
                r"\\server\share\db.sqlite"
            )))
        );
    }
}