refactor: add prefix param to uniqueRandomPath, use in GRPCServerTLS_test

Agent-Logs-Url: https://github.com/XRPLF/rippled/sessions/a8d8f682-0faf-4cb5-a330-39dc6fb7408f

Co-authored-by: mathbunnyru <12270691+mathbunnyru@users.noreply.github.com>
This commit is contained in:
copilot-swe-agent[bot]
2026-05-06 10:04:14 +00:00
committed by GitHub
parent 5147825d61
commit 4714160052
2 changed files with 11 additions and 31 deletions

View File

@@ -10,20 +10,25 @@
namespace beast {
/** Generate a unique, non-existing path under @p base with a random hex suffix.
/** Generate a unique, non-existing path under @p base with an optional @p prefix
and a random hex suffix.
Attempts up to @p maxAttempts paths. Throws `std::runtime_error` if a
unique path cannot be found or if the filesystem returns an error while
checking for existence.
*/
inline std::filesystem::path
uniqueRandomPath(std::filesystem::path const& base, std::size_t maxAttempts = 100)
uniqueRandomPath(
std::filesystem::path const& base,
std::size_t maxAttempts = 100,
std::string const& prefix = "")
{
std::random_device rd;
for (std::size_t attempt = 0; attempt < maxAttempts; ++attempt)
{
std::ostringstream oss;
oss << std::hex << std::setfill('0') << std::setw(8) << rd() << std::setw(8) << rd();
oss << prefix << std::hex << std::setfill('0') << std::setw(8) << rd() << std::setw(8)
<< rd();
auto candidate = base / oss.str();
std::error_code ec;
bool const exists = std::filesystem::exists(candidate, ec);

View File

@@ -4,6 +4,7 @@
#include <xrpld/core/ConfigSections.h>
#include <xrpl/beast/unit_test/suite.h>
#include <xrpl/beast/utility/temp_dir.h>
#include <xrpl/proto/org/xrpl/rpc/v1/get_ledger.pb.h>
#include <xrpl/proto/org/xrpl/rpc/v1/xrp_ledger.grpc.pb.h>
@@ -14,14 +15,10 @@
#include <grpcpp/support/status.h>
#include <chrono>
#include <cstddef>
#include <filesystem>
#include <fstream>
#include <iomanip>
#include <ios>
#include <memory>
#include <random>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
@@ -258,30 +255,8 @@ public:
TemporaryTLSCertificates()
{
auto tmpDir = std::filesystem::temp_directory_path();
std::random_device rd;
constexpr std::size_t kMAX_ATTEMPTS = 100;
for (std::size_t attempt = 0; attempt < kMAX_ATTEMPTS; ++attempt)
{
std::ostringstream oss;
oss << kCERTS_DIR_PREFIX << std::hex << std::setfill('0') << std::setw(8) << rd();
tempDir_ = tmpDir / oss.str();
std::error_code ec;
bool const exists = std::filesystem::exists(tempDir_, ec);
if (ec)
{
throw std::runtime_error(
"Unable to check path '" + tempDir_.string() + "': " + ec.message());
}
if (!exists)
break;
tempDir_.clear();
}
if (tempDir_.empty())
{
throw std::runtime_error(
"Unable to generate a unique temporary TLS certificate directory");
}
tempDir_ = beast::uniqueRandomPath(
std::filesystem::temp_directory_path(), 100, std::string(kCERTS_DIR_PREFIX));
std::filesystem::create_directories(tempDir_);
writeFile(tempDir_ / kCA_CERT_FILENAME, kCA_CERT_CONTENT);