diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml new file mode 100644 index 0000000..a577dd8 --- /dev/null +++ b/.gitea/workflows/release.yml @@ -0,0 +1,90 @@ +name: Release + +on: + push: + tags: + - "v*" + workflow_dispatch: + +jobs: + release: + runs-on: echoion-release-serial + permissions: + contents: write + steps: + - name: Check out VoidLibrary + uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Check out pinned public release tooling + uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + repository: Void/Echoion + ref: ${{ vars.ECHOION_RELEASE_TOOLS_REF }} + path: .release-tools + ssh-key: ${{ secrets.ECHOION_RELEASE_TOOLS_SSH_KEY }} + persist-credentials: false + + - name: Verify immutable release inputs + shell: bash + run: | + set -euo pipefail + [[ "${{ vars.ECHOION_RELEASE_TOOLS_REF }}" =~ ^[0-9a-f]{40}$ ]] + test "$(git -C .release-tools rev-parse HEAD)" = \ + "${{ vars.ECHOION_RELEASE_TOOLS_REF }}" + [[ "$GITHUB_REF_TYPE" == "tag" ]] + [[ "$GITHUB_REF_NAME" =~ ^v([0-9]+\.[0-9]+\.[0-9]+)$ ]] + version="${BASH_REMATCH[1]}" + project_version="$( + sed -nE \ + 's/^project\(Void VERSION ([0-9]+\.[0-9]+\.[0-9]+).*$/\1/p' \ + CMakeLists.txt + )" + test "$version" = "$project_version" + + - name: Configure + run: | + cmake -S . -B build-release -G Ninja \ + -DCMAKE_BUILD_TYPE=Release \ + -DBUILD_SHARED_LIBS=ON \ + -DVOID_ENABLE_TESTING=ON \ + -DVOID_WARNINGS_AS_ERRORS=ON + + - name: Build and test + run: | + cmake --build build-release --parallel + ctest --test-dir build-release --output-on-failure + + - name: Install and package + shell: bash + run: | + set -euo pipefail + version="${GITHUB_REF_NAME#v}" + package="voidlibrary-${version}-linux-x86_64" + epoch="$(git show -s --format=%ct HEAD)" + cmake --install build-release \ + --prefix "$PWD/stage/$package" + mkdir -p dist + SOURCE_DATE_EPOCH="$epoch" \ + tar --sort=name --mtime="@$epoch" \ + --owner=0 --group=0 --numeric-owner \ + --zstd -cf "dist/$package.tar.zst" \ + -C stage "$package" + sha256sum "dist/$package.tar.zst" > dist/SHA256SUMS + + - name: Publish native Gitea release + env: + GITEA_TOKEN: ${{ secrets.GITEA_RELEASE_TOKEN }} + run: | + python3 .release-tools/scripts/gitea_release.py \ + --api-url "${{ vars.GITEA_API_URL }}" \ + publish \ + --owner Void \ + --repo VoidLibrary \ + --tag "$GITHUB_REF_NAME" \ + --target "$GITHUB_SHA" \ + --name "VoidLibrary ${GITHUB_REF_NAME#v}" \ + --body "Reproducible VoidLibrary SDK and shared-library package." \ + --artifacts dist diff --git a/include/Void/Data/Json.hpp b/include/Void/Data/Json.hpp index 5ef7fc6..dbf12f3 100644 --- a/include/Void/Data/Json.hpp +++ b/include/Void/Data/Json.hpp @@ -606,7 +606,8 @@ namespace Void::Json // (\uD800-\uDBFF followed by \uDC00-\uDFFF) // into one code point, so astral characters // (emoji, …) become valid 4-byte UTF-8 - // instead of two invalid encoded surrogates. + // instead of two invalid encoded + // surrogates. if (cp >= 0xD800 && cp <= 0xDBFF) { unsigned lo = 0; if (pos + 1 < src.size() && @@ -617,7 +618,8 @@ namespace Void::Json cp = 0x10000u + ((cp - 0xD800u) << 10) + (lo - 0xDC00u); - for (std::size_t i = 0; i < 6; ++i) { + for (std::size_t i = 0; i < 6; + ++i) { advance(); } } @@ -965,7 +967,8 @@ namespace Void::Json inline void escape_string(std::string& out, std::string_view s) { out += '"'; - for (const unsigned char c : s) { + for (const char value : s) { + const auto c = static_cast(value); switch (c) { case '"': out += "\\\""; diff --git a/include/Void/Data/StrictJson.hpp b/include/Void/Data/StrictJson.hpp new file mode 100644 index 0000000..4aad41d --- /dev/null +++ b/include/Void/Data/StrictJson.hpp @@ -0,0 +1,379 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Json::Strict +{ + inline constexpr std::size_t default_maximum_depth{64U}; + + struct ParseError { + std::size_t offset{}; + std::string message; + }; + + struct Value { + using Array = std::vector; + using Object = std::map>; + std::variant + value; + }; + + namespace Detail + { + struct ParseFailure { + ParseError error; + }; + + class Parser final + { + public: + + explicit Parser(const std::string_view input, + const std::size_t maximumDepth) + : input_{input}, maximumDepth_{maximumDepth} + { + } + + [[nodiscard]] Value parse() + { + skipWhitespace(); + Value result = parseValue(0U); + skipWhitespace(); + if (position_ != input_.size()) { + fail("trailing data"); + } + return result; + } + + private: + + [[noreturn]] void fail(const std::string_view message) const + { + throw ParseFailure{ + .error = + { + .offset = position_, + .message = std::string{message}, + }, + }; + } + + void skipWhitespace() + { + while (position_ < input_.size() && + (input_[position_] == ' ' || + input_[position_] == '\t' || + input_[position_] == '\r' || + input_[position_] == '\n')) { + ++position_; + } + } + + [[nodiscard]] char take() + { + if (position_ >= input_.size()) { + fail("unexpected end of input"); + } + return input_[position_++]; + } + + void expect(const char expected) + { + if (take() != expected) { + fail("unexpected character"); + } + } + + void expectLiteral(const std::string_view literal) + { + if (input_.substr(position_, literal.size()) != literal) { + fail("invalid literal"); + } + position_ += literal.size(); + } + + [[nodiscard]] static int hexValue(const char value) + { + if (value >= '0' && value <= '9') { + return value - '0'; + } + if (value >= 'a' && value <= 'f') { + return value - 'a' + 10; + } + if (value >= 'A' && value <= 'F') { + return value - 'A' + 10; + } + return -1; + } + + [[nodiscard]] std::uint32_t unicodeEscape() + { + std::uint32_t value{}; + for (int index{}; index < 4; ++index) { + const int digit = hexValue(take()); + if (digit < 0) { + fail("invalid unicode escape"); + } + value = value * 16U + static_cast(digit); + } + return value; + } + + static void appendUtf8(std::string& output, + const std::uint32_t codepoint) + { + if (codepoint <= 0x7FU) { + output.push_back(static_cast(codepoint)); + } else if (codepoint <= 0x7FFU) { + output.push_back( + static_cast(0xC0U | (codepoint >> 6U))); + output.push_back( + static_cast(0x80U | (codepoint & 0x3FU))); + } else if (codepoint <= 0xFFFFU) { + output.push_back( + static_cast(0xE0U | (codepoint >> 12U))); + output.push_back(static_cast( + 0x80U | ((codepoint >> 6U) & 0x3FU))); + output.push_back( + static_cast(0x80U | (codepoint & 0x3FU))); + } else { + output.push_back( + static_cast(0xF0U | (codepoint >> 18U))); + output.push_back(static_cast( + 0x80U | ((codepoint >> 12U) & 0x3FU))); + output.push_back(static_cast( + 0x80U | ((codepoint >> 6U) & 0x3FU))); + output.push_back( + static_cast(0x80U | (codepoint & 0x3FU))); + } + } + + [[nodiscard]] std::string parseString() + { + expect('"'); + std::string output; + while (true) { + const unsigned char value = + static_cast(take()); + if (value == '"') { + return output; + } + if (value < 0x20U) { + fail("control character in string"); + } + if (value != '\\') { + output.push_back(static_cast(value)); + continue; + } + switch (take()) { + case '"': + output.push_back('"'); + break; + case '\\': + output.push_back('\\'); + break; + case '/': + output.push_back('/'); + break; + case 'b': + output.push_back('\b'); + break; + case 'f': + output.push_back('\f'); + break; + case 'n': + output.push_back('\n'); + break; + case 'r': + output.push_back('\r'); + break; + case 't': + output.push_back('\t'); + break; + case 'u': + { + std::uint32_t codepoint = unicodeEscape(); + if (codepoint >= 0xD800U && + codepoint <= 0xDBFFU) { + if (take() != '\\' || take() != 'u') { + fail("missing low surrogate"); + } + const std::uint32_t low = + unicodeEscape(); + if (low < 0xDC00U || low > 0xDFFFU) { + fail("invalid low surrogate"); + } + codepoint = + 0x10000U + + ((codepoint - 0xD800U) << 10U) + + low - 0xDC00U; + } else if (codepoint >= 0xDC00U && + codepoint <= 0xDFFFU) { + fail("unexpected low surrogate"); + } + appendUtf8(output, codepoint); + break; + } + default: + fail("invalid string escape"); + } + } + } + + [[nodiscard]] Value parseNumber() + { + const std::size_t start = position_; + if (input_[position_] == '-') { + ++position_; + } + if (position_ >= input_.size()) { + fail("incomplete number"); + } + if (input_[position_] == '0') { + ++position_; + } else { + if (input_[position_] < '1' || + input_[position_] > '9') { + fail("invalid number"); + } + while (position_ < input_.size() && + input_[position_] >= '0' && + input_[position_] <= '9') { + ++position_; + } + } + if (position_ < input_.size() && + (input_[position_] == '.' || input_[position_] == 'e' || + input_[position_] == 'E')) { + fail("floating-point numbers are not supported"); + } + std::int64_t value{}; + const auto result = + std::from_chars(input_.data() + start, + input_.data() + position_, value); + if (result.ec != std::errc{} || + result.ptr != input_.data() + position_) { + fail("integer is out of range"); + } + return Value{value}; + } + + [[nodiscard]] Value parseArray(const std::size_t depth) + { + expect('['); + skipWhitespace(); + Value::Array result; + if (position_ < input_.size() && input_[position_] == ']') { + ++position_; + return Value{std::move(result)}; + } + while (true) { + result.push_back(parseValue(depth + 1U)); + skipWhitespace(); + const char separator = take(); + if (separator == ']') { + return Value{std::move(result)}; + } + if (separator != ',') { + fail("array requires comma or closing bracket"); + } + skipWhitespace(); + } + } + + [[nodiscard]] Value parseObject(const std::size_t depth) + { + expect('{'); + skipWhitespace(); + Value::Object result; + if (position_ < input_.size() && input_[position_] == '}') { + ++position_; + return Value{std::move(result)}; + } + while (true) { + if (position_ >= input_.size() || + input_[position_] != '"') { + fail("object key must be a string"); + } + std::string key = parseString(); + skipWhitespace(); + expect(':'); + skipWhitespace(); + auto [iterator, inserted] = result.emplace( + std::move(key), parseValue(depth + 1U)); + static_cast(iterator); + if (!inserted) { + fail("duplicate object key"); + } + skipWhitespace(); + const char separator = take(); + if (separator == '}') { + return Value{std::move(result)}; + } + if (separator != ',') { + fail("object requires comma or closing brace"); + } + skipWhitespace(); + } + } + + [[nodiscard]] Value parseValue(const std::size_t depth) + { + if (depth > maximumDepth_ || position_ >= input_.size()) { + fail("nesting limit or unexpected end of input"); + } + switch (input_[position_]) { + case '{': + return parseObject(depth); + case '[': + return parseArray(depth); + case '"': + return Value{parseString()}; + case 't': + expectLiteral("true"); + return Value{true}; + case 'f': + expectLiteral("false"); + return Value{false}; + case 'n': + expectLiteral("null"); + return Value{nullptr}; + default: + if (input_[position_] == '-' || + (input_[position_] >= '0' && + input_[position_] <= '9')) { + return parseNumber(); + } + fail("invalid value"); + } + } + + std::string_view input_; + std::size_t maximumDepth_; + std::size_t position_{}; + }; + } // namespace Detail + + [[nodiscard]] inline std::expected + parse(const std::string_view input, + const std::size_t maximumDepth = default_maximum_depth) + { + try { + return Detail::Parser{input, maximumDepth}.parse(); + } catch (const Detail::ParseFailure& failure) { + return std::unexpected{failure.error}; + } + } + +} // namespace Void::Json::Strict diff --git a/include/Void/Resilience/KeyedRateLimiter.hpp b/include/Void/Resilience/KeyedRateLimiter.hpp index 7bec73f..b336728 100644 --- a/include/Void/Resilience/KeyedRateLimiter.hpp +++ b/include/Void/Resilience/KeyedRateLimiter.hpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include @@ -25,29 +26,57 @@ namespace Void::Resilience public: using Clock = TokenBucket::Clock; + using TimePoint = TokenBucket::TimePoint; - // `capacity` is the burst size; `refill_per_sec` the sustained rate. - // The clock is shared with every bucket so tests stay deterministic. + // `capacity` is the burst size; `refill_per_sec` the sustained + // rate. `max_keys == 0` keeps the historic unbounded behaviour. + // Otherwise new keys are rejected at capacity until cleanup/reset + // frees space. The clock is shared with every bucket so tests stay + // deterministic. explicit KeyedRateLimiter(double capacity, double refill_per_sec, - Clock clock = default_clock()) + Clock clock = default_clock(), + std::size_t max_keys = 0) : capacity_{capacity}, rate_{refill_per_sec}, - clock_{std::move(clock)} + clock_{std::move(clock)}, max_keys_{max_keys} { + if (max_keys_ > 0) { + map_.reserve(max_keys_); + } } - // Consume `tokens` for `key`. Returns false (without consuming) when - // the key's bucket is exhausted. + // Consume `tokens` for `key`. Returns false (without consuming) + // when the key's bucket is exhausted. [[nodiscard]] bool allow(const Key& key, double tokens = 1.0) + { + return allow_at(key, clock_(), tokens); + } + + [[nodiscard]] bool allow_at(const Key& key, TimePoint now, + double tokens = 1.0) { std::lock_guard lock{mu_}; - return entry(key).bucket->try_acquire(tokens); + Entry* value = entry(key, now); + return value != nullptr && + value->bucket->try_acquire_at(now, tokens); } // Tokens currently available to `key` (creates the bucket if new). [[nodiscard]] double remaining(const Key& key) + { + return remaining_at(key, clock_()).value_or(0.0); + } + + // A missing optional means the key could not be created because the + // configured key cap is full. + [[nodiscard]] std::optional remaining_at(const Key& key, + TimePoint now) { std::lock_guard lock{mu_}; - return entry(key).bucket->available(); + Entry* value = entry(key, now); + if (value == nullptr) { + return std::nullopt; + } + return value->bucket->available_at(now); } // Forget a key's bucket (its next use starts full). @@ -57,15 +86,27 @@ namespace Void::Resilience map_.erase(key); } + void reset() + { + std::lock_guard lock{mu_}; + map_.clear(); + } + // Drop buckets not touched within `max_age`. Returns how many were // removed. Call periodically to bound memory for churny key spaces. std::size_t cleanup(std::chrono::steady_clock::duration max_age) { - const auto now = std::chrono::steady_clock::now(); + return cleanup_at(clock_(), max_age); + } + + std::size_t cleanup_at(TimePoint now, + std::chrono::steady_clock::duration max_age) + { std::lock_guard lock{mu_}; std::size_t removed = 0; for (auto it = map_.begin(); it != map_.end();) { - if (now - it->second.last_seen >= max_age) { + if (now >= it->second.last_seen && + now - it->second.last_seen >= max_age) { it = map_.erase(it); ++removed; } else { @@ -90,19 +131,20 @@ namespace Void::Resilience } struct Entry { - // TokenBucket owns a std::mutex (non-movable), so hold it by - // pointer to keep Entry movable for the hash map. + // TokenBucket owns a std::mutex (non-movable), so hold it + // by pointer to keep Entry movable for the hash map. std::unique_ptr bucket; std::chrono::steady_clock::time_point last_seen; }; - Entry& entry(const Key& key) + Entry* entry(const Key& key, TimePoint now) { - const auto now = std::chrono::steady_clock::now(); auto it = map_.find(key); if (it == map_.end()) { - it = map_ - .emplace(key, + if (max_keys_ > 0 && map_.size() >= max_keys_) { + return nullptr; + } + it = map_.emplace(key, Entry{std::make_unique( capacity_, rate_, clock_), now}) @@ -110,12 +152,13 @@ namespace Void::Resilience } else { it->second.last_seen = now; } - return it->second; + return &it->second; } double capacity_; double rate_; Clock clock_; + std::size_t max_keys_; mutable std::mutex mu_; std::unordered_map map_; }; diff --git a/include/Void/Resilience/RateLimiter.hpp b/include/Void/Resilience/RateLimiter.hpp index fca74b8..82706ab 100644 --- a/include/Void/Resilience/RateLimiter.hpp +++ b/include/Void/Resilience/RateLimiter.hpp @@ -37,7 +37,45 @@ namespace Void::Resilience [[nodiscard]] bool try_acquire(double tokens = 1.0) { std::lock_guard lock{mu_}; - refill(); + refill(clock_()); + return try_acquire_locked(tokens); + } + + // Explicit-time variant for callers that need a single + // deterministic clock value across several coordinated buckets. + [[nodiscard]] bool try_acquire_at(TimePoint now, + double tokens = 1.0) + { + std::lock_guard lock{mu_}; + refill(now); + return try_acquire_locked(tokens); + } + + // Current token count after refilling for elapsed time. + [[nodiscard]] double available() { return available_at(clock_()); } + + [[nodiscard]] double available_at(TimePoint now) + { + std::lock_guard lock{mu_}; + refill(now); + return tokens_; + } + + void reset() { reset_at(clock_()); } + + void reset_at(TimePoint now) + { + std::lock_guard lock{mu_}; + tokens_ = capacity_; + last_ = now; + } + + [[nodiscard]] double capacity() const noexcept { return capacity_; } + + private: + + [[nodiscard]] bool try_acquire_locked(double tokens) + { if (tokens_ >= tokens) { tokens_ -= tokens; return true; @@ -45,27 +83,15 @@ namespace Void::Resilience return false; } - // Current token count after refilling for elapsed time. - [[nodiscard]] double available() - { - std::lock_guard lock{mu_}; - refill(); - return tokens_; - } - - [[nodiscard]] double capacity() const noexcept { return capacity_; } - - private: - static Clock default_clock() { return [] { return std::chrono::steady_clock::now(); }; } - void refill() + void refill(TimePoint now) { - const auto now = clock_(); - const std::chrono::duration elapsed = now - last_; + const std::chrono::duration elapsed = + now > last_ ? now - last_ : TimePoint::duration::zero(); last_ = now; tokens_ = std::min(capacity_, tokens_ + elapsed.count() * rate_); diff --git a/include/Void/Security/Security.hpp b/include/Void/Security/Security.hpp index e160475..bc6ee22 100644 --- a/include/Void/Security/Security.hpp +++ b/include/Void/Security/Security.hpp @@ -2,9 +2,12 @@ #include +#include #include +#include #include #include +#include namespace Void::Security { @@ -15,6 +18,10 @@ namespace Void::Security enum class PasswordHashStrength { Interactive, Moderate, Sensitive }; inline constexpr std::size_t default_token_entropy_bytes = 32; + inline constexpr std::size_t secret_key_bytes = 32; + inline constexpr std::size_t secret_nonce_bytes = 24; + inline constexpr std::size_t secret_authentication_bytes = 16; + using SecretKey = std::array; /// Generate a URL-safe, unpadded token containing `entropy_bytes` of /// cryptographically secure randomness. @@ -43,4 +50,18 @@ namespace Void::Security verify_password(std::string_view password, std::string_view encoded_hash); + /// Generate a cryptographically random key for local secret encryption. + [[nodiscard]] Void::Result::Result random_secret_key(); + + /// Encrypt and authenticate bytes. The returned portable envelope is + /// nonce || ciphertext || authentication tag. + [[nodiscard]] Void::Result::Result> + seal_secret(std::span plaintext, + const SecretKey& key); + + /// Authenticate and decrypt an envelope produced by seal_secret. + [[nodiscard]] Void::Result::Result> + open_secret(std::span envelope, + const SecretKey& key); + } // namespace Void::Security diff --git a/src/Security/Security.cpp b/src/Security/Security.cpp index 564ba8a..2ee26d7 100644 --- a/src/Security/Security.cpp +++ b/src/Security/Security.cpp @@ -175,4 +175,76 @@ namespace Void::Security static_cast(password.size())) == 0; } + Void::Result::Result random_secret_key() + { + if (const auto initialized = ensure_sodium(); !initialized) { + return Void::Result::fail(std::move(initialized).error()); + } + + static_assert(secret_key_bytes == crypto_secretbox_KEYBYTES); + SecretKey key{}; + crypto_secretbox_keygen(key.data()); + return key; + } + + Void::Result::Result> + seal_secret(std::span plaintext, + const SecretKey& key) + { + if (const auto initialized = ensure_sodium(); !initialized) { + return Void::Result::fail(std::move(initialized).error()); + } + static_assert(secret_nonce_bytes == crypto_secretbox_NONCEBYTES); + static_assert(secret_authentication_bytes == crypto_secretbox_MACBYTES); + if (plaintext.size() > std::numeric_limits::max() - + secret_nonce_bytes - + secret_authentication_bytes) { + return Void::Result::fail( + "Security::seal_secret: plaintext is too large"); + } + + std::vector envelope(secret_nonce_bytes + + secret_authentication_bytes + + plaintext.size()); + auto* nonce = envelope.data(); + auto* ciphertext = nonce + secret_nonce_bytes; + randombytes_buf(nonce, secret_nonce_bytes); + if (crypto_secretbox_easy( + ciphertext, plaintext.data(), + static_cast(plaintext.size()), nonce, + key.data()) != 0) { + return Void::Result::fail( + "Security::seal_secret: encryption failed"); + } + return envelope; + } + + Void::Result::Result> + open_secret(std::span envelope, + const SecretKey& key) + { + if (const auto initialized = ensure_sodium(); !initialized) { + return Void::Result::fail(std::move(initialized).error()); + } + if (envelope.size() < + secret_nonce_bytes + secret_authentication_bytes) { + return Void::Result::fail( + "Security::open_secret: envelope is truncated"); + } + + const auto* nonce = envelope.data(); + const auto* ciphertext = nonce + secret_nonce_bytes; + const auto ciphertext_size = envelope.size() - secret_nonce_bytes; + std::vector plaintext(ciphertext_size - + secret_authentication_bytes); + if (crypto_secretbox_open_easy( + plaintext.data(), ciphertext, + static_cast(ciphertext_size), nonce, + key.data()) != 0) { + return Void::Result::fail( + "Security::open_secret: authentication failed"); + } + return plaintext; + } + } // namespace Void::Security diff --git a/tests/standalone/Data/StrictJson.cpp b/tests/standalone/Data/StrictJson.cpp new file mode 100644 index 0000000..bf3280b --- /dev/null +++ b/tests/standalone/Data/StrictJson.cpp @@ -0,0 +1,41 @@ +#include +#include +#include + +#include +#include +#include + +Void::Testing::Test strict_json_preserves_signed_64_bit_integers() +{ + const auto result = Void::Json::Strict::parse( + R"({"minimum":-9223372036854775808,"maximum":9223372036854775807})"); + Void::Testing::require(result.has_value()); + const auto* object = + std::get_if(&result->value); + Void::Testing::require(object != nullptr); + Void::Testing::expect_eq( + std::get(object->at("minimum").value), INT64_MIN); + Void::Testing::expect_eq( + std::get(object->at("maximum").value), INT64_MAX); +} + +Void::Testing::Test strict_json_rejects_duplicates_floats_and_deep_inputs() +{ + Void::Testing::expect( + !Void::Json::Strict::parse(R"({"key":1,"key":2})").has_value()); + Void::Testing::expect( + !Void::Json::Strict::parse(R"({"value":1.5})").has_value()); + Void::Testing::expect( + !Void::Json::Strict::parse("[[[0]]]", 1U).has_value()); +} + +Void::Testing::Test strict_json_decodes_valid_unicode_pairs() +{ + const auto result = Void::Json::Strict::parse(R"("\uD83D\uDE03")"); + Void::Testing::require(result.has_value()); + Void::Testing::expect_eq(std::get(result->value), + std::string{"\xF0\x9F\x98\x83"}); + Void::Testing::expect( + !Void::Json::Strict::parse(R"("\uD83D")").has_value()); +} diff --git a/tests/standalone/Resilience/KeyedRateLimiter.cpp b/tests/standalone/Resilience/KeyedRateLimiter.cpp index 451578d..13938f5 100644 --- a/tests/standalone/Resilience/KeyedRateLimiter.cpp +++ b/tests/standalone/Resilience/KeyedRateLimiter.cpp @@ -35,7 +35,7 @@ namespace Void::Testing::expect(rl.allow(1)); Void::Testing::expect(rl.allow(1)); Void::Testing::expect(!rl.allow(1)); // key 1 exhausted - Void::Testing::expect(rl.allow(2)); // key 2 still full + Void::Testing::expect(rl.allow(2)); // key 2 still full } Test refills_per_key_over_time() @@ -60,16 +60,43 @@ namespace Test cleanup_drops_stale_keys() { - KeyedRateLimiter rl{1.0, 1.0}; + ManualClock clk; + KeyedRateLimiter rl{1.0, 1.0, clk.fn()}; (void)rl.allow(1); (void)rl.allow(2); Void::Testing::expect_eq(rl.tracked(), std::size_t{2}); // Nothing is older than an hour yet. Void::Testing::expect_eq(rl.cleanup(1h), std::size_t{0}); Void::Testing::expect_eq(rl.tracked(), std::size_t{2}); - // Everything is older than 0ns. - Void::Testing::expect_eq(rl.cleanup(0ns), std::size_t{2}); + clk.advance(2h); + Void::Testing::expect_eq(rl.cleanup(1h), std::size_t{2}); Void::Testing::expect_eq(rl.tracked(), std::size_t{0}); } + + Test bounds_untrusted_key_cardinality() + { + ManualClock clk; + KeyedRateLimiter rl{2.0, 0.0, clk.fn(), + std::size_t{2}}; + Void::Testing::expect(rl.allow("a")); + Void::Testing::expect(rl.allow("b")); + Void::Testing::expect(!rl.allow("c")); + Void::Testing::expect_eq(rl.tracked(), std::size_t{2}); + clk.advance(2min); + Void::Testing::expect_eq(rl.cleanup(1min), std::size_t{2}); + Void::Testing::expect(rl.allow("c")); + } + + Test explicit_time_is_shared_by_tracking_and_refill() + { + ManualClock clk; + KeyedRateLimiter rl{1.0, 1.0, clk.fn(), std::size_t{1}}; + const TP start = *clk.now; + Void::Testing::expect(rl.allow_at(1, start)); + Void::Testing::expect(!rl.allow_at(1, start)); + Void::Testing::expect(rl.allow_at(1, start + 1s)); + Void::Testing::expect_eq(rl.cleanup_at(start + 3s, 1s), + std::size_t{1}); + } }; } // namespace diff --git a/tests/standalone/Security/Security.cpp b/tests/standalone/Security/Security.cpp index c797a0d..7b3ce89 100644 --- a/tests/standalone/Security/Security.cpp +++ b/tests/standalone/Security/Security.cpp @@ -3,6 +3,7 @@ #include #include +#include namespace { @@ -91,5 +92,40 @@ namespace Void::Testing::expect(!*invalid); Void::Testing::expect(!*malformed); } + + Test sealed_secrets_round_trip_and_use_random_nonces() + { + auto key = Void::Security::random_secret_key(); + Void::Testing::require(key.has_value()); + const std::vector plaintext{'s', 'e', 'c', + 'r', 'e', 't'}; + auto first = Void::Security::seal_secret(plaintext, *key); + auto second = Void::Security::seal_secret(plaintext, *key); + Void::Testing::require(first.has_value()); + Void::Testing::require(second.has_value()); + Void::Testing::expect_ne(*first, *second); + + auto opened = Void::Security::open_secret(*first, *key); + Void::Testing::require(opened.has_value()); + Void::Testing::expect_eq(*opened, plaintext); + } + + Test sealed_secrets_reject_tampering_and_wrong_keys() + { + auto key = Void::Security::random_secret_key(); + auto wrong = Void::Security::random_secret_key(); + Void::Testing::require(key.has_value()); + Void::Testing::require(wrong.has_value()); + const std::vector plaintext{'t', 'o', 'k', 'e', + 'n'}; + auto envelope = Void::Security::seal_secret(plaintext, *key); + Void::Testing::require(envelope.has_value()); + + auto wrong_key = Void::Security::open_secret(*envelope, *wrong); + Void::Testing::expect(!wrong_key.has_value()); + envelope->back() ^= 0x01U; + auto tampered = Void::Security::open_secret(*envelope, *key); + Void::Testing::expect(!tampered.has_value()); + } }; } // namespace