From 977914118d9b4a13e02223a76f3b570369fbbb5e Mon Sep 17 00:00:00 2001 From: Steve Sperandeo Date: Tue, 3 Nov 2026 04:36:26 -0700 Subject: [PATCH 1/2] docs(security): verify the deployment page Related to https://github.com/homer6/cpp-docs/issues/303 --- .claude/skills/cpp-security/SKILL.md | 2 +- docs/security/README.md | 2 +- docs/security/deployment.md | 227 +++++++++++++++++++++++++-- tests/security/deployment_test.cpp | 147 +++++++++++++++++ 4 files changed, 364 insertions(+), 14 deletions(-) create mode 100644 tests/security/deployment_test.cpp diff --git a/.claude/skills/cpp-security/SKILL.md b/.claude/skills/cpp-security/SKILL.md index 003b2bb..9b6905b 100644 --- a/.claude/skills/cpp-security/SKILL.md +++ b/.claude/skills/cpp-security/SKILL.md @@ -82,7 +82,7 @@ it's trusted. | Build flags, library hardening, binary protections | `hardening.md`, `language-versions.md` | `docs/guidelines/safety.md#hardening-in-practice`, `docs/guidelines/build-and-packaging.md` | | Testing for security: sanitizers, fuzzing, static analysis | `verification.md` | `docs/guidelines/tooling.md`, `docs/guidelines/testing.md` | | Dependencies, release artifacts, CI | `supply-chain.md` | | -| Deployment: privileges, isolation, logs, crash reports | `deployment.md` | | +| Deployment: dropping privileges, sandboxing parsers, crash dumps and logs without secrets, vulnerability intake | `deployment.md` | `filesystem-and-processes.md`, `cryptography-and-secrets.md` | | A team policy, release gate or review checklist | `policy.md` | | Find a Core Guidelines rule's text and our BAD/GOOD example through diff --git a/docs/security/README.md b/docs/security/README.md index 2373094..1d6a66e 100644 --- a/docs/security/README.md +++ b/docs/security/README.md @@ -72,7 +72,7 @@ each practice belongs to and what evidence shows it's in place. | [Compiler and library hardening](hardening.md) | Production hardening profiles per platform and standard library, checked in the final artifact. | ✅ verified | | [Security verification](verification.md) | Warnings, static analysis, sanitizers, fuzzing and failure tests: complementary evidence for security properties. | ✅ verified | | [Supply chain and release security](supply-chain.md) | Control build inputs, verify provenance, and keep the evidence for every release. | imported | -| [Deployment and incident readiness](deployment.md) | Least privilege, isolation of risky components, careful logging, and a process for vulnerabilities. | imported | +| [Deployment and incident readiness](deployment.md) | Least privilege, isolation of risky components, careful logging, and a process for vulnerabilities. | ✅ verified | | [Security policy, review and adoption](policy.md) | Enforceable rules, release gates, a review checklist and an adoption order. | imported | ## See also diff --git a/docs/security/deployment.md b/docs/security/deployment.md index 7015cab..830dcb4 100644 --- a/docs/security/deployment.md +++ b/docs/security/deployment.md @@ -1,22 +1,225 @@ # Deployment and incident readiness -> Least privilege, isolation of risky components, careful logging, and a process for vulnerabilities. +> Run with the least privilege the job needs, put the code that parses untrusted input in a process that can do little else, keep secrets out of logs and crash dumps, and have a way to receive and ship fixes. -> **Imported** from the research report *Security Practices for Modern C++* (2026-11-02, [#287](https://github.com/homer6/cpp-docs/issues/287)). It is being verified against primary sources and our compilers in [#303](https://github.com/homer6/cpp-docs/issues/303) (epic [#286](https://github.com/homer6/cpp-docs/issues/286)); until then, treat its claims as leads. +## Mental model -**MUST:** Run with the minimum privileges needed and restrict access to files, secrets, devices, and network destinations according to the threat model.[^8][^7] +The other pages reduce the chance of a bug; this one limits what a bug +is worth. If the parser is compromised, what can the attacker do with that +process's privileges, files, network and memory? -**SHOULD:** Isolate high-risk parsing and native-code components so that a detected memory-safety failure does not automatically compromise the most privileged process.[^7] +``` + ┌───────────── broker (privileged, small) ─────────────┐ + network ─▶ │ accept ─▶ hand bytes to worker ─▶ act on typed result │ ─▶ files, keys, DB + └───────────────────────┬──────────────────────────────┘ + ▼ IPC: bytes in, typed result out + ┌──────── worker (unprivileged, sandboxed) ────────┐ + │ parse, decode, decompress: no files, no network │ + └──────────────────────────────────────────────────┘ +``` -**MUST:** Avoid logging plaintext credentials or unnecessary sensitive input. Microsoft explicitly advises against exposing cleartext credentials in development and operational materials.[^2] +This is the [threat model](threat-modeling.md)'s "small trusted core", +applied at the process level: the code that handles attacker bytes runs +where a compromise reaches nothing valuable. -**SHOULD:** Protect diagnostic artifacts and make crashes useful for investigation without turning crash reports into an uncontrolled sensitive-data channel.[^2] +## Run with least privilege -**MUST:** Define a vulnerability intake, triage, patch, and deployment process. A secure-development program must continue after the binary has shipped.[^48][^2] +**MUST:** Start with only the privileges the program needs, and drop the rest +as soon as the work that needed them is done: bind the low port, open the +key file, then drop. Drop in the right order, supplementary groups, then the +group, then the user, because once the user ID is gone the process can no +longer change its groups. Then check that the drop can't be undone (CERT +[POS36-C](https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/rules/posix-pos/pos36-c), +[POS37-C](https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/rules/posix-pos/pos37-c)): -## Sources +```cpp +#include +#include +#include +#include -[^2]: -[^7]: -[^8]: -[^48]: +// Permanently become uid:gid. Throws instead of carrying on with privileges. +void drop_privileges(uid_t uid, gid_t gid) { + if (setgroups(0, nullptr) != 0) throw std::runtime_error("setgroups failed"); + if (setgid(gid) != 0) throw std::runtime_error("setgid failed"); + if (setuid(uid) != 0) throw std::runtime_error("setuid failed"); + if (uid != 0 && setuid(0) == 0) throw std::runtime_error("root could be regained"); +} +``` + +Every call's result is checked. A failed `setuid` that's ignored leaves the +program running as root, believing it isn't. + +**SHOULD:** Prefer not having the privilege at all: let the service manager +bind the socket and pass it in, use Linux capabilities (`CAP_NET_BIND_SERVICE`) +instead of root, run in a container as a non-root user with a read-only +filesystem. On Windows, run as a dedicated service account with a restricted +token. + +## Isolate the code that parses untrusted input + +**SHOULD:** Run high-risk parsing (file formats, media, compression, +protocol decoding) in a separate process that has no access to files, +credentials or the network, and give it bytes and take back a validated, +typed result. A memory-safety bug in the worker then can't reach the +broker's privileges. Browsers and mail clients are built this way. + +Sandboxing is per operating system: + +| Platform | Mechanism | +|---|---| +| Linux | `prctl(PR_SET_NO_NEW_PRIVS, 1)` then a seccomp filter on system calls; Landlock (5.13+) to restrict file access; namespaces | +| FreeBSD | Capsicum: `cap_enter()`, after which only descriptors already held (with their rights) work | +| OpenBSD | `pledge()` (allowed system call groups) and `unveil()` (visible paths) | +| macOS | App Sandbox entitlements | +| Windows | AppContainer or a restricted token, job objects | + +On Linux, an unprivileged process can install a seccomp filter only after +setting `no_new_privs`, which also makes set-user-ID programs it runs gain +nothing. The strictest built-in mode, `SECCOMP_MODE_STRICT`, allows only +`read`, `write`, `_exit` and `sigreturn`. That's enough for a worker that +reads a request from one pipe and writes its answer to another.[^seccomp] + +```cpp +#if defined(__linux__) +#include + +// First step of any Linux sandbox: nothing this process runs can gain privileges. +bool forbid_new_privileges() { + return prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) == 0; +} +#endif +``` + +**MUST:** Treat the worker's output as untrusted too: validate the result in +the broker ([parsing and validation](parsing-and-validation.md)), and bound +the worker's memory, CPU time and output size +([resource limits](resource-limits.md)). + +## Keep secrets out of crash dumps + +A core dump or minidump holds the process's memory, so it holds every key, +password and token the process had. If it's written to disk, collected by a +crash reporter or attached to a bug report, the secrets go with it. + +**MUST:** Decide where crash data goes and who can read it, and keep dumps +of processes that hold secrets from leaving the machine unreviewed. On +Linux: + +- `prctl(PR_SET_DUMPABLE, 0)` stops core dumps of the process, and also stops + other processes of the same user from attaching a debugger to it. One + caveat: with `fs.suid_dumpable=2`, the kernel still dumps such a process, + readable by root only. +- `madvise(addr, len, MADV_DONTDUMP)` (Linux 3.4+) leaves the pages holding + secrets out of any dump. +- `setrlimit(RLIMIT_CORE, {0, 0})` stops core *files*. The kernel doesn't + enforce it when `core_pattern` pipes dumps to a handler such as + systemd-coredump, so don't rely on it alone.[^core] + +```cpp +#if defined(__linux__) +#include +#include +#include + +bool keep_out_of_dumps(void* page_aligned, std::size_t len) { + return prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) == 0 + && madvise(page_aligned, len, MADV_DONTDUMP) == 0; +} +#endif +``` + +**SHOULD:** If you ship a crash reporter (Crashpad, Breakpad, Windows Error +Reporting), know what it collects: minidumps include thread stacks and can +include heap. Strip or exclude secret-holding memory, and treat uploaded +dumps as sensitive data with access control and retention. Keep secrets in +few places to begin with ([cryptography and secrets](cryptography-and-secrets.md#keep-secrets-out-of-code-logs-and-long-lived-memory)). + +## Keep logs safe to keep and safe to read + +**MUST:** Never log credentials, keys, session tokens or whole requests that +may carry them. Make the safe thing the default with a type that can't +print its contents: + +```cpp +#include +#include +#include +#include + +class Secret { +public: + explicit Secret(std::string value) : value_{std::move(value)} {} + const std::string& reveal() const { return value_; } // grep-able at every use +private: + std::string value_; +}; + +template <> +struct std::formatter : std::formatter { + auto format(const Secret&, std::format_context& ctx) const { + return std::formatter::format("[redacted]", ctx); + } +}; + +inline std::ostream& operator<<(std::ostream& os, const Secret&) { return os << "[redacted]"; } +``` + +**MUST:** Neutralize untrusted text before it goes into a log line. A user +name containing a newline can forge a whole log entry, and terminal escape +sequences can rewrite what an operator sees +([CWE-117](https://cwe.mitre.org/data/definitions/117.html)). Escape control +characters, or log structured fields (JSON) through an encoder that does: + +```cpp +#include +#include +#include + +// Control characters become visible escapes, so one input is one log line. +std::string log_field(std::string_view untrusted) { + std::string out; + for (unsigned char c : untrusted) { + if (c == '\n') out += "\\n"; + else if (c == '\r') out += "\\r"; + else if (c < 0x20 || c == 0x7f) out += std::format("\\x{:02x}", c); + else out += static_cast(c); + } + return out; +} +``` + +**SHOULD:** Protect the logs themselves: who can read them, how long they're +kept, and that the program can append but not rewrite them. + +## Be ready to receive and ship fixes + +**MUST:** Have a way for people to report vulnerabilities privately (a +`SECURITY.md` naming the contact; GitHub's private vulnerability reporting), +and a process behind it: acknowledge, reproduce, fix, ship and disclose. For +C++ code, "ship" means a new binary: know which versions are supported, how +users get a patched build, and how long that takes +([supply chain](supply-chain.md) keeps what you need to rebuild exactly). + +**MUST:** Turn each reported vulnerability into a regression test and look +for the same pattern elsewhere ([verification](verification.md#test-the-intended-failure-behaviour)). + +## See also + +- [Threat modeling](threat-modeling.md) (the small trusted core) · + [filesystem and processes](filesystem-and-processes.md) (launching a child safely) · + [cryptography and secrets](cryptography-and-secrets.md) · [hardening](hardening.md) +- Core Guidelines: [P.8](../guidelines/core-guidelines/philosophy.md) (don't leak resources), + [I.4](../guidelines/core-guidelines/interfaces.md) (precisely typed interfaces) +- Man pages: [seccomp(2)](https://man7.org/linux/man-pages/man2/seccomp.2.html) · + [landlock(7)](https://man7.org/linux/man-pages/man7/landlock.7.html) · + [core(5)](https://man7.org/linux/man-pages/man5/core.5.html) · + [PR_SET_DUMPABLE](https://man7.org/linux/man-pages/man2/PR_SET_DUMPABLE.2const.html) · + [madvise(2)](https://man7.org/linux/man-pages/man2/madvise.2.html) · + [capsicum(4)](https://man.freebsd.org/cgi/man.cgi?capsicum(4)) · + [pledge(2)](https://man.openbsd.org/pledge.2) +- [GitHub: privately reporting a security vulnerability](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability) +- Tests: [`tests/security/deployment_test.cpp`](../../tests/security/deployment_test.cpp) + +[^seccomp]: [seccomp(2)](https://man7.org/linux/man-pages/man2/seccomp.2.html): the system calls `SECCOMP_MODE_STRICT` permits, and the `no_new_privs` or `CAP_SYS_ADMIN` requirement for `SECCOMP_SET_MODE_FILTER`; the kernel's [no_new_privs](https://docs.kernel.org/userspace-api/no_new_privs.html) documentation. +[^core]: [core(5)](https://man7.org/linux/man-pages/man5/core.5.html): "The RLIMIT_CORE limit is not enforced for core dumps that are piped to a program"; `suid_dumpable` modes; [PR_SET_DUMPABLE](https://man7.org/linux/man-pages/man2/PR_SET_DUMPABLE.2const.html); [madvise(2)](https://man7.org/linux/man-pages/man2/madvise.2.html) `MADV_DONTDUMP` (since Linux 3.4). diff --git a/tests/security/deployment_test.cpp b/tests/security/deployment_test.cpp new file mode 100644 index 0000000..8875990 --- /dev/null +++ b/tests/security/deployment_test.cpp @@ -0,0 +1,147 @@ +// Checks claims made by docs/security/deployment.md. +#include +#include +#include +#include +#include +#include +#include +#include + +#if !defined(_WIN32) && __has_include() && __has_include() +# include +# include +# include +# include +# define CPPDOCS_POSIX_PRIVILEGES 1 // NOLINT(cppcoreguidelines-macro-usage): tested by #if +#endif +#if defined(__linux__) +# include +# include +#endif + +#include + +namespace { + +class Secret { +public: + explicit Secret(std::string value) : value_{std::move(value)} {} + const std::string& reveal() const { return value_; } +private: + std::string value_; +}; + +std::ostream& operator<<(std::ostream& os, const Secret&) { return os << "[redacted]"; } + +std::string log_field(std::string_view untrusted) { + std::string out; + for (unsigned char c : untrusted) { + if (c == '\n') out += "\\n"; + else if (c == '\r') out += "\\r"; + else if (c < 0x20 || c == 0x7f) out += std::format("\\x{:02x}", c); + else out += static_cast(c); + } + return out; +} + +#if defined(CPPDOCS_POSIX_PRIVILEGES) +void drop_privileges(uid_t uid, gid_t gid) { + if (setgroups(0, nullptr) != 0) throw std::runtime_error("setgroups failed"); + if (setgid(gid) != 0) throw std::runtime_error("setgid failed"); + if (setuid(uid) != 0) throw std::runtime_error("setuid failed"); + if (uid != 0 && setuid(0) == 0) throw std::runtime_error("root could be regained"); +} +#endif + +} // namespace + +template <> +struct std::formatter : std::formatter { + auto format(const Secret&, std::format_context& ctx) const { + return std::formatter::format("[redacted]", ctx); + } +}; + +// "Keep logs safe to keep": a Secret prints as [redacted] through std::format and +// streams; its value is reachable only through reveal(). +TEST(SecurityDeployment, SecretNeverPrints) { + const Secret token{"hunter2"}; + EXPECT_EQ(std::format("token={}", token), "token=[redacted]"); + std::ostringstream os; + os << token; + EXPECT_EQ(os.str(), "[redacted]"); + EXPECT_EQ(token.reveal(), "hunter2"); +} + +// "Neutralize untrusted text": a newline can't start a forged log entry, and +// terminal escapes become visible. +TEST(SecurityDeployment, LogFieldIsOneLine) { + const std::string forged = log_field("alice\nINFO admin logged in"); + EXPECT_EQ(forged, "alice\\nINFO admin logged in"); + EXPECT_EQ(forged.find('\n'), std::string::npos); + EXPECT_EQ(log_field("\x1b[2J"), "\\x1b[2J"); + EXPECT_EQ(log_field("caf\xc3\xa9"), "caf\xc3\xa9"); // UTF-8 passes through +} + +// "Run with least privilege": an unprivileged process can't drop to another +// identity, and drop_privileges reports that instead of carrying on. +TEST(SecurityDeployment, FailedDropThrows) { +#if defined(CPPDOCS_POSIX_PRIVILEGES) + if (geteuid() == 0) GTEST_SKIP() << "running as root: the drop would succeed and change this process"; + EXPECT_THROW(drop_privileges(getuid(), getgid()), std::runtime_error); // setgroups needs privilege +#else + GTEST_SKIP() << "POSIX privileges only (no /)"; +#endif +} + +// "Keep secrets out of crash dumps": the core-file limit can be lowered to 0 by +// an unprivileged process. +TEST(SecurityDeployment, CoreLimitCanBeLowered) { +#if defined(CPPDOCS_POSIX_PRIVILEGES) + rlimit saved{}; + ASSERT_EQ(getrlimit(RLIMIT_CORE, &saved), 0); + rlimit none = saved; + none.rlim_cur = 0; // soft limit only, so it can be restored + ASSERT_EQ(setrlimit(RLIMIT_CORE, &none), 0); + rlimit now{}; + ASSERT_EQ(getrlimit(RLIMIT_CORE, &now), 0); + EXPECT_EQ(now.rlim_cur, rlim_t{0}); + EXPECT_EQ(setrlimit(RLIMIT_CORE, &saved), 0); +#else + GTEST_SKIP() << "POSIX resource limits only"; +#endif +} + +// "Keep secrets out of crash dumps": on Linux a process can mark itself not +// dumpable and exclude pages from dumps. +TEST(SecurityDeployment, LinuxNotDumpableAndDontDump) { +#if defined(__linux__) + ASSERT_EQ(prctl(PR_SET_DUMPABLE, 0, 0, 0, 0), 0); + EXPECT_EQ(prctl(PR_GET_DUMPABLE, 0, 0, 0, 0), 0); + EXPECT_EQ(prctl(PR_SET_DUMPABLE, 1, 0, 0, 0), 0); // restore: sanitizers' leak checks attach at exit + const long page = sysconf(_SC_PAGESIZE); + void* p = mmap(nullptr, static_cast(page), PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + ASSERT_NE(p, MAP_FAILED); + EXPECT_EQ(madvise(p, static_cast(page), MADV_DONTDUMP), 0); + munmap(p, static_cast(page)); +#else + GTEST_SKIP() << "Linux only (prctl, MADV_DONTDUMP)"; +#endif +} + +// "Isolate the code that parses untrusted input": setting no_new_privs works +// unprivileged, and can't be unset. +TEST(SecurityDeployment, LinuxNoNewPrivs) { +#if defined(__linux__) + // Run in a child so the test process keeps its ability to gain privileges. + EXPECT_EXIT({ + if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0) std::_Exit(1); + if (prctl(PR_GET_NO_NEW_PRIVS, 0, 0, 0, 0) != 1) std::_Exit(2); + if (prctl(PR_SET_NO_NEW_PRIVS, 0, 0, 0, 0) == 0) std::_Exit(3); // one-way + std::_Exit(0); + }, testing::ExitedWithCode(0), ""); +#else + GTEST_SKIP() << "Linux only (PR_SET_NO_NEW_PRIVS)"; +#endif +} From 3089886fcafcd6825abb60089fa36d9682eecd98 Mon Sep 17 00:00:00 2001 From: Steve Sperandeo Date: Tue, 3 Nov 2026 07:08:33 -0700 Subject: [PATCH 2/2] docs(security): deployment page adds restart and run-time secrets Under the owner's rule that guidance beyond C++ belongs when it changes how the C++ is written: stop safely and restart cleanly (supervisor with a rate limit, write-to-temp-then-rename so a crash never leaves half a file, with a tested write_atomically), and get secrets at run time (a secret store, never argv, prefer files to environment variables, read once, plan for rotation). Related to https://github.com/homer6/cpp-docs/issues/303 --- docs/security/deployment.md | 58 ++++++++++++++++++++++++++++++ tests/security/deployment_test.cpp | 37 +++++++++++++++++++ 2 files changed, 95 insertions(+) diff --git a/docs/security/deployment.md b/docs/security/deployment.md index 830dcb4..d88eb0e 100644 --- a/docs/security/deployment.md +++ b/docs/security/deployment.md @@ -96,6 +96,64 @@ the broker ([parsing and validation](parsing-and-validation.md)), and bound the worker's memory, CPU time and output size ([resource limits](resource-limits.md)). +## Stop safely, restart cleanly + +The pages tell code to stop on a broken invariant rather than continue +([error handling](error-handling.md#stop-on-broken-invariants)), and +hardening and contract checks stop the process the same way. That is only +safe if something restarts it and nothing is left half-done. + +**SHOULD:** Run the program under a supervisor that restarts it: a service +manager (systemd `Restart=on-failure`, launchd, a Windows service's recovery +actions) or an orchestrator. Limit the restart rate, so input that crashes the +worker every time doesn't keep the machine busy restarting it. + +**MUST:** Write state so a crash at any moment leaves either the old version +or the new one. Write to a temporary file, then rename it over the target: +on POSIX file systems `rename` replaces the target atomically. For +durability across a power loss, also `fsync` the file and its directory +(POSIX only; the standard library has no portable call). + +```cpp +#include +#include +#include +#include + +// A crash leaves the old file or the new one, never half of each. +bool write_atomically(const std::filesystem::path& target, std::string_view data) { + std::filesystem::path tmp = target; + tmp += ".tmp"; + { + std::ofstream out{tmp, std::ios::binary | std::ios::trunc}; + if (!out.write(data.data(), static_cast(data.size()))) return false; + out.flush(); + if (!out) return false; + } + std::error_code ec; + std::filesystem::rename(tmp, target, ec); // replaces target + return !ec; +} +``` + +## Get secrets at run time + +**MUST:** Keep secrets out of the binary, the repository and the command line, +and load them when the program starts. Use a secret store (a cloud secret +manager or KMS, HashiCorp Vault, systemd's `LoadCredential=`, the OS keychain +or DPAPI on Windows), or a file only the service account can read. This shapes +the C++: +- **Arguments:** never pass a secret in `argv`. On Linux any local user can + read a process's arguments (`ps`, `/proc//cmdline`). +- **Environment variables:** prefer files or a credentials API. Every child + process inherits the environment, and the same user and root can read it + through `/proc//environ`. +- **Storage:** read each secret once, into the one type that holds it + ([cryptography and secrets](cryptography-and-secrets.md#keep-secrets-out-of-code-logs-and-long-lived-memory)), + and erase buffers you no longer need. +- **Rotation:** plan for it. The program reloads a rotated secret without a + rebuild, which means no secret is a compile-time constant. + ## Keep secrets out of crash dumps A core dump or minidump holds the process's memory, so it holds every key, diff --git a/tests/security/deployment_test.cpp b/tests/security/deployment_test.cpp index 8875990..f21cb2e 100644 --- a/tests/security/deployment_test.cpp +++ b/tests/security/deployment_test.cpp @@ -1,11 +1,15 @@ // Checks claims made by docs/security/deployment.md. #include #include +#include #include +#include +#include #include #include #include #include +#include #include #if !defined(_WIN32) && __has_include() && __has_include() @@ -45,6 +49,25 @@ std::string log_field(std::string_view untrusted) { return out; } +bool write_atomically(const std::filesystem::path& target, std::string_view data) { + std::filesystem::path tmp = target; + tmp += ".tmp"; + { + std::ofstream out{tmp, std::ios::binary | std::ios::trunc}; + if (!out.write(data.data(), static_cast(data.size()))) return false; + out.flush(); + if (!out) return false; + } + std::error_code ec; + std::filesystem::rename(tmp, target, ec); + return !ec; +} + +std::string slurp(const std::filesystem::path& p) { + std::ifstream in{p, std::ios::binary}; + return {std::istreambuf_iterator{in}, std::istreambuf_iterator{}}; +} + #if defined(CPPDOCS_POSIX_PRIVILEGES) void drop_privileges(uid_t uid, gid_t gid) { if (setgroups(0, nullptr) != 0) throw std::runtime_error("setgroups failed"); @@ -145,3 +168,17 @@ TEST(SecurityDeployment, LinuxNoNewPrivs) { GTEST_SKIP() << "Linux only (PR_SET_NO_NEW_PRIVS)"; #endif } + +// "Stop safely, restart cleanly": writing to a temporary file and renaming it +// replaces the target in one step, and leaves no temporary file behind. +TEST(SecurityDeployment, AtomicWriteReplacesTarget) { + const auto dir = std::filesystem::temp_directory_path() / "cppdocs-deployment-test"; + std::filesystem::create_directories(dir); + const auto target = dir / "state.txt"; + ASSERT_TRUE(write_atomically(target, "version 1")); + EXPECT_EQ(slurp(target), "version 1"); + ASSERT_TRUE(write_atomically(target, "version 2")); + EXPECT_EQ(slurp(target), "version 2"); + EXPECT_FALSE(std::filesystem::exists(dir / "state.txt.tmp")); + std::filesystem::remove_all(dir); +}