Merge branch 'worktree-agent-a8ca0a146d4c559f4'

This commit is contained in:
2026-10-25 20:28:07 +01:00
+51 -2
View File
@@ -6,8 +6,49 @@
#include <sys/stat.h>
#include <unistd.h>
#include <vector>
namespace molo::runtime::static_ {
namespace {
// openat() with O_NOFOLLOW on the full relative path only blocks the
// kernel from dereferencing a symlink at the FINAL component; an earlier
// component that is a symlink is still followed transparently while the
// rest of the path resolves, escaping root_fd_'s jail. Walk the path one
// component at a time instead, applying O_NOFOLLOW at every single level
// (every intermediate directory, then the final entry), so a symlink
// anywhere in the path is rejected, not only at the end. Returns a valid
// fd, or -1 (errno set) the moment any component fails to open this way.
int OpenNoFollowWalk(int root_fd, const std::string& path) {
std::vector<std::string> segs;
std::size_t i = 0;
while (i <= path.size()) {
std::size_t slash = path.find('/', i);
if (slash == std::string::npos) slash = path.size();
if (slash == i) return -1; // empty segment: "//" or a trailing "/"
segs.emplace_back(path, i, slash - i);
i = slash + 1;
}
if (segs.empty()) return -1;
int dir_fd = root_fd;
bool owns_dir_fd = false;
for (std::size_t k = 0; k + 1 < segs.size(); ++k) {
int next = openat(dir_fd, segs[k].c_str(),
O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
if (owns_dir_fd) close(dir_fd);
if (next < 0) return -1;
dir_fd = next;
owns_dir_fd = true;
}
int fd = openat(dir_fd, segs.back().c_str(),
O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
if (owns_dir_fd) close(dir_fd);
return fd;
}
} // namespace
DiskProvider::DiskProvider(std::string root, bool follow_symlinks,
bool allow_dotfiles)
: root_(std::move(root)),
@@ -37,8 +78,16 @@ std::optional<Asset> DiskProvider::open(std::string_view rel) {
i = slash + 1;
}
}
int fd = openat(root_fd_, path.c_str(),
O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
int fd;
if (follow_symlinks_) {
// Unchanged: single openat, with the realpath containment fallback
// below for when a symlink (anywhere in the path) makes it fail.
fd = openat(root_fd_, path.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
} else {
// Strict default: reject a symlink in ANY component, not just the
// final one.
fd = OpenNoFollowWalk(root_fd_, path);
}
if (fd < 0 && follow_symlinks_) {
// Resolve through realpath and verify containment (v1: small TOCTOU
// window, documented; strict deployments keep follow_symlinks off).