From f5955e352e033d3871f471c4c7776da5a94806a1 Mon Sep 17 00:00:00 2001 From: Christian Parpart Date: Mon, 30 Nov 2026 11:25:33 +0100 Subject: [PATCH] fix(fs): move a staged owner-only directory without a placeholder A staged CreationAccess::OwnerOnly directory (macOS, FreeBSD) reached its final name by renameat over an empty placeholder made under that name. A concurrent opener of the name could hold the placeholder, which the rename then unlinked, so nothing could be created in what it opened (NoEntry). Isoline's racing key and cache creators hit it on macOS. The directory now moves with a rename that refuses an existing target (renameNoReplace: renameatx_np(RENAME_EXCL) on Apple, renameat2's RENAME_NOREPLACE on Linux, where the staged tests run), so the name names nothing until it names the finished directory. Where the system or file system has none (FreeBSD), the placeholder remains, documented. The rename is injected into OwnerOnlyCreator so the fallback stays tested. Signed-off-by: Christian Parpart --- .agent/reference/provenance.md | 4 +- CHANGELOG.md | 8 ++ src/core/fs/darwin/PosixSystem.cpp | 9 +- src/core/fs/posix/OwnerOnlyCreation.cpp | 46 ++++++++-- src/core/fs/posix/OwnerOnlyCreation.hpp | 18 +++- src/core/fs/posix/OwnerOnly_test.cpp | 114 ++++++++++++++++++++++-- src/core/fs/posix/PosixSystem.cpp | 19 +++- src/core/fs/posix/PosixSystem.hpp | 11 +++ 8 files changed, 212 insertions(+), 17 deletions(-) diff --git a/.agent/reference/provenance.md b/.agent/reference/provenance.md index 037e1a3b..38752ecb 100644 --- a/.agent/reference/provenance.md +++ b/.agent/reference/provenance.md @@ -189,7 +189,7 @@ others in notes. | `src/core/fs/bsd/Relation_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): a nullfs mount beneath a grant that shows the key, FreeBSD | | `src/core/fs/darwin/AccessFacts.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): macOS's access reader, extended ACLs | | `src/core/fs/darwin/InheritableAcl_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `chmod +a`, macOS | -| `src/core/fs/darwin/PosixSystem.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): Apple: `st_atimespec`, `F_RDADVISE`, `F_FULLFSYNC`, `EACCES` for `O_CREAT` on a directory | +| `src/core/fs/darwin/PosixSystem.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): Apple: `st_atimespec`, `F_RDADVISE`, `F_FULLFSYNC`, `EACCES` for `O_CREAT` on a directory; `renameatx_np(RENAME_EXCL)` | | `src/core/fs/detail/Ancestry.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `decideRelation`, shared by the walkers and the model | | `src/core/fs/detail/Ancestry.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): `ObjectIdentity`, `decideRelation`, `nativeRelation` | | `src/core/fs/detail/DirectoryStream.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | @@ -253,7 +253,7 @@ others in notes. | `src/core/fs/posix/PosixPathWalk.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the component walker over held directory descriptors | | `src/core/fs/posix/PosixPathWalk.hpp` | origin: core-cpp | - | - | 0.24.0 (P13) | | `src/core/fs/posix/PosixPathWalk_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the walker against a swap at a chosen step | -| `src/core/fs/posix/PosixSystem.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): Linux, the BSDs and any POSIX system but Apple's; `#ifdef` inside the data picks `O_DSYNC` and `O_RSYNC` where a system lacks them | +| `src/core/fs/posix/PosixSystem.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): Linux, the BSDs and any POSIX system but Apple's; `#ifdef` inside the data picks `O_DSYNC` and `O_RSYNC` where a system lacks them; `#ifdef __linux__` picks `renameat2(RENAME_NOREPLACE)` for `renameNoReplace`, which the BSDs lack | | `src/core/fs/posix/PosixSystem.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): the calls POSIX systems differ in | | `src/core/fs/testing/InMemoryDescriptorFileSystem.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | | `src/core/fs/testing/InMemoryDescriptorFileSystem.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): the in-memory model, resolving and enforcing through the code the native one uses | diff --git a/CHANGELOG.md b/CHANGELOG.md index d5ae30e4..273f13d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,14 @@ workflow refuses one without a section here. ## [Unreleased] +### Fixed + +- **An owner-only directory created on macOS is never replaced under a concurrent opener.** A staged + `CreationAccess::OwnerOnly` directory reached its final name by `renameat` over an empty placeholder, so a second + process or thread that opened the name in between held the placeholder, which the rename then unlinked: nothing + could be created in it (`NoEntry`). macOS now moves it with `renameatx_np(RENAME_EXCL)`, which needs no + placeholder. FreeBSD has no such rename and keeps the placeholder, with that window. + ## [0.25.0] - 2026-11-30 ### Breaking diff --git a/src/core/fs/darwin/PosixSystem.cpp b/src/core/fs/darwin/PosixSystem.cpp index 3a4623df..3d967d62 100644 --- a/src/core/fs/darwin/PosixSystem.cpp +++ b/src/core/fs/darwin/PosixSystem.cpp @@ -2,7 +2,8 @@ // // The descriptor calls of Apple's systems: the `st_atimespec` family of times; `F_RDADVISE` for // read-ahead, the one advice macOS can act on (it has no `posix_fadvise`); and `F_FULLFSYNC`, without -// which macOS's `fsync` leaves the data in the drive's cache. macOS has no `O_RSYNC`. +// which macOS's `fsync` leaves the data in the drive's cache; `renameatx_np(RENAME_EXCL)`, the rename that +// refuses an existing target. macOS has no `O_RSYNC`. #include #include @@ -16,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -162,4 +164,9 @@ FsError openFailure(int directory, std::string const& name, int flags, int error return fsErrorFromSystemCode(error, "openat"); } +int renameNoReplace(int fromDirectory, char const* from, int toDirectory, char const* to) noexcept +{ + return ::renameatx_np(fromDirectory, from, toDirectory, to, RENAME_EXCL); +} + } // namespace core::fs::detail diff --git a/src/core/fs/posix/OwnerOnlyCreation.cpp b/src/core/fs/posix/OwnerOnlyCreation.cpp index afe4541c..538e4e27 100644 --- a/src/core/fs/posix/OwnerOnlyCreation.cpp +++ b/src/core/fs/posix/OwnerOnlyCreation.cpp @@ -10,9 +10,14 @@ // 2. the object is created inside it, where nothing can be inherited, and stripped and verified // too; // 3. it is moved to its final name: a file by linkat, which fails where the name exists, as -// O_EXCL does; a directory by renameat over an empty placeholder made with the final name by -// mkdirat, which is what fails where the name exists, and which is stripped and verified as -// well, so that what it inherited lets nobody leave an entry in it under the final name; +// O_EXCL does; a directory by a rename that refuses an existing target (renameNoReplace), so +// that the final name names nothing until it names the finished directory. Only where the +// system has no such rename (FreeBSD) is it renamed over an empty placeholder made with the +// final name by mkdirat, which is what fails where the name exists there, and which is +// stripped and verified as well, so that what it inherited lets nobody leave an entry in it +// under the final name. A concurrent opener of the name can hold that placeholder, which the +// rename then unlinks: on such a system a directory opened while another flow creates it may +// be one no longer linked anywhere; // 4. the staging directory is removed. // // A staging name is an HMAC of a counter under a key drawn once per file system, so nobody can make @@ -100,6 +105,13 @@ namespace .context = "the new object is not owner-only" } }; } + /// @return Whether a renameNoReplace() failed with @p error because the system or the file system + /// has no rename that refuses an existing target, rather than for the move itself. + [[nodiscard]] bool lacksNoReplaceRename(int error) noexcept + { + return error == ENOTSUP || error == EINVAL || error == ENOSYS; + } + /// Opens the directory just made as @p name beneath @p directory and holds it to owner-only. [[nodiscard]] FsResult holdDirectory(OwnerOnlyCreator const& creator, int directory, @@ -223,6 +235,19 @@ namespace removeStaging(directory, *staging, Leftover::Directory); return held; } + // Moved in one step where the system can refuse an existing target: the name names nothing + // until it names the finished directory, so whoever opens it meanwhile finds nothing or this. + if (creator.moveWithoutReplacing(staging->handle.get(), StagedName, directory, name.c_str()) == 0) + { + removeStaging(directory, *staging, Leftover::Nothing); + return {}; + } + if (!lacksNoReplaceRename(errno)) + { + auto failed = errnoError("renameNoReplace"); + removeStaging(directory, *staging, Leftover::Directory); + return failed; + } // The placeholder is what refuses an existing name; the rename replaces it, empty, at once. // It is held to owner-only first: what it inherited could otherwise let another user leave // an entry in it, which would fail the rename and keep their entry under the final name. @@ -256,8 +281,11 @@ int systemStatHandle(int handle, struct ::stat* status) return ::fstat(handle, status); } -OwnerOnlyCreator::OwnerOnlyCreator(IRandom& random, OwnerOnlyCreation how, StatHandle statHandle): - _how { how }, _statHandle { std::move(statHandle) } +OwnerOnlyCreator::OwnerOnlyCreator(IRandom& random, + OwnerOnlyCreation how, + StatHandle statHandle, + RenameNoReplace renameNoReplace): + _how { how }, _statHandle { std::move(statHandle) }, _renameNoReplace { std::move(renameNoReplace) } { random.fill(_stagingKey); } @@ -307,4 +335,12 @@ FsResult OwnerOnlyCreator::createDirectory(int directory, std::string cons : createDirectoryDirect(*this, directory, name); } +int OwnerOnlyCreator::moveWithoutReplacing(int fromDirectory, + char const* from, + int toDirectory, + char const* to) const +{ + return _renameNoReplace(fromDirectory, from, toDirectory, to); +} + } // namespace core::fs::detail diff --git a/src/core/fs/posix/OwnerOnlyCreation.hpp b/src/core/fs/posix/OwnerOnlyCreation.hpp index 242f717c..80c7a20a 100644 --- a/src/core/fs/posix/OwnerOnlyCreation.hpp +++ b/src/core/fs/posix/OwnerOnlyCreation.hpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include @@ -49,6 +50,11 @@ using StatHandle = std::function; /// @return 0, or -1 with `errno` set. [[nodiscard]] CORE_FS_API int systemStatHandle(int handle, struct ::stat* status); +/// Moves a finished directory to its final name, refusing an existing target (@c renameNoReplace), +/// or a test's stand-in for a system or file system that has no such rename. +using RenameNoReplace = + std::function; + /// Creates files and directories beneath a held directory that no other user can reach at any /// moment, as @c OwnerOnlyCreation says. One per file system, fixed at construction; safe to use /// from every thread at once. Where any step fails, what was made is removed through the directory. @@ -59,9 +65,11 @@ class CORE_FS_API OwnerOnlyCreator /// staging name before it is made, so no name made in advance can stand in the way. /// @param how Where an object is created. /// @param statHandle How a new object's status is read back. + /// @param renameNoReplace How a staged directory is moved to its final name. OwnerOnlyCreator(IRandom& random, OwnerOnlyCreation how, - StatHandle statHandle = StatHandle { &systemStatHandle }); + StatHandle statHandle = StatHandle { &systemStatHandle }, + RenameNoReplace renameNoReplace = RenameNoReplace { &detail::renameNoReplace }); /// Creates the regular file @p name beneath @p directory, mode 0600. /// @param directory The held parent. @@ -90,10 +98,18 @@ class CORE_FS_API OwnerOnlyCreator /// refused the stripping. [[nodiscard]] FsResult holdOwnerOnly(int handle, ::mode_t mode) const; + /// Moves a staged directory to its final name through the injected @c RenameNoReplace. + /// @return 0; -1 with `errno` set, as @c renameNoReplace says. + [[nodiscard]] int moveWithoutReplacing(int fromDirectory, + char const* from, + int toDirectory, + char const* to) const; + private: std::array _stagingKey {}; OwnerOnlyCreation _how; StatHandle _statHandle; + RenameNoReplace _renameNoReplace; mutable std::atomic _stagingCounter { 0 }; ///< Each call's own staging name. }; diff --git a/src/core/fs/posix/OwnerOnly_test.cpp b/src/core/fs/posix/OwnerOnly_test.cpp index 65427619..e443ce1a 100644 --- a/src/core/fs/posix/OwnerOnly_test.cpp +++ b/src/core/fs/posix/OwnerOnly_test.cpp @@ -22,6 +22,7 @@ #include #include +#include #include #include #include @@ -30,6 +31,7 @@ #include #include #include +#include #include #include @@ -255,10 +257,21 @@ constexpr auto StagingSeed = std::uint64_t { 18 }; [[nodiscard]] OwnerOnlyCreator creatorOf( OwnerOnlyCreation how, std::uint64_t seed = StagingSeed, - core::fs::detail::StatHandle statHandle = &core::fs::detail::systemStatHandle) + core::fs::detail::StatHandle statHandle = &core::fs::detail::systemStatHandle, + core::fs::detail::RenameNoReplace renameNoReplace = &core::fs::detail::renameNoReplace) { auto random = FixedRandom { seed }; - return OwnerOnlyCreator { random, how, std::move(statHandle) }; + return OwnerOnlyCreator { random, how, std::move(statHandle), std::move(renameNoReplace) }; +} + +/// The rename of a system without one that refuses an existing target, as FreeBSD's. +int lackingRenameNoReplace(int /*fromDirectory*/, + char const* /*from*/, + int /*toDirectory*/, + char const* /*to*/) +{ + errno = ENOTSUP; + return -1; } /// A stat of a file system that ignores the mode it was given, as vfat or exfat under `fmask` and @@ -289,6 +302,9 @@ struct HeldDirectory } }; +/// How many times a creation and an opener of its name race, each over a name of its own. +constexpr auto RacingRounds = 256; + constexpr auto CreateFlags = O_CREAT | O_EXCL | O_RDWR | O_NOFOLLOW | O_CLOEXEC; [[nodiscard]] AccessScope scopeOf(int handle) @@ -397,15 +413,19 @@ TEST_CASE("posix: a creation the file system will not hold owner-only leaves not TEST_CASE("posix: a placeholder the file system will not hold owner-only is removed", "[fs][native][access]") { - // A staged directory reads back its staging directory, itself, then the placeholder under the - // final name: only the third is wider than it was made. + // Where the system has no rename that refuses a target, a staged directory reads back its staging + // directory, itself, then the placeholder under the final name: only the third is wider than it + // was made. auto const held = HeldDirectory {}; auto reads = 0; - auto const creator = - creatorOf(OwnerOnlyCreation::Staged, StagingSeed, [&reads](int handle, struct ::stat* status) { + auto const creator = creatorOf( + OwnerOnlyCreation::Staged, + StagingSeed, + [&reads](int handle, struct ::stat* status) { ++reads; return reads == 3 ? modeIgnoringStat(handle, status) : ::fstat(handle, status); - }); + }, + &lackingRenameNoReplace); auto const directory = creator.createDirectory(held.handle.get(), "keys"); REQUIRE_FALSE(directory.has_value()); CHECK(directory.error().code == FsErrorCode::NotPermitted); @@ -413,6 +433,86 @@ TEST_CASE("posix: a placeholder the file system will not hold owner-only is remo CHECK(held.names().empty()); } +TEST_CASE( + "posix: a staged directory goes over a placeholder where the system has no rename refusing a target", + "[fs][native][access]") +{ + auto const held = HeldDirectory {}; + std::filesystem::create_directory(held.directory.path() / "taken"); + auto const creator = creatorOf( + OwnerOnlyCreation::Staged, StagingSeed, &core::fs::detail::systemStatHandle, &lackingRenameNoReplace); + REQUIRE(creator.createDirectory(held.handle.get(), "keys").has_value()); + CHECK(modeOf(held.directory.path() / "keys") == 0700); + auto const taken = creator.createDirectory(held.handle.get(), "taken"); + REQUIRE_FALSE(taken.has_value()); + CHECK(taken.error().code == FsErrorCode::Exist); + CHECK(held.names() == std::vector { "keys", "taken" }); +} + +TEST_CASE("posix: a staged directory whose move fails for itself leaves nothing behind", + "[fs][native][access]") +{ + auto const held = HeldDirectory {}; + auto const creator = creatorOf(OwnerOnlyCreation::Staged, + StagingSeed, + &core::fs::detail::systemStatHandle, + [](int, char const*, int, char const*) { + errno = EACCES; + return -1; + }); + auto const directory = creator.createDirectory(held.handle.get(), "keys"); + REQUIRE_FALSE(directory.has_value()); + CHECK(directory.error().code == FsErrorCode::Access); + CHECK(held.names().empty()); +} + +TEST_CASE("posix: a directory opened while a staged creation runs is the one left under its name", + "[fs][native][access][threading]") +{ + // Whoever opens the name while the creation runs either finds nothing yet or the directory the + // creation leaves there: never an object the creation replaces afterwards, whose handle would + // name a directory no longer linked anywhere, in which nothing can be created. + auto const held = HeldDirectory {}; + // Moving a name that does not exist tells a system with the rename (ENOENT) from one without. + if (core::fs::detail::renameNoReplace(held.handle.get(), "absent", held.handle.get(), "target") != 0 + && errno != ENOENT) + SKIP("no rename refusing a target here (FreeBSD): the directory goes over a placeholder, with that " + "window"); + auto const creator = creatorOf(OwnerOnlyCreation::Staged); + for (auto const round: std::views::iota(0, RacingRounds)) + { + auto const name = "keys-" + std::to_string(round); + auto started = std::atomic { false }; + auto opened = core::fs::detail::UniqueHandle { core::platform::InvalidHandle }; + auto openError = 0; + auto opener = std::thread { [&] { + while (!started.load()) + std::this_thread::yield(); + while (true) + { + opened = core::fs::detail::UniqueHandle { ::openat( + held.handle.get(), name.c_str(), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC) }; + if (opened.get() >= 0 || errno != ENOENT) + { + openError = opened.get() >= 0 ? 0 : errno; + return; + } + } + } }; + started.store(true); + auto const created = creator.createDirectory(held.handle.get(), name); + opener.join(); + INFO("round " << round); + REQUIRE(created.has_value()); + REQUIRE(openError == 0); + struct ::stat byHandle {}; + struct ::stat byName {}; + REQUIRE(::fstat(opened.get(), &byHandle) == 0); + REQUIRE(::lstat((held.directory.path() / name).c_str(), &byName) == 0); + CHECK(byHandle.st_ino == byName.st_ino); + } +} + TEST_CASE("posix: a staged creation under an inheritable ACL is owner-only", "[fs][native][access]") { auto const held = HeldDirectory {}; diff --git a/src/core/fs/posix/PosixSystem.cpp b/src/core/fs/posix/PosixSystem.cpp index 0f7be5bb..6f755558 100644 --- a/src/core/fs/posix/PosixSystem.cpp +++ b/src/core/fs/posix/PosixSystem.cpp @@ -2,7 +2,8 @@ // // The descriptor calls of Linux, the BSDs and any POSIX system but Apple's: the `st_atim` family of // times, `posix_fadvise`, `fdatasync` and `fsync`. A write-integrity mode the system lacks (FreeBSD -// has no `O_RSYNC`) is a row whose flag is 0, chosen by the macro test inside the data. +// has no `O_RSYNC`) is a row whose flag is 0, chosen by the macro test inside the data. A rename that +// refuses an existing target is Linux's `renameat2`; the others have none. #include #include @@ -13,7 +14,9 @@ #include #include +#include #include +#include #include #include #include @@ -131,4 +134,18 @@ FsError openFailure(int, std::string const&, int flags, int error) return fsErrorFromSystemCode(error, "openat"); } +int renameNoReplace([[maybe_unused]] int fromDirectory, + [[maybe_unused]] char const* from, + [[maybe_unused]] int toDirectory, + [[maybe_unused]] char const* to) noexcept +{ +#ifdef __linux__ + return ::renameat2(fromDirectory, from, toDirectory, to, RENAME_NOREPLACE); +#else + // FreeBSD and the other systems this file serves have no rename that refuses an existing target. + errno = ENOTSUP; + return -1; +#endif +} + } // namespace core::fs::detail diff --git a/src/core/fs/posix/PosixSystem.hpp b/src/core/fs/posix/PosixSystem.hpp index 85c8f753..81fc0312 100644 --- a/src/core/fs/posix/PosixSystem.hpp +++ b/src/core/fs/posix/PosixSystem.hpp @@ -170,4 +170,15 @@ struct StatTimes /// @return Nothing, or what refused the change. [[nodiscard]] CORE_FS_API FsResult stripInheritedAcl(int handle, ::mode_t mode); +/// Moves @p from beneath @p fromDirectory to @p to beneath @p toDirectory, refusing an existing +/// target where the system can: Linux's `renameat2(RENAME_NOREPLACE)`, Apple's +/// `renameatx_np(RENAME_EXCL)`. Unlike a plain `renameat`, it never replaces an empty directory, so +/// nothing stands under @p to before the move. +/// @return 0; -1 with `errno` set: `EEXIST` where @p to exists, `ENOTSUP` or `EINVAL` where the +/// system or the file system has no such rename (FreeBSD, an old kernel), and nothing moved. +[[nodiscard]] CORE_FS_API int renameNoReplace(int fromDirectory, + char const* from, + int toDirectory, + char const* to) noexcept; + } // namespace core::fs::detail