SPB Git

Repository Public

PathSandbox.swift 3.9 KB 79 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatSecurity/Sources/PathSandbox.swift3// Description: Confines file access to granted folders: canonicalizes and resolves symlinks before checking containment.4import Foundation56public enum PathSandboxError: LocalizedError, Sendable, Equatable {7    case noGrantedFolders8    case outsideGrantedFolders(String)9    case invalidPath(String)10    public var errorDescription: String? {11        switch self {12        case .noGrantedFolders: "No folder has been granted. Grant a folder in the agent's permissions first."13        case .outsideGrantedFolders(let p): "Access denied: \(p) is outside the granted folders."14        case .invalidPath(let p): "Invalid path: \(p)"15        }16    }17}1819public struct PathSandbox: Sendable {20    public let roots: [URL]          // canonical, symlink-resolved21    public init(roots: [URL]) { self.roots = roots.map { Self.canonical($0) } }2223    /// A realpath that also works for paths that do not exist yet: walks the components, follows every symlink (also dangling ones),24    /// applies `..` on the already-resolved prefix, and keeps the non-existing tail as written.25    static func canonical(_ url: URL) -> URL {26        var pending = Array(url.path.split(separator: "/", omittingEmptySubsequences: true).map(String.init).reversed())27        var resolved: [String] = []28        var hops = 029        while let component = pending.popLast() {30            if component == "." { continue }31            if component == ".." { _ = resolved.popLast(); continue }32            let candidate = "/" + (resolved + [component]).joined(separator: "/")33            if let destination = try? FileManager.default.destinationOfSymbolicLink(atPath: candidate) {34                hops += 135                if hops > 40 { return URL(fileURLWithPath: "/dev/null/symlink-loop") }   // never inside a granted folder36                if destination.hasPrefix("/") { resolved = [] }37                pending.append(contentsOf: destination.split(separator: "/", omittingEmptySubsequences: true).map(String.init).reversed())38                continue39            }40            resolved.append(component)41        }42        return URL(fileURLWithPath: "/" + resolved.joined(separator: "/"))43    }4445    static func isInside(_ url: URL, _ root: URL) -> Bool {46        let a = url.pathComponents, b = root.pathComponents47        return a.count >= b.count && Array(a.prefix(b.count)) == b48    }4950    /// Resolves `path` (absolute, `~`, or relative to `base` / the first root) and returns it only if it stays inside a granted root.51    public func resolve(_ path: String, relativeTo base: URL? = nil) throws -> URL {52        guard !roots.isEmpty else { throw PathSandboxError.noGrantedFolders }53        let trimmed = path.trimmingCharacters(in: .whitespacesAndNewlines)54        guard !trimmed.isEmpty, !trimmed.contains("\0") else { throw PathSandboxError.invalidPath(path) }55        let url: URL56        if trimmed.hasPrefix("/") { url = URL(fileURLWithPath: trimmed) }57        else if trimmed.hasPrefix("~") { url = URL(fileURLWithPath: (trimmed as NSString).expandingTildeInPath) }58        else { url = (base ?? roots[0]).appendingPathComponent(trimmed) }59        let canonical = Self.canonical(url)60        guard roots.contains(where: { Self.isInside(canonical, $0) }) else { throw PathSandboxError.outsideGrantedFolders(trimmed) }61        return canonical62    }6364    public func contains(_ url: URL) -> Bool {65        let c = Self.canonical(url)66        return roots.contains { Self.isInside(c, $0) }67    }6869    /// Path shown to the model: relative to its root when possible.70    public func displayPath(_ url: URL) -> String {71        let c = Self.canonical(url)72        for root in roots where Self.isInside(c, root) {73            let rel = c.pathComponents.dropFirst(root.pathComponents.count).joined(separator: "/")74            return rel.isEmpty ? "." : rel75        }76        return c.path77    }78}79
Files main
Menu

Theme